gun-eth 1.3.5 → 1.4.0
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +292 -77
- package/dist/gun-eth.cjs.js +2808 -0
- package/dist/gun-eth.esm.js +2806 -0
- package/dist/gun-eth.min.js +1 -0
- package/package.json +43 -4
- package/TUTORIAL.md +0 -103
- package/src/abis/SHINE.json +0 -262
- package/src/contracts/SHINE.sol +0 -52
- package/src/examples/eth2gun.html +0 -163
- package/src/examples/gun2eth.html +0 -164
- package/src/examples/shine.html +0 -256
- package/src/index.js +0 -533
@@ -0,0 +1,2808 @@
|
|
1
|
+
'use strict';
|
2
|
+
|
3
|
+
var require$$1 = require('gun/sea');
|
4
|
+
var require$$2 = require('ethers');
|
5
|
+
|
6
|
+
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
7
|
+
|
8
|
+
var gunEthBrowser = {exports: {}};
|
9
|
+
|
10
|
+
function commonjsRequire(path) {
|
11
|
+
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.');
|
12
|
+
}
|
13
|
+
|
14
|
+
var gun = {exports: {}};
|
15
|
+
|
16
|
+
gun.exports;
|
17
|
+
|
18
|
+
var hasRequiredGun;
|
19
|
+
|
20
|
+
function requireGun () {
|
21
|
+
if (hasRequiredGun) return gun.exports;
|
22
|
+
hasRequiredGun = 1;
|
23
|
+
(function (module) {
|
24
|
+
(function(){
|
25
|
+
|
26
|
+
/* UNBUILD */
|
27
|
+
function USE(arg, req){
|
28
|
+
return req? commonjsRequire(arg) : arg.slice? USE[R(arg)] : function(mod, path){
|
29
|
+
arg(mod = {exports: {}});
|
30
|
+
USE[R(path)] = mod.exports;
|
31
|
+
}
|
32
|
+
function R(p){
|
33
|
+
return p.split('/').slice(-1).toString().replace('.js','');
|
34
|
+
}
|
35
|
+
}
|
36
|
+
{ var MODULE = module; }
|
37
|
+
USE(function(module){
|
38
|
+
// Shim for generic javascript utilities.
|
39
|
+
String.random = function(l, c){
|
40
|
+
var s = '';
|
41
|
+
l = l || 24; // you are not going to make a 0 length random number, so no need to check type
|
42
|
+
c = c || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXZabcdefghijklmnopqrstuvwxyz';
|
43
|
+
while(l-- > 0){ s += c.charAt(Math.floor(Math.random() * c.length)); }
|
44
|
+
return s;
|
45
|
+
};
|
46
|
+
String.match = function(t, o){ var tmp, u;
|
47
|
+
if('string' !== typeof t){ return false }
|
48
|
+
if('string' == typeof o){ o = {'=': o}; }
|
49
|
+
o = o || {};
|
50
|
+
tmp = (o['='] || o['*'] || o['>'] || o['<']);
|
51
|
+
if(t === tmp){ return true }
|
52
|
+
if(u !== o['=']){ return false }
|
53
|
+
tmp = (o['*'] || o['>']);
|
54
|
+
if(t.slice(0, (tmp||'').length) === tmp){ return true }
|
55
|
+
if(u !== o['*']){ return false }
|
56
|
+
if(u !== o['>'] && u !== o['<']){
|
57
|
+
return (t >= o['>'] && t <= o['<'])? true : false;
|
58
|
+
}
|
59
|
+
if(u !== o['>'] && t >= o['>']){ return true }
|
60
|
+
if(u !== o['<'] && t <= o['<']){ return true }
|
61
|
+
return false;
|
62
|
+
};
|
63
|
+
String.hash = function(s, c){ // via SO
|
64
|
+
if(typeof s !== 'string'){ return }
|
65
|
+
c = c || 0; // CPU schedule hashing by
|
66
|
+
if(!s.length){ return c }
|
67
|
+
for(var i=0,l=s.length,n; i<l; ++i){
|
68
|
+
n = s.charCodeAt(i);
|
69
|
+
c = ((c<<5)-c)+n;
|
70
|
+
c |= 0;
|
71
|
+
}
|
72
|
+
return c;
|
73
|
+
};
|
74
|
+
var has = Object.prototype.hasOwnProperty;
|
75
|
+
Object.plain = function(o){ return o? (o instanceof Object && o.constructor === Object) || Object.prototype.toString.call(o).match(/^\[object (\w+)\]$/)[1] === 'Object' : false };
|
76
|
+
Object.empty = function(o, n){
|
77
|
+
for(var k in o){ if(has.call(o, k) && (!n || -1==n.indexOf(k))){ return false } }
|
78
|
+
return true;
|
79
|
+
};
|
80
|
+
Object.keys = Object.keys || function(o){
|
81
|
+
var l = [];
|
82
|
+
for(var k in o){ if(has.call(o, k)){ l.push(k); } }
|
83
|
+
return l;
|
84
|
+
}
|
85
|
+
;(function(){
|
86
|
+
var u, sT = setTimeout, l = 0, c = 0
|
87
|
+
, sI = (typeof setImmediate !== ''+u && setImmediate) || (function(c,f){
|
88
|
+
if(typeof MessageChannel == ''+u){ return sT }
|
89
|
+
(c = new MessageChannel()).port1.onmessage = function(e){ ''==e.data && f(); };
|
90
|
+
return function(q){ f=q;c.port2.postMessage(''); }
|
91
|
+
}()), check = sT.check = sT.check || (typeof performance !== ''+u && performance)
|
92
|
+
|| {now: function(){ return +new Date }};
|
93
|
+
sT.hold = sT.hold || 9; // half a frame benchmarks faster than < 1ms?
|
94
|
+
sT.poll = sT.poll || function(f){
|
95
|
+
if((sT.hold >= (check.now() - l)) && c++ < 3333){ f(); return }
|
96
|
+
sI(function(){ l = check.now(); f(); },c=0);
|
97
|
+
};
|
98
|
+
}());
|
99
|
+
(function(){ // Too many polls block, this "threads" them in turns over a single thread in time.
|
100
|
+
var sT = setTimeout, t = sT.turn = sT.turn || function(f){ 1 == s.push(f) && p(T); }
|
101
|
+
, s = t.s = [], p = sT.poll, i = 0, f, T = function(){
|
102
|
+
if(f = s[i++]){ f(); }
|
103
|
+
if(i == s.length || 99 == i){
|
104
|
+
s = t.s = s.slice(i);
|
105
|
+
i = 0;
|
106
|
+
}
|
107
|
+
if(s.length){ p(T); }
|
108
|
+
};
|
109
|
+
}());
|
110
|
+
(function(){
|
111
|
+
var u, sT = setTimeout, T = sT.turn;
|
112
|
+
(sT.each = sT.each || function(l,f,e,S){ S = S || 9; (function t(s,L,r){
|
113
|
+
if(L = (s = (l||[]).splice(0,S)).length){
|
114
|
+
for(var i = 0; i < L; i++){
|
115
|
+
if(u !== (r = f(s[i]))){ break }
|
116
|
+
}
|
117
|
+
if(u === r){ T(t); return }
|
118
|
+
} e && e(r);
|
119
|
+
}());})();
|
120
|
+
}());
|
121
|
+
})(USE, './shim');
|
122
|
+
USE(function(module){
|
123
|
+
// On event emitter generic javascript utility.
|
124
|
+
module.exports = function onto(tag, arg, as){
|
125
|
+
if(!tag){ return {to: onto} }
|
126
|
+
var u, f = 'function' == typeof arg, tag = (this.tag || (this.tag = {}))[tag] || f && (
|
127
|
+
this.tag[tag] = {tag: tag, to: onto._ = { next: function(arg){ var tmp;
|
128
|
+
if(tmp = this.to){ tmp.next(arg); }
|
129
|
+
}}});
|
130
|
+
if(f){
|
131
|
+
var be = {
|
132
|
+
off: onto.off ||
|
133
|
+
(onto.off = function(){
|
134
|
+
if(this.next === onto._.next){ return !0 }
|
135
|
+
if(this === this.the.last){
|
136
|
+
this.the.last = this.back;
|
137
|
+
}
|
138
|
+
this.to.back = this.back;
|
139
|
+
this.next = onto._.next;
|
140
|
+
this.back.to = this.to;
|
141
|
+
if(this.the.last === this.the){
|
142
|
+
delete this.on.tag[this.the.tag];
|
143
|
+
}
|
144
|
+
}),
|
145
|
+
to: onto._,
|
146
|
+
next: arg,
|
147
|
+
the: tag,
|
148
|
+
on: this,
|
149
|
+
as: as,
|
150
|
+
};
|
151
|
+
(be.back = tag.last || tag).to = be;
|
152
|
+
return tag.last = be;
|
153
|
+
}
|
154
|
+
if((tag = tag.to) && u !== arg){ tag.next(arg); }
|
155
|
+
return tag;
|
156
|
+
};
|
157
|
+
})(USE, './onto');
|
158
|
+
USE(function(module){
|
159
|
+
// Valid values are a subset of JSON: null, binary, number (!Infinity), text,
|
160
|
+
// or a soul relation. Arrays need special algorithms to handle concurrency,
|
161
|
+
// so they are not supported directly. Use an extension that supports them if
|
162
|
+
// needed but research their problems first.
|
163
|
+
module.exports = function (v) {
|
164
|
+
// "deletes", nulling out keys.
|
165
|
+
return v === null ||
|
166
|
+
"string" === typeof v ||
|
167
|
+
"boolean" === typeof v ||
|
168
|
+
// we want +/- Infinity to be, but JSON does not support it, sad face.
|
169
|
+
// can you guess what v === v checks for? ;)
|
170
|
+
("number" === typeof v && v != Infinity && v != -Infinity && v === v) ||
|
171
|
+
(!!v && "string" == typeof v["#"] && Object.keys(v).length === 1 && v["#"]);
|
172
|
+
};
|
173
|
+
})(USE, './valid');
|
174
|
+
USE(function(module){
|
175
|
+
USE('./shim');
|
176
|
+
function State(){
|
177
|
+
var t = +new Date;
|
178
|
+
if(last < t){
|
179
|
+
return N = 0, last = t + State.drift;
|
180
|
+
}
|
181
|
+
return last = t + ((N += 1) / D) + State.drift;
|
182
|
+
}
|
183
|
+
State.drift = 0;
|
184
|
+
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).
|
185
|
+
State.is = function(n, k, o){ // convenience function to get the state on a key on a node and return it.
|
186
|
+
var tmp = (k && n && n._ && n._['>']) || o;
|
187
|
+
if(!tmp){ return }
|
188
|
+
return ('number' == typeof (tmp = tmp[k]))? tmp : NI;
|
189
|
+
};
|
190
|
+
State.ify = function(n, k, s, v, soul){ // put a key's state on a node.
|
191
|
+
(n = n || {})._ = n._ || {}; // safety check or init.
|
192
|
+
if(soul){ n._['#'] = soul; } // set a soul if specified.
|
193
|
+
var tmp = n._['>'] || (n._['>'] = {}); // grab the states data.
|
194
|
+
if(u !== k && k !== '_'){
|
195
|
+
if('number' == typeof s){ tmp[k] = s; } // add the valid state.
|
196
|
+
if(u !== v){ n[k] = v; } // Note: Not its job to check for valid values!
|
197
|
+
}
|
198
|
+
return n;
|
199
|
+
};
|
200
|
+
module.exports = State;
|
201
|
+
})(USE, './state');
|
202
|
+
USE(function(module){
|
203
|
+
USE('./shim');
|
204
|
+
function Dup(opt){
|
205
|
+
var dup = {s:{}}, s = dup.s;
|
206
|
+
opt = opt || {max: 999, age: 1000 * 9};//*/ 1000 * 9 * 3};
|
207
|
+
dup.check = function(id){
|
208
|
+
if(!s[id]){ return false }
|
209
|
+
return dt(id);
|
210
|
+
};
|
211
|
+
var dt = dup.track = function(id){
|
212
|
+
var it = s[id] || (s[id] = {});
|
213
|
+
it.was = dup.now = +new Date;
|
214
|
+
if(!dup.to){ dup.to = setTimeout(dup.drop, opt.age + 9); }
|
215
|
+
if(dt.ed){ dt.ed(id); }
|
216
|
+
return it;
|
217
|
+
};
|
218
|
+
dup.drop = function(age){
|
219
|
+
dup.to = null;
|
220
|
+
dup.now = +new Date;
|
221
|
+
var l = Object.keys(s);
|
222
|
+
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
|
223
|
+
setTimeout.each(l, function(id){ var it = s[id]; // TODO: .keys( is slow?
|
224
|
+
if(it && (age || opt.age) > (dup.now - it.was)){ return }
|
225
|
+
delete s[id];
|
226
|
+
},0,99);
|
227
|
+
};
|
228
|
+
return dup;
|
229
|
+
}
|
230
|
+
module.exports = Dup;
|
231
|
+
})(USE, './dup');
|
232
|
+
USE(function(module){
|
233
|
+
// request / response module, for asking and acking messages.
|
234
|
+
USE('./onto'); // depends upon onto!
|
235
|
+
module.exports = function ask(cb, as){
|
236
|
+
if(!this.on){ return }
|
237
|
+
var lack = (this.opt||{}).lack || 9000;
|
238
|
+
if(!('function' == typeof cb)){
|
239
|
+
if(!cb){ return }
|
240
|
+
var id = cb['#'] || cb, tmp = (this.tag||'')[id];
|
241
|
+
if(!tmp){ return }
|
242
|
+
if(as){
|
243
|
+
tmp = this.on(id, as);
|
244
|
+
clearTimeout(tmp.err);
|
245
|
+
tmp.err = setTimeout(function(){ tmp.off(); }, lack);
|
246
|
+
}
|
247
|
+
return true;
|
248
|
+
}
|
249
|
+
var id = (as && as['#']) || random(9);
|
250
|
+
if(!cb){ return id }
|
251
|
+
var to = this.on(id, cb, as);
|
252
|
+
to.err = to.err || setTimeout(function(){ to.off();
|
253
|
+
to.next({err: "Error: No ACK yet.", lack: true});
|
254
|
+
}, lack);
|
255
|
+
return id;
|
256
|
+
};
|
257
|
+
var random = String.random || function(){ return Math.random().toString(36).slice(2) };
|
258
|
+
})(USE, './ask');
|
259
|
+
USE(function(module){
|
260
|
+
|
261
|
+
function Gun(o){
|
262
|
+
if(o instanceof Gun){ return (this._ = {$: this}).$ }
|
263
|
+
if(!(this instanceof Gun)){ return new Gun(o) }
|
264
|
+
return Gun.create(this._ = {$: this, opt: o});
|
265
|
+
}
|
266
|
+
|
267
|
+
Gun.is = function($){ return ($ instanceof Gun) || ($ && $._ && ($ === $._.$)) || false };
|
268
|
+
|
269
|
+
Gun.version = 0.2020;
|
270
|
+
|
271
|
+
Gun.chain = Gun.prototype;
|
272
|
+
Gun.chain.toJSON = function(){};
|
273
|
+
|
274
|
+
USE('./shim');
|
275
|
+
Gun.valid = USE('./valid');
|
276
|
+
Gun.state = USE('./state');
|
277
|
+
Gun.on = USE('./onto');
|
278
|
+
Gun.dup = USE('./dup');
|
279
|
+
Gun.ask = USE('./ask');
|
280
|
+
(function(){
|
281
|
+
Gun.create = function(at){
|
282
|
+
at.root = at.root || at;
|
283
|
+
at.graph = at.graph || {};
|
284
|
+
at.on = at.on || Gun.on;
|
285
|
+
at.ask = at.ask || Gun.ask;
|
286
|
+
at.dup = at.dup || Gun.dup();
|
287
|
+
var gun = at.$.opt(at.opt);
|
288
|
+
if(!at.once){
|
289
|
+
at.on('in', universe, at);
|
290
|
+
at.on('out', universe, at);
|
291
|
+
at.on('put', map, at);
|
292
|
+
Gun.on('create', at);
|
293
|
+
at.on('create', at);
|
294
|
+
}
|
295
|
+
at.once = 1;
|
296
|
+
return gun;
|
297
|
+
};
|
298
|
+
function universe(msg){
|
299
|
+
// TODO: BUG! msg.out = null being set!
|
300
|
+
//if(!F){ var eve = this; setTimeout(function(){ universe.call(eve, msg,1) },Math.random() * 100);return; } // ADD F TO PARAMS!
|
301
|
+
if(!msg){ return }
|
302
|
+
if(msg.out === universe){ this.to.next(msg); return }
|
303
|
+
var eve = this, as = eve.as, at = as.at || as, gun = at.$, dup = at.dup, tmp, DBG = msg.DBG;
|
304
|
+
(tmp = msg['#']) || (tmp = msg['#'] = text_rand(9));
|
305
|
+
if(dup.check(tmp)){ return } dup.track(tmp);
|
306
|
+
tmp = msg._; msg._ = ('function' == typeof tmp)? tmp : function(){};
|
307
|
+
(msg.$ && (msg.$ === (msg.$._||'').$)) || (msg.$ = gun);
|
308
|
+
if(msg['@'] && !msg.put){ ack(msg); }
|
309
|
+
if(!at.ask(msg['@'], msg)){ // is this machine listening for an ack?
|
310
|
+
DBG && (DBG.u = +new Date);
|
311
|
+
if(msg.put){ put(msg); return } else
|
312
|
+
if(msg.get){ Gun.on.get(msg, gun); }
|
313
|
+
}
|
314
|
+
DBG && (DBG.uc = +new Date);
|
315
|
+
eve.to.next(msg);
|
316
|
+
DBG && (DBG.ua = +new Date);
|
317
|
+
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.
|
318
|
+
msg.out = universe; at.on('out', msg);
|
319
|
+
DBG && (DBG.ue = +new Date);
|
320
|
+
}
|
321
|
+
function put(msg){
|
322
|
+
if(!msg){ return }
|
323
|
+
var ctx = msg._||'', root = ctx.root = ((ctx.$ = msg.$||'')._||'').root;
|
324
|
+
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 @.
|
325
|
+
msg.out = universe;
|
326
|
+
root.on('out', msg);
|
327
|
+
return;
|
328
|
+
}
|
329
|
+
ctx.latch = root.hatch; ctx.match = root.hatch = [];
|
330
|
+
var put = msg.put;
|
331
|
+
var DBG = ctx.DBG = msg.DBG, S = +new Date; CT = CT || S;
|
332
|
+
if(put['#'] && put['.']){ /*root && root.on('put', msg);*/ return } // TODO: BUG! This needs to call HAM instead.
|
333
|
+
DBG && (DBG.p = S);
|
334
|
+
ctx['#'] = msg['#'];
|
335
|
+
ctx.msg = msg;
|
336
|
+
ctx.all = 0;
|
337
|
+
ctx.stun = 1;
|
338
|
+
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.
|
339
|
+
console.STAT && console.STAT(S, ((DBG||ctx).pk = +new Date) - S, 'put sort');
|
340
|
+
var ni = 0, nj, kl, soul, node, states, err, tmp;
|
341
|
+
(function pop(o){
|
342
|
+
if(nj != ni){ nj = ni;
|
343
|
+
if(!(soul = nl[ni])){
|
344
|
+
console.STAT && console.STAT(S, ((DBG||ctx).pd = +new Date) - S, 'put');
|
345
|
+
fire(ctx);
|
346
|
+
return;
|
347
|
+
}
|
348
|
+
if(!(node = put[soul])){ err = ERR+cut(soul)+"no node."; } else
|
349
|
+
if(!(tmp = node._)){ err = ERR+cut(soul)+"no meta."; } else
|
350
|
+
if(soul !== tmp['#']){ err = ERR+cut(soul)+"soul not same."; } else
|
351
|
+
if(!(states = tmp['>'])){ err = ERR+cut(soul)+"no state."; }
|
352
|
+
kl = Object.keys(node||{}); // TODO: .keys( is slow
|
353
|
+
}
|
354
|
+
if(err){
|
355
|
+
msg.err = ctx.err = err; // invalid data should error and stun the message.
|
356
|
+
fire(ctx);
|
357
|
+
//console.log("handle error!", err) // handle!
|
358
|
+
return;
|
359
|
+
}
|
360
|
+
var i = 0, key; o = o || 0;
|
361
|
+
while(o++ < 9 && (key = kl[i++])){
|
362
|
+
if('_' === key){ continue }
|
363
|
+
var val = node[key], state = states[key];
|
364
|
+
if(u === state){ err = ERR+cut(key)+"on"+cut(soul)+"no state."; break }
|
365
|
+
if(!valid(val)){ err = ERR+cut(key)+"on"+cut(soul)+"bad "+(typeof val)+cut(val); break }
|
366
|
+
//ctx.all++; //ctx.ack[soul+key] = '';
|
367
|
+
ham(val, key, soul, state, msg);
|
368
|
+
++C; // courtesy count;
|
369
|
+
}
|
370
|
+
if((kl = kl.slice(i)).length){ turn(pop); return }
|
371
|
+
++ni; kl = null; pop(o);
|
372
|
+
}());
|
373
|
+
} Gun.on.put = put;
|
374
|
+
// TODO: MARK!!! clock below, reconnect sync, SEA certify wire merge, User.auth taking multiple times, // msg put, put, say ack, hear loop...
|
375
|
+
// WASIS BUG! local peer not ack. .off other people: .open
|
376
|
+
function ham(val, key, soul, state, msg){
|
377
|
+
var ctx = msg._||'', root = ctx.root, graph = root.graph, tmp;
|
378
|
+
var vertex = graph[soul] || empty, was = state_is(vertex, key, 1), known = vertex[key];
|
379
|
+
|
380
|
+
var DBG = ctx.DBG; if(tmp = console.STAT){ if(!graph[soul] || !known){ tmp.has = (tmp.has || 0) + 1; } }
|
381
|
+
|
382
|
+
var now = State();
|
383
|
+
if(state > now){
|
384
|
+
setTimeout(function(){ ham(val, key, soul, state, msg); }, (tmp = state - now) > MD? MD : tmp); // Max Defer 32bit. :(
|
385
|
+
console.STAT && console.STAT(((DBG||ctx).Hf = +new Date), tmp, 'future');
|
386
|
+
return;
|
387
|
+
}
|
388
|
+
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?)
|
389
|
+
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.
|
390
|
+
if(state === was && (val === known || L(val) <= L(known))){ /*console.log("same");*/ /*same;*/ if(!ctx.miss){ return } } // same
|
391
|
+
}
|
392
|
+
ctx.stun++; // TODO: 'forget' feature in SEA tied to this, bad approach, but hacked in for now. Any changes here must update there.
|
393
|
+
var aid = msg['#']+ctx.all++, id = {toString: function(){ return aid }, _: ctx}; id.toJSON = id.toString; // this *trick* makes it compatible between old & new versions.
|
394
|
+
root.dup.track(id)['#'] = msg['#']; // fixes new OK acks for RPC like RTC.
|
395
|
+
DBG && (DBG.ph = DBG.ph || +new Date);
|
396
|
+
root.on('put', {'#': id, '@': msg['@'], put: {'#': soul, '.': key, ':': val, '>': state}, ok: msg.ok, _: ctx});
|
397
|
+
}
|
398
|
+
function map(msg){
|
399
|
+
var DBG; if(DBG = (msg._||'').DBG){ DBG.pa = +new Date; DBG.pm = DBG.pm || +new Date;}
|
400
|
+
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;
|
401
|
+
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.
|
402
|
+
//var bytes = ((graph[soul]||'')[key]||'').length||1;
|
403
|
+
graph[soul] = state_ify(graph[soul], key, state, val, soul);
|
404
|
+
if(tmp = (root.next||'')[soul]){
|
405
|
+
//tmp.bytes = (tmp.bytes||0) + ((val||'').length||1) - bytes;
|
406
|
+
//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") }
|
407
|
+
tmp.on('in', msg);
|
408
|
+
}
|
409
|
+
fire(ctx);
|
410
|
+
eve.to.next(msg);
|
411
|
+
}
|
412
|
+
function fire(ctx, msg){ var root;
|
413
|
+
if(ctx.stop){ return }
|
414
|
+
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.
|
415
|
+
ctx.stop = 1;
|
416
|
+
if(!(root = ctx.root)){ return }
|
417
|
+
var tmp = ctx.match; tmp.end = 1;
|
418
|
+
if(tmp === root.hatch){ if(!(tmp = ctx.latch) || tmp.end){ delete root.hatch; } else { root.hatch = tmp; } }
|
419
|
+
ctx.hatch && ctx.hatch(); // TODO: rename/rework how put & this interact.
|
420
|
+
setTimeout.each(ctx.match, function(cb){cb && cb();});
|
421
|
+
if(!(msg = ctx.msg) || ctx.err || msg.err){ return }
|
422
|
+
msg.out = universe;
|
423
|
+
ctx.root.on('out', msg);
|
424
|
+
|
425
|
+
CF(); // courtesy check;
|
426
|
+
}
|
427
|
+
function ack(msg){ // aggregate ACKs.
|
428
|
+
var id = msg['@'] || '', ctx;
|
429
|
+
if(!(ctx = id._)){
|
430
|
+
var dup = (dup = msg.$) && (dup = dup._) && (dup = dup.root) && (dup = dup.dup);
|
431
|
+
if(!(dup = dup.check(id))){ return }
|
432
|
+
msg['@'] = dup['#'] || msg['@']; // This doesn't do anything anymore, backtrack it to something else?
|
433
|
+
return;
|
434
|
+
}
|
435
|
+
ctx.acks = (ctx.acks||0) + 1;
|
436
|
+
if(ctx.err = msg.err){
|
437
|
+
msg['@'] = ctx['#'];
|
438
|
+
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.
|
439
|
+
}
|
440
|
+
ctx.ok = msg.ok || ctx.ok;
|
441
|
+
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.
|
442
|
+
back(ctx);
|
443
|
+
}
|
444
|
+
function back(ctx){
|
445
|
+
if(!ctx || !ctx.root){ return }
|
446
|
+
if(ctx.stun || ctx.acks !== ctx.all){ return }
|
447
|
+
ctx.root.on('in', {'@': ctx['#'], err: ctx.err, ok: ctx.err? u : ctx.ok || {'':1}});
|
448
|
+
}
|
449
|
+
|
450
|
+
var ERR = "Error: Invalid graph!";
|
451
|
+
var cut = function(s){ return " '"+(''+s).slice(0,9)+"...' " };
|
452
|
+
var L = JSON.stringify, MD = 2147483647, State = Gun.state;
|
453
|
+
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;};}};
|
454
|
+
|
455
|
+
}());
|
456
|
+
(function(){
|
457
|
+
Gun.on.get = function(msg, gun){
|
458
|
+
var root = gun._, get = msg.get, soul = get['#'], node = root.graph[soul], has = get['.'];
|
459
|
+
var next = root.next || (root.next = {}), at = next[soul];
|
460
|
+
|
461
|
+
// TODO: Azarattum bug, what is in graph is not same as what is in next. Fix!
|
462
|
+
|
463
|
+
// queue concurrent GETs?
|
464
|
+
// TODO: consider tagging original message into dup for DAM.
|
465
|
+
// 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.
|
466
|
+
// TODO: Moving quick hacks fixing these things to axe for now.
|
467
|
+
// TODO: a lot of GET #foo then GET #foo."" happening, why?
|
468
|
+
// TODO: DAM's ## hash check, on same get ACK, producing multiple replies still, maybe JSON vs YSON?
|
469
|
+
// TMP note for now: viMZq1slG was chat LEX query #.
|
470
|
+
/*if(gun !== (tmp = msg.$) && (tmp = (tmp||'')._)){
|
471
|
+
if(tmp.Q){ tmp.Q[msg['#']] = ''; return } // chain does not need to ask for it again.
|
472
|
+
tmp.Q = {};
|
473
|
+
}*/
|
474
|
+
/*if(u === has){
|
475
|
+
if(at.Q){
|
476
|
+
//at.Q[msg['#']] = '';
|
477
|
+
//return;
|
478
|
+
}
|
479
|
+
at.Q = {};
|
480
|
+
}*/
|
481
|
+
var ctx = msg._||{}, DBG = ctx.DBG = msg.DBG;
|
482
|
+
DBG && (DBG.g = +new Date);
|
483
|
+
//console.log("GET:", get, node, has, at);
|
484
|
+
//if(!node && !at){ return root.on('get', msg) }
|
485
|
+
//if(has && node){ // replace 2 below lines to continue dev?
|
486
|
+
if(!node){ return root.on('get', msg) }
|
487
|
+
if(has){
|
488
|
+
if('string' != typeof has || u === node[has]){
|
489
|
+
if(!((at||'').next||'')[has]){ root.on('get', msg); return }
|
490
|
+
}
|
491
|
+
node = state_ify({}, has, state_is(node, has), node[has], soul);
|
492
|
+
// If we have a key in-memory, do we really need to fetch?
|
493
|
+
// Maybe... in case the in-memory key we have is a local write
|
494
|
+
// we still need to trigger a pull/merge from peers.
|
495
|
+
}
|
496
|
+
//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
|
497
|
+
node && ack(msg, node);
|
498
|
+
root.on('get', msg); // send GET to storage adapters.
|
499
|
+
};
|
500
|
+
function ack(msg, node){
|
501
|
+
var S = +new Date, ctx = msg._||{}, DBG = ctx.DBG = msg.DBG;
|
502
|
+
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]);
|
503
|
+
console.STAT && console.STAT(S, ((DBG||ctx).gk = +new Date) - S, 'got keys');
|
504
|
+
// PERF: Consider commenting this out to force disk-only reads for perf testing? // TODO: .keys( is slow
|
505
|
+
node && (function go(){
|
506
|
+
S = +new Date;
|
507
|
+
var i = 0, k, put = {}, tmp;
|
508
|
+
while(i < 9 && (k = keys[i++])){
|
509
|
+
state_ify(put, k, state_is(node, k), node[k], soul);
|
510
|
+
}
|
511
|
+
keys = keys.slice(i);
|
512
|
+
(tmp = {})[soul] = put; put = tmp;
|
513
|
+
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.
|
514
|
+
tmp = keys.length;
|
515
|
+
console.STAT && console.STAT(S, -(S - (S = +new Date)), 'got copied some');
|
516
|
+
DBG && (DBG.ga = +new Date);
|
517
|
+
root.on('in', {'@': to, '#': id, put: put, '%': (tmp? (id = text_rand(9)) : u), $: root.$, _: faith, DBG: DBG, FOO: 1});
|
518
|
+
console.STAT && console.STAT(S, +new Date - S, 'got in');
|
519
|
+
if(!tmp){ return }
|
520
|
+
setTimeout.turn(go);
|
521
|
+
}());
|
522
|
+
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.
|
523
|
+
} Gun.on.get.ack = ack;
|
524
|
+
}());
|
525
|
+
(function(){
|
526
|
+
Gun.chain.opt = function(opt){
|
527
|
+
opt = opt || {};
|
528
|
+
var gun = this, at = gun._, tmp = opt.peers || opt;
|
529
|
+
if(!Object.plain(opt)){ opt = {}; }
|
530
|
+
if(!Object.plain(at.opt)){ at.opt = opt; }
|
531
|
+
if('string' == typeof tmp){ tmp = [tmp]; }
|
532
|
+
if(!Object.plain(at.opt.peers)){ at.opt.peers = {};}
|
533
|
+
if(tmp instanceof Array){
|
534
|
+
opt.peers = {};
|
535
|
+
tmp.forEach(function(url){
|
536
|
+
var p = {}; p.id = p.url = url;
|
537
|
+
opt.peers[url] = at.opt.peers[url] = at.opt.peers[url] || p;
|
538
|
+
});
|
539
|
+
}
|
540
|
+
obj_each(opt, function each(k){ var v = this[k];
|
541
|
+
if((this && this.hasOwnProperty(k)) || 'string' == typeof v || Object.empty(v)){ this[k] = v; return }
|
542
|
+
if(v && v.constructor !== Object && !(v instanceof Array)){ return }
|
543
|
+
obj_each(v, each);
|
544
|
+
});
|
545
|
+
at.opt.from = opt;
|
546
|
+
Gun.on('opt', at);
|
547
|
+
at.opt.uuid = at.opt.uuid || function uuid(l){ return Gun.state().toString(36).replace('.','') + String.random(l||12) };
|
548
|
+
return gun;
|
549
|
+
};
|
550
|
+
}());
|
551
|
+
|
552
|
+
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;
|
553
|
+
|
554
|
+
Gun.log = function(){ return (!Gun.log.off && C.log.apply(C, arguments)), [].slice.call(arguments).join(' ') };
|
555
|
+
Gun.log.once = function(w,s,o){ return (o = Gun.log.once)[w] = o[w] || 0, o[w]++ || Gun.log(s) };
|
556
|
+
|
557
|
+
if(typeof window !== "undefined"){ (window.GUN = window.Gun = Gun).window = window; }
|
558
|
+
try{ if(typeof MODULE !== "undefined"){ MODULE.exports = Gun; } }catch(e){}
|
559
|
+
module.exports = Gun;
|
560
|
+
|
561
|
+
(Gun.window||{}).console = (Gun.window||{}).console || {log: function(){}};
|
562
|
+
(C = console).only = function(i, s){ return (C.only.i && i === C.only.i && C.only.i++) && (C.log.apply(C, arguments) || s) };
|
563
|
+
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!");
|
564
|
+
})(USE, './root');
|
565
|
+
USE(function(module){
|
566
|
+
var Gun = USE('./root');
|
567
|
+
Gun.chain.back = function(n, opt){ var tmp;
|
568
|
+
n = n || 1;
|
569
|
+
if(-1 === n || Infinity === n){
|
570
|
+
return this._.root.$;
|
571
|
+
} else
|
572
|
+
if(1 === n){
|
573
|
+
return (this._.back || this._).$;
|
574
|
+
}
|
575
|
+
var gun = this, at = gun._;
|
576
|
+
if(typeof n === 'string'){
|
577
|
+
n = n.split('.');
|
578
|
+
}
|
579
|
+
if(n instanceof Array){
|
580
|
+
var i = 0, l = n.length, tmp = at;
|
581
|
+
for(i; i < l; i++){
|
582
|
+
tmp = (tmp||empty)[n[i]];
|
583
|
+
}
|
584
|
+
if(u !== tmp){
|
585
|
+
return opt? gun : tmp;
|
586
|
+
} else
|
587
|
+
if((tmp = at.back)){
|
588
|
+
return tmp.$.back(n, opt);
|
589
|
+
}
|
590
|
+
return;
|
591
|
+
}
|
592
|
+
if('function' == typeof n){
|
593
|
+
var yes, tmp = {back: at};
|
594
|
+
while((tmp = tmp.back)
|
595
|
+
&& u === (yes = n(tmp, opt))){}
|
596
|
+
return yes;
|
597
|
+
}
|
598
|
+
if('number' == typeof n){
|
599
|
+
return (at.back || at).$.back(n - 1);
|
600
|
+
}
|
601
|
+
return this;
|
602
|
+
};
|
603
|
+
var empty = {}, u;
|
604
|
+
})(USE, './back');
|
605
|
+
USE(function(module){
|
606
|
+
// WARNING: GUN is very simple, but the JavaScript chaining API around GUN
|
607
|
+
// is complicated and was extremely hard to build. If you port GUN to another
|
608
|
+
// language, consider implementing an easier API to build.
|
609
|
+
var Gun = USE('./root');
|
610
|
+
Gun.chain.chain = function(sub){
|
611
|
+
var gun = this, at = gun._, chain = new (sub || gun).constructor(gun), cat = chain._, root;
|
612
|
+
cat.root = root = at.root;
|
613
|
+
cat.id = ++root.once;
|
614
|
+
cat.back = gun._;
|
615
|
+
cat.on = Gun.on;
|
616
|
+
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.
|
617
|
+
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.
|
618
|
+
return chain;
|
619
|
+
};
|
620
|
+
|
621
|
+
function output(msg){
|
622
|
+
var get, at = this.as, back = at.back, root = at.root, tmp;
|
623
|
+
if(!msg.$){ msg.$ = at.$; }
|
624
|
+
this.to.next(msg);
|
625
|
+
if(at.err){ at.on('in', {put: at.put = u, $: at.$}); return }
|
626
|
+
if(get = msg.get){
|
627
|
+
/*if(u !== at.put){
|
628
|
+
at.on('in', at);
|
629
|
+
return;
|
630
|
+
}*/
|
631
|
+
if(root.pass){ root.pass[at.id] = at; } // will this make for buggy behavior elsewhere?
|
632
|
+
if(at.lex){ Object.keys(at.lex).forEach(function(k){ tmp[k] = at.lex[k]; }, tmp = msg.get = msg.get || {}); }
|
633
|
+
if(get['#'] || at.soul){
|
634
|
+
get['#'] = get['#'] || at.soul;
|
635
|
+
//root.graph[get['#']] = root.graph[get['#']] || {_:{'#':get['#'],'>':{}}};
|
636
|
+
msg['#'] || (msg['#'] = text_rand(9)); // A3120 ?
|
637
|
+
back = (root.$.get(get['#'])._);
|
638
|
+
if(!(get = get['.'])){ // soul
|
639
|
+
tmp = back.ask && back.ask['']; // check if we have already asked for the full node
|
640
|
+
(back.ask || (back.ask = {}))[''] = back; // add a flag that we are now.
|
641
|
+
if(u !== back.put){ // if we already have data,
|
642
|
+
back.on('in', back); // send what is cached down the chain
|
643
|
+
if(tmp){ return } // and don't ask for it again.
|
644
|
+
}
|
645
|
+
msg.$ = back.$;
|
646
|
+
} else
|
647
|
+
if(obj_has(back.put, get)){ // TODO: support #LEX !
|
648
|
+
tmp = back.ask && back.ask[get];
|
649
|
+
(back.ask || (back.ask = {}))[get] = back.$.get(get)._;
|
650
|
+
back.on('in', {get: get, put: {'#': back.soul, '.': get, ':': back.put[get], '>': state_is(root.graph[back.soul], get)}});
|
651
|
+
if(tmp){ return }
|
652
|
+
}
|
653
|
+
/*put = (back.$.get(get)._);
|
654
|
+
if(!(tmp = put.ack)){ put.ack = -1 }
|
655
|
+
back.on('in', {
|
656
|
+
$: back.$,
|
657
|
+
put: Gun.state.ify({}, get, Gun.state(back.put, get), back.put[get]),
|
658
|
+
get: back.get
|
659
|
+
});
|
660
|
+
if(tmp){ return }
|
661
|
+
} else
|
662
|
+
if('string' != typeof get){
|
663
|
+
var put = {}, meta = (back.put||{})._;
|
664
|
+
Gun.obj.map(back.put, function(v,k){
|
665
|
+
if(!Gun.text.match(k, get)){ return }
|
666
|
+
put[k] = v;
|
667
|
+
})
|
668
|
+
if(!Gun.obj.empty(put)){
|
669
|
+
put._ = meta;
|
670
|
+
back.on('in', {$: back.$, put: put, get: back.get})
|
671
|
+
}
|
672
|
+
if(tmp = at.lex){
|
673
|
+
tmp = (tmp._) || (tmp._ = function(){});
|
674
|
+
if(back.ack < tmp.ask){ tmp.ask = back.ack }
|
675
|
+
if(tmp.ask){ return }
|
676
|
+
tmp.ask = 1;
|
677
|
+
}
|
678
|
+
}
|
679
|
+
*/
|
680
|
+
root.ask(ack, msg); // A3120 ?
|
681
|
+
return root.on('in', msg);
|
682
|
+
}
|
683
|
+
//if(root.now){ root.now[at.id] = root.now[at.id] || true; at.pass = {} }
|
684
|
+
if(get['.']){
|
685
|
+
if(at.get){
|
686
|
+
msg = {get: {'.': at.get}, $: at.$};
|
687
|
+
(back.ask || (back.ask = {}))[at.get] = msg.$._; // TODO: PERFORMANCE? More elegant way?
|
688
|
+
return back.on('out', msg);
|
689
|
+
}
|
690
|
+
msg = {get: at.lex? msg.get : {}, $: at.$};
|
691
|
+
return back.on('out', msg);
|
692
|
+
}
|
693
|
+
(at.ask || (at.ask = {}))[''] = at; //at.ack = at.ack || -1;
|
694
|
+
if(at.get){
|
695
|
+
get['.'] = at.get;
|
696
|
+
(back.ask || (back.ask = {}))[at.get] = msg.$._; // TODO: PERFORMANCE? More elegant way?
|
697
|
+
return back.on('out', msg);
|
698
|
+
}
|
699
|
+
}
|
700
|
+
return back.on('out', msg);
|
701
|
+
} Gun.on.out = output;
|
702
|
+
|
703
|
+
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.
|
704
|
+
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).
|
705
|
+
if(u !== msg.put && (u === tmp['#'] || u === tmp['.'] || (u === tmp[':'] && u === tmp['=']) || u === tmp['>'])){ // convert from old format
|
706
|
+
if(!valid(tmp)){
|
707
|
+
if(!(soul = ((tmp||'')._||'')['#'])){ console.log("chain not yet supported for", tmp, '...', msg, cat); return; }
|
708
|
+
gun = cat.root.$.get(soul);
|
709
|
+
return setTimeout.each(Object.keys(tmp).sort(), function(k){ // TODO: .keys( is slow // BUG? ?Some re-in logic may depend on this being sync?
|
710
|
+
if('_' == k || u === (state = state_is(tmp, k))){ return }
|
711
|
+
cat.on('in', {$: gun, put: {'#': soul, '.': k, '=': tmp[k], '>': state}, VIA: msg});
|
712
|
+
});
|
713
|
+
}
|
714
|
+
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.
|
715
|
+
return;
|
716
|
+
}
|
717
|
+
if((msg.seen||'')[cat.id]){ return } (msg.seen || (msg.seen = function(){}))[cat.id] = cat; // help stop some infinite loops
|
718
|
+
|
719
|
+
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.
|
720
|
+
Object.keys(msg).forEach(function(k){ tmp[k] = msg[k]; }, tmp = {}); // make copy of message
|
721
|
+
tmp.get = cat.get || tmp.get;
|
722
|
+
if(!cat.soul && !cat.has){ // if we do not recognize the chain type
|
723
|
+
tmp.$$$ = tmp.$$$ || cat.$; // make a reference to wherever it came from.
|
724
|
+
} else
|
725
|
+
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.
|
726
|
+
tmp.$ = cat.$;
|
727
|
+
tmp.$$ = tmp.$$ || at.$;
|
728
|
+
}
|
729
|
+
msg = tmp; // use the message with the new context instead;
|
730
|
+
}
|
731
|
+
unlink(msg, cat);
|
732
|
+
|
733
|
+
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.
|
734
|
+
(tmp = root.$.get(soul)._).put = state_ify(tmp.put, key, state, change, soul);
|
735
|
+
}
|
736
|
+
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.
|
737
|
+
sat.put = change; // update cache
|
738
|
+
if('string' == typeof (tmp = valid(change))){
|
739
|
+
sat.put = root.$.get(tmp)._.put || change; // share same cache as what we're linked to.
|
740
|
+
}
|
741
|
+
}
|
742
|
+
|
743
|
+
this.to && this.to.next(msg); // 1st API job is to call all chain listeners.
|
744
|
+
// 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.
|
745
|
+
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.
|
746
|
+
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.
|
747
|
+
|
748
|
+
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?
|
749
|
+
// is there cases where it is a $$ that we do NOT want to do the following?
|
750
|
+
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.
|
751
|
+
tmp = {}; Object.keys(msg).forEach(function(k){ tmp[k] = msg[k]; });
|
752
|
+
tmp.$ = (msg.$$||msg.$).get(tmp.get = key); delete tmp.$$; delete tmp.$$$;
|
753
|
+
sat.on('in', tmp);
|
754
|
+
}
|
755
|
+
}
|
756
|
+
|
757
|
+
link(msg, cat);
|
758
|
+
} Gun.on.in = input;
|
759
|
+
|
760
|
+
function link(msg, cat){ cat = cat || this.as || msg.$._;
|
761
|
+
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.
|
762
|
+
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.
|
763
|
+
var put = msg.put||'', link = put['=']||put[':'], tmp;
|
764
|
+
var root = cat.root, tat = root.$.get(put['#']).get(put['.'])._;
|
765
|
+
if('string' != typeof (link = valid(link))){
|
766
|
+
if(this === Gun.on){ (tat.echo || (tat.echo = {}))[cat.id] = cat; } // allow some chain to explicitly force linking to simple data.
|
767
|
+
return; // by default do not link to data that is not a link.
|
768
|
+
}
|
769
|
+
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)
|
770
|
+
&& !(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.
|
771
|
+
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.
|
772
|
+
|
773
|
+
(tat.echo||(tat.echo={}))[cat.id] = cat; // set ourself up for the echo! // TODO: BUG? Echo to self no longer causes problems? Confirm.
|
774
|
+
|
775
|
+
if(cat.has){ cat.link = link; }
|
776
|
+
var sat = root.$.get(tat.link = link)._; // grab what we're linking to.
|
777
|
+
(sat.echo || (sat.echo = {}))[tat.id] = tat; // link it.
|
778
|
+
var tmp = cat.ask||''; // ask the chain for what needs to be loaded next!
|
779
|
+
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.
|
780
|
+
sat.on('out', {get: {'#': link}});
|
781
|
+
}
|
782
|
+
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?
|
783
|
+
if(!get || !(sat = tmp[get])){ return }
|
784
|
+
sat.on('out', {get: {'#': link, '.': get}}); // go get it.
|
785
|
+
},0,99);
|
786
|
+
} Gun.on.link = link;
|
787
|
+
|
788
|
+
function unlink(msg, cat){ // ugh, so much code for seemingly edge case behavior.
|
789
|
+
var put = msg.put||'', change = (u !== put['='])? put['='] : put[':'], root = cat.root, link, tmp;
|
790
|
+
if(u === change){ // 1st edge case: If we have a brand new database, no data will be found.
|
791
|
+
// 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?
|
792
|
+
// 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.
|
793
|
+
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.
|
794
|
+
//if(!cat.has){ return }
|
795
|
+
tmp = (msg.$$||msg.$||'')._||'';
|
796
|
+
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.
|
797
|
+
//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".
|
798
|
+
if(link = cat.link || msg.linked){
|
799
|
+
delete (root.$.get(link)._.echo||'')[cat.id];
|
800
|
+
}
|
801
|
+
if(cat.has){ // TODO: Empty out links, maps, echos, acks/asks, etc.?
|
802
|
+
cat.link = null;
|
803
|
+
}
|
804
|
+
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.
|
805
|
+
// TODO: BUG! For maps, proxy this so the individual sub is triggered, not all subs.
|
806
|
+
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.
|
807
|
+
if(!(sat = cat.next[get])){ return }
|
808
|
+
//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".
|
809
|
+
if(link){ delete (root.$.get(link).get(get)._.echo||'')[sat.id]; }
|
810
|
+
sat.on('in', {get: get, put: u, $: sat.$}); // TODO: BUG? Add recursive seen check?
|
811
|
+
},0,99);
|
812
|
+
return;
|
813
|
+
}
|
814
|
+
if(cat.soul){ return } // a soul cannot unlink itself.
|
815
|
+
if(msg.$$){ return } // a linked chain does not do the unlinking, the sub chain does. // TODO: BUG? Will this cancel maps?
|
816
|
+
link = valid(change); // need to unlink anytime we are not the same link, though only do this once per unlink (and not on init).
|
817
|
+
tmp = msg.$._||'';
|
818
|
+
if(link === tmp.link || (cat.has && !tmp.link)){
|
819
|
+
if((root.pass||'')[cat.id] && 'string' !== typeof link); else {
|
820
|
+
return;
|
821
|
+
}
|
822
|
+
}
|
823
|
+
delete (tmp.echo||'')[cat.id];
|
824
|
+
unlink({get: cat.get, put: u, $: msg.$, linked: msg.linked = msg.linked || tmp.link}, cat); // unlink our sub chains.
|
825
|
+
} Gun.on.unlink = unlink;
|
826
|
+
|
827
|
+
function ack(msg, ev){
|
828
|
+
//if(!msg['%'] && (this||'').off){ this.off() } // do NOT memory leak, turn off listeners! Now handled by .ask itself
|
829
|
+
// manhattan:
|
830
|
+
var as = this.as, at = as.$._; at.root; var get = as.get||'', tmp = (msg.put||'')[get['#']]||'';
|
831
|
+
if(!msg.put || ('string' == typeof get['.'] && u === tmp[get['.']])){
|
832
|
+
if(u !== at.put){ return }
|
833
|
+
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.
|
834
|
+
at.ack = (at.ack || 0) + 1;
|
835
|
+
at.on('in', {
|
836
|
+
get: at.get,
|
837
|
+
put: at.put = u,
|
838
|
+
$: at.$,
|
839
|
+
'@': msg['@']
|
840
|
+
});
|
841
|
+
/*(tmp = at.Q) && setTimeout.each(Object.keys(tmp), function(id){ // TODO: Temporary testing, not integrated or being used, probably delete.
|
842
|
+
Object.keys(msg).forEach(function(k){ tmp[k] = msg[k] }, tmp = {}); tmp['@'] = id; // copy message
|
843
|
+
root.on('in', tmp);
|
844
|
+
}); delete at.Q;*/
|
845
|
+
return;
|
846
|
+
}
|
847
|
+
(msg._||{}).miss = 1;
|
848
|
+
Gun.on.put(msg);
|
849
|
+
return; // eom
|
850
|
+
}
|
851
|
+
|
852
|
+
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;
|
853
|
+
})(USE, './chain');
|
854
|
+
USE(function(module){
|
855
|
+
var Gun = USE('./root');
|
856
|
+
Gun.chain.get = function(key, cb, as){
|
857
|
+
var gun, tmp;
|
858
|
+
if(typeof key === 'string'){
|
859
|
+
if(key.length == 0) {
|
860
|
+
(gun = this.chain())._.err = {err: Gun.log('0 length key!', key)};
|
861
|
+
if(cb){ cb.call(gun, gun._.err); }
|
862
|
+
return gun;
|
863
|
+
}
|
864
|
+
var back = this, cat = back._;
|
865
|
+
var next = cat.next || empty;
|
866
|
+
if(!(gun = next[key])){
|
867
|
+
gun = key && cache(key, back);
|
868
|
+
}
|
869
|
+
gun = gun && gun.$;
|
870
|
+
} else
|
871
|
+
if('function' == typeof key){
|
872
|
+
if(true === cb){ return soul(this, key, cb, as), this }
|
873
|
+
gun = this;
|
874
|
+
var cat = gun._, opt = cb || {}, root = cat.root, id;
|
875
|
+
opt.at = cat;
|
876
|
+
opt.ok = key;
|
877
|
+
var wait = {}; // can we assign this to the at instead, like in once?
|
878
|
+
//var path = []; cat.$.back(at => { at.get && path.push(at.get.slice(0,9))}); path = path.reverse().join('.');
|
879
|
+
function any(msg, eve, f){
|
880
|
+
if(any.stun){ return }
|
881
|
+
if((tmp = root.pass) && !tmp[id]){ return }
|
882
|
+
var at = msg.$._, sat = (msg.$$||'')._, data = (sat||at).put, odd = (!at.has && !at.soul), test = {}, tmp;
|
883
|
+
if(odd || u === data){ // handles non-core
|
884
|
+
data = (u === ((tmp = msg.put)||'')['='])? (u === (tmp||'')[':'])? tmp : tmp[':'] : tmp['='];
|
885
|
+
}
|
886
|
+
if(('string' == typeof (tmp = Gun.valid(data)))){
|
887
|
+
data = (u === (tmp = root.$.get(tmp)._.put))? opt.not? u : data : tmp;
|
888
|
+
}
|
889
|
+
if(opt.not && u === data){ return }
|
890
|
+
if(u === opt.stun){
|
891
|
+
if((tmp = root.stun) && tmp.on){
|
892
|
+
cat.$.back(function(a){ // our chain stunned?
|
893
|
+
tmp.on(''+a.id, test = {});
|
894
|
+
if((test.run || 0) < any.id){ return test } // if there is an earlier stun on gapless parents/self.
|
895
|
+
});
|
896
|
+
!test.run && tmp.on(''+at.id, test = {}); // this node stunned?
|
897
|
+
!test.run && sat && tmp.on(''+sat.id, test = {}); // linked node stunned?
|
898
|
+
if(any.id > test.run){
|
899
|
+
if(!test.stun || test.stun.end){
|
900
|
+
test.stun = tmp.on('stun');
|
901
|
+
test.stun = test.stun && test.stun.last;
|
902
|
+
}
|
903
|
+
if(test.stun && !test.stun.end){
|
904
|
+
//if(odd && u === data){ return }
|
905
|
+
//if(u === msg.put){ return } // "not found" acks will be found if there is stun, so ignore these.
|
906
|
+
(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.
|
907
|
+
return;
|
908
|
+
}
|
909
|
+
}
|
910
|
+
}
|
911
|
+
if(/*odd &&*/ u === data){ f = 0; } // if data not found, keep waiting/trying.
|
912
|
+
/*if(f && u === data){
|
913
|
+
cat.on('out', opt.out);
|
914
|
+
return;
|
915
|
+
}*/
|
916
|
+
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.
|
917
|
+
if(wait[at.$._.id]){ return } wait[at.$._.id] = 1;
|
918
|
+
tmp.push(function(){any(msg,eve,1);});
|
919
|
+
return;
|
920
|
+
} wait = {}; // end quick hack.
|
921
|
+
}
|
922
|
+
// call:
|
923
|
+
if(root.pass){ if(root.pass[id+at.id]){ return } root.pass[id+at.id] = 1; }
|
924
|
+
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.
|
925
|
+
if(opt.v2020){ opt.ok(msg, eve || any); return }
|
926
|
+
Object.keys(msg).forEach(function(k){ tmp[k] = msg[k]; }, tmp = {}); msg = tmp; msg.put = data; // 2019 COMPATIBILITY! TODO: GET RID OF THIS!
|
927
|
+
opt.ok.call(opt.as, msg, eve || any); // is this the right
|
928
|
+
} any.at = cat;
|
929
|
+
//(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?
|
930
|
+
(cat.any||(cat.any={}))[id = String.random(7)] = any;
|
931
|
+
any.off = function(){ any.stun = 1; if(!cat.any){ return } delete cat.any[id]; };
|
932
|
+
any.rid = rid; // logic from old version, can we clean it up now?
|
933
|
+
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?
|
934
|
+
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?
|
935
|
+
opt.out = opt.out || {get: {}};
|
936
|
+
cat.on('out', opt.out);
|
937
|
+
root.pass = tmp;
|
938
|
+
return gun;
|
939
|
+
} else
|
940
|
+
if('number' == typeof key){
|
941
|
+
return this.get(''+key, cb, as);
|
942
|
+
} else
|
943
|
+
if('string' == typeof (tmp = valid(key))){
|
944
|
+
return this.get(tmp, cb, as);
|
945
|
+
} else
|
946
|
+
if(tmp = this.get.next){
|
947
|
+
gun = tmp(this, key);
|
948
|
+
}
|
949
|
+
if(!gun){
|
950
|
+
(gun = this.chain())._.err = {err: Gun.log('Invalid get request!', key)}; // CLEAN UP
|
951
|
+
if(cb){ cb.call(gun, gun._.err); }
|
952
|
+
return gun;
|
953
|
+
}
|
954
|
+
if(cb && 'function' == typeof cb){
|
955
|
+
gun.get(cb, as);
|
956
|
+
}
|
957
|
+
return gun;
|
958
|
+
};
|
959
|
+
function cache(key, back){
|
960
|
+
var cat = back._, next = cat.next, gun = back.chain(), at = gun._;
|
961
|
+
if(!next){ next = cat.next = {}; }
|
962
|
+
next[at.get = key] = at;
|
963
|
+
if(back === cat.root.$){
|
964
|
+
at.soul = key;
|
965
|
+
//at.put = {};
|
966
|
+
} else
|
967
|
+
if(cat.soul || cat.has){
|
968
|
+
at.has = key;
|
969
|
+
//if(obj_has(cat.put, key)){
|
970
|
+
//at.put = cat.put[key];
|
971
|
+
//}
|
972
|
+
}
|
973
|
+
return at;
|
974
|
+
}
|
975
|
+
function soul(gun, cb, opt, as){
|
976
|
+
var cat = gun._, acks = 0, tmp;
|
977
|
+
if(tmp = cat.soul || cat.link){ return cb(tmp, as, cat) }
|
978
|
+
if(cat.jam){ return cat.jam.push([cb, as]) }
|
979
|
+
cat.jam = [[cb,as]];
|
980
|
+
gun.get(function go(msg, eve){
|
981
|
+
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
|
982
|
+
return;
|
983
|
+
}
|
984
|
+
eve.rid(msg);
|
985
|
+
var at = ((at = msg.$) && at._) || {}, i = 0, as;
|
986
|
+
tmp = cat.jam; delete cat.jam; // tmp = cat.jam.splice(0, 100);
|
987
|
+
//if(tmp.length){ process.nextTick(function(){ go(msg, eve) }) }
|
988
|
+
while(as = tmp[i++]){ //Gun.obj.map(tmp, function(as, cb){
|
989
|
+
var cb = as[0]; as = as[1];
|
990
|
+
cb && cb(at.link || at.soul || Gun.valid(msg.put) || ((msg.put||{})._||{})['#'], as, msg, eve);
|
991
|
+
} //);
|
992
|
+
}, {out: {get: {'.':true}}});
|
993
|
+
return gun;
|
994
|
+
}
|
995
|
+
function rid(at){
|
996
|
+
var cat = this.at || this.on;
|
997
|
+
if(!at || cat.soul || cat.has){ return this.off() }
|
998
|
+
if(!(at = (at = (at = at.$ || at)._ || at).id)){ return }
|
999
|
+
cat.map; var seen;
|
1000
|
+
//if(!map || !(tmp = map[at]) || !(tmp = tmp.at)){ return }
|
1001
|
+
if((seen = this.seen || (this.seen = {}))[at]){ return true }
|
1002
|
+
seen[at] = true;
|
1003
|
+
return;
|
1004
|
+
}
|
1005
|
+
var empty = {}, valid = Gun.valid, u;
|
1006
|
+
})(USE, './get');
|
1007
|
+
USE(function(module){
|
1008
|
+
var Gun = USE('./root');
|
1009
|
+
Gun.chain.put = function(data, cb, as){ // I rewrote it :)
|
1010
|
+
var gun = this, at = gun._, root = at.root;
|
1011
|
+
as = as || {};
|
1012
|
+
as.root = at.root;
|
1013
|
+
as.run || (as.run = root.once);
|
1014
|
+
stun(as, at.id); // set a flag for reads to check if this chain is writing.
|
1015
|
+
as.ack = as.ack || cb;
|
1016
|
+
as.via = as.via || gun;
|
1017
|
+
as.data = as.data || data;
|
1018
|
+
as.soul || (as.soul = at.soul || ('string' == typeof cb && cb));
|
1019
|
+
var s = as.state = as.state || Gun.state();
|
1020
|
+
if('function' == typeof data){ data(function(d){ as.data = d; gun.put(u,u,as); }); return gun }
|
1021
|
+
if(!as.soul){ return get(as), gun }
|
1022
|
+
as.$ = root.$.get(as.soul); // TODO: This may not allow user chaining and similar?
|
1023
|
+
as.todo = [{it: as.data, ref: as.$}];
|
1024
|
+
as.turn = as.turn || turn;
|
1025
|
+
as.ran = as.ran || ran;
|
1026
|
+
//var path = []; as.via.back(at => { at.get && path.push(at.get.slice(0,9)) }); path = path.reverse().join('.');
|
1027
|
+
// TODO: Perf! We only need to stun chains that are being modified, not necessarily written to.
|
1028
|
+
(function walk(){
|
1029
|
+
var to = as.todo, at = to.pop(), d = at.it; at.ref && at.ref._.id; var v, k, cat, tmp, g;
|
1030
|
+
stun(as, at.ref);
|
1031
|
+
if(tmp = at.todo){
|
1032
|
+
k = tmp.pop(); d = d[k];
|
1033
|
+
if(tmp.length){ to.push(at); }
|
1034
|
+
}
|
1035
|
+
k && (to.path || (to.path = [])).push(k);
|
1036
|
+
if(!(v = valid(d)) && !(g = Gun.is(d))){
|
1037
|
+
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 }
|
1038
|
+
var seen = as.seen || (as.seen = []), i = seen.length;
|
1039
|
+
while(i--){ if(d === (tmp = seen[i]).it){ v = d = tmp.link; break } }
|
1040
|
+
}
|
1041
|
+
if(k && v){ at.node = state_ify(at.node, k, s, d); } // handle soul later.
|
1042
|
+
else {
|
1043
|
+
if(!as.seen){ ran.err(as, "Data at root of graph must be a node (an object)."); return }
|
1044
|
+
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( ?
|
1045
|
+
at.node = state_ify(at.node, k, s, cat.link);
|
1046
|
+
!g && cat.todo.length && to.push(cat);
|
1047
|
+
// ---------------
|
1048
|
+
var id = as.seen.length;
|
1049
|
+
(as.wait || (as.wait = {}))[id] = '';
|
1050
|
+
tmp = (cat.ref = (g? d : k? at.ref.get(k) : at.ref))._;
|
1051
|
+
(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?
|
1052
|
+
//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!
|
1053
|
+
function resolve(msg, eve){
|
1054
|
+
var end = cat.link['#'];
|
1055
|
+
if(eve){ eve.off(); eve.rid(msg); } // TODO: Too early! Check all peers ack not found.
|
1056
|
+
// TODO: BUG maybe? Make sure this does not pick up a link change wipe, that it uses the changign link instead.
|
1057
|
+
var soul = end || msg.soul || (tmp = (msg.$$||msg.$)._||'').soul || tmp.link || ((tmp = tmp.put||'')._||'')['#'] || tmp['#'] || (((tmp = msg.put||'') && msg.$$)? tmp['#'] : (tmp['=']||tmp[':']||'')['#']);
|
1058
|
+
!end && stun(as, msg.$);
|
1059
|
+
if(!soul && !at.link['#']){ // check soul link above us
|
1060
|
+
(at.wait || (at.wait = [])).push(function(){ resolve(msg, eve); }); // wait
|
1061
|
+
return;
|
1062
|
+
}
|
1063
|
+
if(!soul){
|
1064
|
+
soul = [];
|
1065
|
+
(msg.$$||msg.$).back(function(at){
|
1066
|
+
if(tmp = at.soul || at.link){ return soul.push(tmp) }
|
1067
|
+
soul.push(at.get);
|
1068
|
+
});
|
1069
|
+
soul = soul.reverse().join('/');
|
1070
|
+
}
|
1071
|
+
cat.link['#'] = soul;
|
1072
|
+
!g && (((as.graph || (as.graph = {}))[soul] = (cat.node || (cat.node = {_:{}})))._['#'] = soul);
|
1073
|
+
delete as.wait[id];
|
1074
|
+
cat.wait && setTimeout.each(cat.wait, function(cb){ cb && cb(); });
|
1075
|
+
as.ran(as);
|
1076
|
+
} // ---------------
|
1077
|
+
}
|
1078
|
+
if(!to.length){ return as.ran(as) }
|
1079
|
+
as.turn(walk);
|
1080
|
+
}());
|
1081
|
+
return gun;
|
1082
|
+
};
|
1083
|
+
|
1084
|
+
function stun(as, id){
|
1085
|
+
if(!id){ return } id = (id._||'').id||id;
|
1086
|
+
var run = as.root.stun || (as.root.stun = {on: Gun.on}), test = {}, tmp;
|
1087
|
+
as.stun || (as.stun = run.on('stun', function(){ }));
|
1088
|
+
if(tmp = run.on(''+id)){ tmp.the.last.next(test); }
|
1089
|
+
if(test.run >= as.run){ return }
|
1090
|
+
run.on(''+id, function(test){
|
1091
|
+
if(as.stun.end){
|
1092
|
+
this.off();
|
1093
|
+
this.to.next(test);
|
1094
|
+
return;
|
1095
|
+
}
|
1096
|
+
test.run = test.run || as.run;
|
1097
|
+
test.stun = test.stun || as.stun; return;
|
1098
|
+
});
|
1099
|
+
}
|
1100
|
+
|
1101
|
+
function ran(as){
|
1102
|
+
if(as.err){ ran.end(as.stun, as.root); return } // move log handle here.
|
1103
|
+
if(as.todo.length || as.end || !Object.empty(as.wait)){ return } as.end = 1;
|
1104
|
+
//(as.retry = function(){ as.acks = 0;
|
1105
|
+
var cat = (as.$.back(-1)._), root = cat.root, ask = cat.ask(function(ack){
|
1106
|
+
root.on('ack', ack);
|
1107
|
+
if(ack.err && !ack.lack){ Gun.log(ack); }
|
1108
|
+
if(++acks > (as.acks || 0)){ this.off(); } // Adjustable ACKs! Only 1 by default.
|
1109
|
+
if(!as.ack){ return }
|
1110
|
+
as.ack(ack, this);
|
1111
|
+
}, as.opt), acks = 0, stun = as.stun, tmp;
|
1112
|
+
(tmp = function(){ // this is not official yet, but quick solution to hack in for now.
|
1113
|
+
if(!stun){ return }
|
1114
|
+
ran.end(stun, root);
|
1115
|
+
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( ?
|
1116
|
+
}).hatch = tmp; // this is not official yet ^
|
1117
|
+
//console.log(1, "PUT", as.run, as.graph);
|
1118
|
+
if(as.ack && !as.ok){ as.ok = as.acks || 9; } // TODO: In future! Remove this! This is just old API support.
|
1119
|
+
(as.via._).on('out', {put: as.out = as.graph, ok: as.ok && {'@': as.ok+1}, opt: as.opt, '#': ask, _: tmp});
|
1120
|
+
//})();
|
1121
|
+
} ran.end = function(stun,root){
|
1122
|
+
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.
|
1123
|
+
if(stun.the.to === stun && stun === stun.the.last){ delete root.stun; }
|
1124
|
+
stun.off();
|
1125
|
+
}; ran.err = function(as, err){
|
1126
|
+
(as.ack||noop).call(as, as.out = { err: as.err = Gun.log(err) });
|
1127
|
+
as.ran(as);
|
1128
|
+
};
|
1129
|
+
|
1130
|
+
function get(as){
|
1131
|
+
var at = as.via._, tmp;
|
1132
|
+
as.via = as.via.back(function(at){
|
1133
|
+
if(at.soul || !at.get){ return at.$ }
|
1134
|
+
tmp = as.data; (as.data = {})[at.get] = tmp;
|
1135
|
+
});
|
1136
|
+
if(!as.via || !as.via._.soul){
|
1137
|
+
as.via = at.root.$.get(((as.data||'')._||'')['#'] || at.$.back('opt.uuid')());
|
1138
|
+
}
|
1139
|
+
as.via.put(as.data, as.ack, as);
|
1140
|
+
|
1141
|
+
|
1142
|
+
return;
|
1143
|
+
}
|
1144
|
+
function check(d, tmp){ return ((d && (tmp = d.constructor) && tmp.name) || typeof d) }
|
1145
|
+
|
1146
|
+
var u, noop = function(){}, turn = setTimeout.turn, valid = Gun.valid, state_ify = Gun.state.ify;
|
1147
|
+
})(USE, './put');
|
1148
|
+
USE(function(module){
|
1149
|
+
var Gun = USE('./root');
|
1150
|
+
USE('./chain');
|
1151
|
+
USE('./back');
|
1152
|
+
USE('./put');
|
1153
|
+
USE('./get');
|
1154
|
+
module.exports = Gun;
|
1155
|
+
})(USE, './index');
|
1156
|
+
USE(function(module){
|
1157
|
+
var Gun = USE('./index');
|
1158
|
+
Gun.chain.on = function(tag, arg, eas, as){ // don't rewrite!
|
1159
|
+
var gun = this, cat = gun._; cat.root; var act;
|
1160
|
+
if(typeof tag === 'string'){
|
1161
|
+
if(!arg){ return cat.on(tag) }
|
1162
|
+
act = cat.on(tag, arg, eas || cat, as);
|
1163
|
+
if(eas && eas.$){
|
1164
|
+
(eas.subs || (eas.subs = [])).push(act);
|
1165
|
+
}
|
1166
|
+
return gun;
|
1167
|
+
}
|
1168
|
+
var opt = arg;
|
1169
|
+
(opt = (true === opt)? {change: true} : opt || {}).not = 1; opt.on = 1;
|
1170
|
+
gun.get(tag, opt);
|
1171
|
+
/*gun.get(function on(data,key,msg,eve){ var $ = this;
|
1172
|
+
if(tmp = root.hatch){ // quick hack!
|
1173
|
+
if(wait[$._.id]){ return } wait[$._.id] = 1;
|
1174
|
+
tmp.push(function(){on.call($, data,key,msg,eve)});
|
1175
|
+
return;
|
1176
|
+
}; wait = {}; // end quick hack.
|
1177
|
+
tag.call($, data,key,msg,eve);
|
1178
|
+
}, opt); // TODO: PERF! Event listener leak!!!?*/
|
1179
|
+
/*
|
1180
|
+
function one(msg, eve){
|
1181
|
+
if(one.stun){ return }
|
1182
|
+
var at = msg.$._, data = at.put, tmp;
|
1183
|
+
if(tmp = at.link){ data = root.$.get(tmp)._.put }
|
1184
|
+
if(opt.not===u && u === data){ return }
|
1185
|
+
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(`.
|
1186
|
+
tmp[id] = function(){one(msg,eve)};
|
1187
|
+
return;
|
1188
|
+
}
|
1189
|
+
//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];
|
1190
|
+
// call:
|
1191
|
+
if(opt.as){
|
1192
|
+
opt.ok.call(opt.as, msg, eve || one);
|
1193
|
+
} else {
|
1194
|
+
opt.ok.call(at.$, data, msg.get || at.get, msg, eve || one);
|
1195
|
+
}
|
1196
|
+
};
|
1197
|
+
one.at = cat;
|
1198
|
+
(cat.act||(cat.act={}))[id = String.random(7)] = one;
|
1199
|
+
one.off = function(){ one.stun = 1; if(!cat.act){ return } delete cat.act[id] }
|
1200
|
+
cat.on('out', {get: {}});*/
|
1201
|
+
return gun;
|
1202
|
+
};
|
1203
|
+
// Rules:
|
1204
|
+
// 1. If cached, should be fast, but not read while write.
|
1205
|
+
// 2. Should not retrigger other listeners, should get triggered even if nothing found.
|
1206
|
+
// 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
|
1207
|
+
Gun.chain.once = function(cb, opt){ opt = opt || {}; // avoid rewriting
|
1208
|
+
if(!cb){ return none(this) }
|
1209
|
+
var gun = this, cat = gun._, root = cat.root; cat.put; var id = String.random(7), tmp;
|
1210
|
+
gun.get(function(data,key,msg,eve){
|
1211
|
+
var $ = this, at = $._, one = (at.one||(at.one={}));
|
1212
|
+
if(eve.stun){ return } if('' === one[id]){ return }
|
1213
|
+
if(true === (tmp = Gun.valid(data))){ once(); return }
|
1214
|
+
if('string' == typeof tmp){ return } // TODO: BUG? Will this always load?
|
1215
|
+
clearTimeout((cat.one||'')[id]); // clear "not found" since they only get set on cat.
|
1216
|
+
clearTimeout(one[id]); one[id] = setTimeout(once, opt.wait||99); // TODO: Bug? This doesn't handle plural chains.
|
1217
|
+
function once(f){
|
1218
|
+
if(!at.has && !at.soul){ at = {put: data, get: key}; } // handles non-core messages.
|
1219
|
+
if(u === (tmp = at.put)){ tmp = ((msg.$$||'')._||'').put; }
|
1220
|
+
if('string' == typeof Gun.valid(tmp)){
|
1221
|
+
tmp = root.$.get(tmp)._.put;
|
1222
|
+
if(tmp === u && !f){
|
1223
|
+
one[id] = setTimeout(function(){ once(1); }, opt.wait||99); // TODO: Quick fix. Maybe use ack count for more predictable control?
|
1224
|
+
return
|
1225
|
+
}
|
1226
|
+
}
|
1227
|
+
//console.log("AND VANISHED", data);
|
1228
|
+
if(eve.stun){ return } if('' === one[id]){ return } one[id] = '';
|
1229
|
+
if(cat.soul || cat.has){ eve.off(); } // TODO: Plural chains? // else { ?.off() } // better than one check?
|
1230
|
+
cb.call($, tmp, at.get);
|
1231
|
+
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.
|
1232
|
+
} }, {on: 1});
|
1233
|
+
return gun;
|
1234
|
+
};
|
1235
|
+
function none(gun,opt,chain){
|
1236
|
+
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.");
|
1237
|
+
(chain = gun.chain())._.nix = gun.once(function(data, key){ chain._.on('in', this._); });
|
1238
|
+
chain._.lex = gun._.lex; // TODO: Better approach in future? This is quick for now.
|
1239
|
+
return chain;
|
1240
|
+
}
|
1241
|
+
|
1242
|
+
Gun.chain.off = function(){
|
1243
|
+
// make off more aggressive. Warning, it might backfire!
|
1244
|
+
var gun = this, at = gun._, tmp;
|
1245
|
+
var cat = at.back;
|
1246
|
+
if(!cat){ return }
|
1247
|
+
at.ack = 0; // so can resubscribe.
|
1248
|
+
if(tmp = cat.next){
|
1249
|
+
if(tmp[at.get]){
|
1250
|
+
delete tmp[at.get];
|
1251
|
+
}
|
1252
|
+
}
|
1253
|
+
// TODO: delete cat.one[map.id]?
|
1254
|
+
if (tmp = cat.any) {
|
1255
|
+
delete cat.any;
|
1256
|
+
cat.any = {};
|
1257
|
+
}
|
1258
|
+
if(tmp = cat.ask){
|
1259
|
+
delete tmp[at.get];
|
1260
|
+
}
|
1261
|
+
if(tmp = cat.put){
|
1262
|
+
delete tmp[at.get];
|
1263
|
+
}
|
1264
|
+
if(tmp = at.soul){
|
1265
|
+
delete cat.root.graph[tmp];
|
1266
|
+
}
|
1267
|
+
if(tmp = at.map){
|
1268
|
+
Object.keys(tmp).forEach(function(i,at){ at = tmp[i]; //obj_map(tmp, function(at){
|
1269
|
+
if(at.link){
|
1270
|
+
cat.root.$.get(at.link).off();
|
1271
|
+
}
|
1272
|
+
});
|
1273
|
+
}
|
1274
|
+
if(tmp = at.next){
|
1275
|
+
Object.keys(tmp).forEach(function(i,neat){ neat = tmp[i]; //obj_map(tmp, function(neat){
|
1276
|
+
neat.$.off();
|
1277
|
+
});
|
1278
|
+
}
|
1279
|
+
at.on('off', {});
|
1280
|
+
return gun;
|
1281
|
+
};
|
1282
|
+
var u;
|
1283
|
+
})(USE, './on');
|
1284
|
+
USE(function(module){
|
1285
|
+
var Gun = USE('./index'), next = Gun.chain.get.next;
|
1286
|
+
Gun.chain.get.next = function(gun, lex){ var tmp;
|
1287
|
+
if(!Object.plain(lex)){ return (next||noop)(gun, lex) }
|
1288
|
+
if(tmp = ((tmp = lex['#'])||'')['='] || tmp){ return gun.get(tmp) }
|
1289
|
+
(tmp = gun.chain()._).lex = lex; // LEX!
|
1290
|
+
gun.on('in', function(eve){
|
1291
|
+
if(String.match(eve.get|| (eve.put||'')['.'], lex['.'] || lex['#'] || lex)){
|
1292
|
+
tmp.on('in', eve);
|
1293
|
+
}
|
1294
|
+
this.to.next(eve);
|
1295
|
+
});
|
1296
|
+
return tmp.$;
|
1297
|
+
};
|
1298
|
+
Gun.chain.map = function(cb, opt, t){
|
1299
|
+
var gun = this, cat = gun._, lex, chain;
|
1300
|
+
if(Object.plain(cb)){ lex = cb['.']? cb : {'.': cb}; cb = u; }
|
1301
|
+
if(!cb){
|
1302
|
+
if(chain = cat.each){ return chain }
|
1303
|
+
(cat.each = chain = gun.chain())._.lex = lex || chain._.lex || cat.lex;
|
1304
|
+
chain._.nix = gun.back('nix');
|
1305
|
+
gun.on('in', map, chain._);
|
1306
|
+
return chain;
|
1307
|
+
}
|
1308
|
+
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.");
|
1309
|
+
chain = gun.chain();
|
1310
|
+
gun.map().on(function(data, key, msg, eve){
|
1311
|
+
var next = (cb||noop).call(this, data, key, msg, eve);
|
1312
|
+
if(u === next){ return }
|
1313
|
+
if(data === next){ return chain._.on('in', msg) }
|
1314
|
+
if(Gun.is(next)){ return chain._.on('in', next._) }
|
1315
|
+
var tmp = {}; Object.keys(msg.put).forEach(function(k){ tmp[k] = msg.put[k]; }, tmp); tmp['='] = next;
|
1316
|
+
chain._.on('in', {get: key, put: tmp});
|
1317
|
+
});
|
1318
|
+
return chain;
|
1319
|
+
};
|
1320
|
+
function map(msg){ this.to.next(msg);
|
1321
|
+
var cat = this.as, gun = msg.$, at = gun._, put = msg.put, tmp;
|
1322
|
+
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.
|
1323
|
+
if((tmp = cat.lex) && !String.match(msg.get|| (put||'')['.'], tmp['.'] || tmp['#'] || tmp)){ return }
|
1324
|
+
Gun.on.link(msg, cat);
|
1325
|
+
}
|
1326
|
+
var noop = function(){}, u;
|
1327
|
+
})(USE, './map');
|
1328
|
+
USE(function(module){
|
1329
|
+
var Gun = USE('./index');
|
1330
|
+
Gun.chain.set = function(item, cb, opt){
|
1331
|
+
var gun = this, root = gun.back(-1), soul, tmp;
|
1332
|
+
cb = cb || function(){};
|
1333
|
+
opt = opt || {}; opt.item = opt.item || item;
|
1334
|
+
if(soul = ((item||'')._||'')['#']){ (item = {})['#'] = soul; } // check if node, make link.
|
1335
|
+
if('string' == typeof (tmp = Gun.valid(item))){ return gun.get(soul = tmp).put(item, cb, opt) } // check if link
|
1336
|
+
if(!Gun.is(item)){
|
1337
|
+
if(Object.plain(item)){
|
1338
|
+
item = root.get(soul = gun.back('opt.uuid')()).put(item);
|
1339
|
+
}
|
1340
|
+
return gun.get(soul || root.back('opt.uuid')(7)).put(item, cb, opt);
|
1341
|
+
}
|
1342
|
+
gun.put(function(go){
|
1343
|
+
item.get(function(soul, o, msg){ // TODO: BUG! We no longer have this option? & go error not handled?
|
1344
|
+
if(!soul){ return cb.call(gun, {err: Gun.log('Only a node can be linked! Not "' + msg.put + '"!')}) }
|
1345
|
+
(tmp = {})[soul] = {'#': soul}; go(tmp);
|
1346
|
+
},true);
|
1347
|
+
});
|
1348
|
+
return item;
|
1349
|
+
};
|
1350
|
+
})(USE, './set');
|
1351
|
+
USE(function(module){
|
1352
|
+
USE('./shim');
|
1353
|
+
|
1354
|
+
var noop = function(){};
|
1355
|
+
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); } };
|
1356
|
+
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); } };
|
1357
|
+
json.sucks = function(d){ if(d > 99){ console.log("Warning: JSON blocking CPU detected. Add `gun/lib/yson.js` to fix."); json.sucks = noop; } };
|
1358
|
+
|
1359
|
+
function Mesh(root){
|
1360
|
+
var mesh = function(){};
|
1361
|
+
var opt = root.opt || {};
|
1362
|
+
opt.log = opt.log || console.log;
|
1363
|
+
opt.gap = opt.gap || opt.wait || 0;
|
1364
|
+
opt.max = opt.max || (opt.memory? (opt.memory * 999 * 999) : 300000000) * 0.3;
|
1365
|
+
opt.pack = opt.pack || (opt.max * 0.01 * 0.01);
|
1366
|
+
opt.puff = opt.puff || 9; // IDEA: do a start/end benchmark, divide ops/result.
|
1367
|
+
var puff = setTimeout.turn || setTimeout;
|
1368
|
+
|
1369
|
+
var dup = root.dup, dup_check = dup.check, dup_track = dup.track;
|
1370
|
+
|
1371
|
+
var hear = mesh.hear = function(raw, peer){
|
1372
|
+
if(!raw){ return }
|
1373
|
+
if(opt.max <= raw.length){ return mesh.say({dam: '!', err: "Message too big!"}, peer) }
|
1374
|
+
if(mesh === this){
|
1375
|
+
/*if('string' == typeof raw){ try{
|
1376
|
+
var stat = console.STAT || {};
|
1377
|
+
//console.log('HEAR:', peer.id, (raw||'').slice(0,250), ((raw||'').length / 1024 / 1024).toFixed(4));
|
1378
|
+
|
1379
|
+
//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');
|
1380
|
+
}catch(e){ console.log('DBG err', e) }}*/
|
1381
|
+
hear.d += raw.length||0 ; ++hear.c; } // STATS!
|
1382
|
+
var S = peer.SH = +new Date;
|
1383
|
+
var tmp = raw[0], msg;
|
1384
|
+
//raw && raw.slice && console.log("hear:", ((peer.wire||'').headers||'').origin, raw.length, raw.slice && raw.slice(0,50)); //tc-iamunique-tc-package-ds1
|
1385
|
+
if('[' === tmp){
|
1386
|
+
parse(raw, function(err, msg){
|
1387
|
+
if(err || !msg){ return mesh.say({dam: '!', err: "DAM JSON parse error."}, peer) }
|
1388
|
+
console.STAT && console.STAT(+new Date, msg.length, '# on hear batch');
|
1389
|
+
var P = opt.puff;
|
1390
|
+
(function go(){
|
1391
|
+
var S = +new Date;
|
1392
|
+
var i = 0, m; while(i < P && (m = msg[i++])){ mesh.hear(m, peer); }
|
1393
|
+
msg = msg.slice(i); // slicing after is faster than shifting during.
|
1394
|
+
console.STAT && console.STAT(S, +new Date - S, 'hear loop');
|
1395
|
+
flush(peer); // force send all synchronously batched acks.
|
1396
|
+
if(!msg.length){ return }
|
1397
|
+
puff(go, 0);
|
1398
|
+
}());
|
1399
|
+
});
|
1400
|
+
raw = ''; //
|
1401
|
+
return;
|
1402
|
+
}
|
1403
|
+
if('{' === tmp || ((raw['#'] || Object.plain(raw)) && (msg = raw))){
|
1404
|
+
if(msg){ return hear.one(msg, peer, S) }
|
1405
|
+
parse(raw, function(err, msg){
|
1406
|
+
if(err || !msg){ return mesh.say({dam: '!', err: "DAM JSON parse error."}, peer) }
|
1407
|
+
hear.one(msg, peer, S);
|
1408
|
+
});
|
1409
|
+
return;
|
1410
|
+
}
|
1411
|
+
};
|
1412
|
+
hear.one = function(msg, peer, S){ // S here is temporary! Undo.
|
1413
|
+
var id, hash, tmp, ash, DBG;
|
1414
|
+
if(msg.DBG){ msg.DBG = DBG = {DBG: msg.DBG}; }
|
1415
|
+
DBG && (DBG.h = S);
|
1416
|
+
DBG && (DBG.hp = +new Date);
|
1417
|
+
if(!(id = msg['#'])){ id = msg['#'] = String.random(9); }
|
1418
|
+
if(tmp = dup_check(id)){ return }
|
1419
|
+
// DAM logic:
|
1420
|
+
if(!(hash = msg['##']) && false && u !== msg.put); // disable hashing for now // TODO: impose warning/penalty instead (?)
|
1421
|
+
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.
|
1422
|
+
(msg._ = function(){}).via = mesh.leap = peer;
|
1423
|
+
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.
|
1424
|
+
// DAM ^
|
1425
|
+
if(tmp = msg.dam){
|
1426
|
+
if(tmp = mesh.hear[tmp]){
|
1427
|
+
tmp(msg, peer, root);
|
1428
|
+
}
|
1429
|
+
dup_track(id);
|
1430
|
+
return;
|
1431
|
+
}
|
1432
|
+
if(tmp = msg.ok){ msg._.near = tmp['/']; }
|
1433
|
+
var S = +new Date;
|
1434
|
+
DBG && (DBG.is = S); peer.SI = id;
|
1435
|
+
dup_track.ed = function(d){
|
1436
|
+
if(id !== d){ return }
|
1437
|
+
dup_track.ed = 0;
|
1438
|
+
if(!(d = dup.s[id])){ return }
|
1439
|
+
d.via = peer;
|
1440
|
+
if(msg.get){ d.it = msg; }
|
1441
|
+
};
|
1442
|
+
root.on('in', mesh.last = msg);
|
1443
|
+
DBG && (DBG.hd = +new Date);
|
1444
|
+
console.STAT && console.STAT(S, +new Date - S, msg.get? 'msg get' : msg.put? 'msg put' : 'msg');
|
1445
|
+
dup_track(id); // in case 'in' does not call track.
|
1446
|
+
if(ash){ dup_track(ash); } //dup.track(tmp+hash, true).it = it(msg);
|
1447
|
+
mesh.leap = mesh.last = null; // warning! mesh.leap could be buggy.
|
1448
|
+
};
|
1449
|
+
hear.c = hear.d = 0;
|
1450
|
+
(function(){
|
1451
|
+
var SMIA = 0;
|
1452
|
+
var loop;
|
1453
|
+
mesh.hash = function(msg, peer){ var h, s, t;
|
1454
|
+
var S = +new Date;
|
1455
|
+
json(msg.put, function hash(err, text){
|
1456
|
+
var ss = (s || (s = t = text||'')).slice(0, 32768); // 1024 * 32
|
1457
|
+
h = String.hash(ss, h); s = s.slice(32768);
|
1458
|
+
if(s){ puff(hash, 0); return }
|
1459
|
+
console.STAT && console.STAT(S, +new Date - S, 'say json+hash');
|
1460
|
+
msg._.$put = t;
|
1461
|
+
msg['##'] = h;
|
1462
|
+
mesh.say(msg, peer);
|
1463
|
+
delete msg._.$put;
|
1464
|
+
}, sort);
|
1465
|
+
};
|
1466
|
+
function sort(k, v){ var tmp;
|
1467
|
+
if(!(v instanceof Object)){ return v }
|
1468
|
+
Object.keys(v).sort().forEach(sorta, {to: tmp = {}, on: v});
|
1469
|
+
return tmp;
|
1470
|
+
} function sorta(k){ this.to[k] = this.on[k]; }
|
1471
|
+
|
1472
|
+
mesh.say = function(msg, peer){ var tmp;
|
1473
|
+
if((tmp = this) && (tmp = tmp.to) && tmp.next){ tmp.next(msg); } // compatible with middleware adapters.
|
1474
|
+
if(!msg){ return false }
|
1475
|
+
var id, hash, raw, ack = msg['@'];
|
1476
|
+
//if(opt.super && (!ack || !msg.put)){ return } // TODO: MANHATTAN STUB //OBVIOUSLY BUG! But squelch relay. // :( get only is 100%+ CPU usage :(
|
1477
|
+
var meta = msg._||(msg._=function(){});
|
1478
|
+
var DBG = msg.DBG, S = +new Date; meta.y = meta.y || S; if(!peer){ DBG && (DBG.y = S); }
|
1479
|
+
if(!(id = msg['#'])){ id = msg['#'] = String.random(9); }
|
1480
|
+
!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.
|
1481
|
+
//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.
|
1482
|
+
if(!(hash = msg['##']) && u !== msg.put && !meta.via && ack){ mesh.hash(msg, peer); return } // TODO: Should broadcasts be hashed?
|
1483
|
+
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.
|
1484
|
+
if(!peer && ack){ // still no peer, then ack daisy chain 'tunnel' got lost.
|
1485
|
+
if(dup.s[ack]){ return } // in dups but no peer hints that this was ack to ourself, ignore.
|
1486
|
+
console.STAT && console.STAT(+new Date, ++SMIA, 'total no peer to ack to'); // TODO: Delete this now. Dropping lost ACKs is protocol fine now.
|
1487
|
+
return false;
|
1488
|
+
} // 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.
|
1489
|
+
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!
|
1490
|
+
if(!peer && mesh.way){ return mesh.way(msg) }
|
1491
|
+
DBG && (DBG.yh = +new Date);
|
1492
|
+
if(!(raw = meta.raw)){ mesh.raw(msg, peer); return }
|
1493
|
+
DBG && (DBG.yr = +new Date);
|
1494
|
+
if(!peer || !peer.id){
|
1495
|
+
if(!Object.plain(peer || opt.peers)){ return false }
|
1496
|
+
var S = +new Date;
|
1497
|
+
opt.puff; var ps = opt.peers, pl = Object.keys(peer || opt.peers || {}); // TODO: .keys( is slow
|
1498
|
+
console.STAT && console.STAT(S, +new Date - S, 'peer keys');
|
1499
|
+
(function go(){
|
1500
|
+
var S = +new Date;
|
1501
|
+
//Type.obj.map(peer || opt.peers, each); // in case peer is a peer list.
|
1502
|
+
loop = 1; var wr = meta.raw; meta.raw = raw; // quick perf hack
|
1503
|
+
var i = 0, p; while(i < 9 && (p = (pl||'')[i++])){
|
1504
|
+
if(!(p = ps[p] || (peer||'')[p])){ continue }
|
1505
|
+
mesh.say(msg, p);
|
1506
|
+
}
|
1507
|
+
meta.raw = wr; loop = 0;
|
1508
|
+
pl = pl.slice(i); // slicing after is faster than shifting during.
|
1509
|
+
console.STAT && console.STAT(S, +new Date - S, 'say loop');
|
1510
|
+
if(!pl.length){ return }
|
1511
|
+
puff(go, 0);
|
1512
|
+
ack && dup_track(ack); // keep for later
|
1513
|
+
}());
|
1514
|
+
return;
|
1515
|
+
}
|
1516
|
+
// TODO: PERF: consider splitting function here, so say loops do less work.
|
1517
|
+
if(!peer.wire && mesh.wire){ mesh.wire(peer); }
|
1518
|
+
if(id === peer.last){ return } peer.last = id; // was it just sent?
|
1519
|
+
if(peer === meta.via){ return false } // don't send back to self.
|
1520
|
+
if((tmp = meta.yo) && (tmp[peer.url] || tmp[peer.pid] || tmp[peer.id]) /*&& !o*/){ return false }
|
1521
|
+
console.STAT && console.STAT(S, ((DBG||meta).yp = +new Date) - (meta.y || S), 'say prep');
|
1522
|
+
!loop && ack && dup_track(ack); // streaming long responses needs to keep alive the ack.
|
1523
|
+
if(peer.batch){
|
1524
|
+
peer.tail = (tmp = peer.tail || 0) + raw.length;
|
1525
|
+
if(peer.tail <= opt.pack){
|
1526
|
+
peer.batch += (tmp?',':'')+raw;
|
1527
|
+
return;
|
1528
|
+
}
|
1529
|
+
flush(peer);
|
1530
|
+
}
|
1531
|
+
peer.batch = '['; // Prevents double JSON!
|
1532
|
+
var ST = +new Date;
|
1533
|
+
setTimeout(function(){
|
1534
|
+
console.STAT && console.STAT(ST, +new Date - ST, '0ms TO');
|
1535
|
+
flush(peer);
|
1536
|
+
}, opt.gap); // TODO: queuing/batching might be bad for low-latency video game performance! Allow opt out?
|
1537
|
+
send(raw, peer);
|
1538
|
+
console.STAT && (ack === peer.SI) && console.STAT(S, +new Date - peer.SH, 'say ack');
|
1539
|
+
};
|
1540
|
+
mesh.say.c = mesh.say.d = 0;
|
1541
|
+
// TODO: this caused a out-of-memory crash!
|
1542
|
+
mesh.raw = function(msg, peer){ // TODO: Clean this up / delete it / move logic out!
|
1543
|
+
if(!msg){ return '' }
|
1544
|
+
var meta = (msg._) || {}, put, tmp;
|
1545
|
+
if(tmp = meta.raw){ return tmp }
|
1546
|
+
if('string' == typeof msg){ return msg }
|
1547
|
+
var hash = msg['##'], ack = msg['@'];
|
1548
|
+
if(hash && ack){
|
1549
|
+
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!
|
1550
|
+
if(tmp = (dup.s[ack]||'').it){
|
1551
|
+
if(hash === tmp['##']){ return false } // if ask has a matching hash, acking is optional.
|
1552
|
+
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.
|
1553
|
+
}
|
1554
|
+
}
|
1555
|
+
if(!msg.dam && !msg['@']){
|
1556
|
+
var i = 0, to = []; tmp = opt.peers;
|
1557
|
+
for(var k in tmp){ var p = tmp[k]; // TODO: Make it up peers instead!
|
1558
|
+
to.push(p.url || p.pid || p.id);
|
1559
|
+
if(++i > 6){ break }
|
1560
|
+
}
|
1561
|
+
if(i > 1){ msg['><'] = to.join(); } // TODO: BUG! This gets set regardless of peers sent to! Detect?
|
1562
|
+
}
|
1563
|
+
if(msg.put && (tmp = msg.ok)){ msg.ok = {'@':(tmp['@']||1)-1, '/': (tmp['/']==msg._.near)? mesh.near : tmp['/']}; }
|
1564
|
+
if(put = meta.$put){
|
1565
|
+
tmp = {}; Object.keys(msg).forEach(function(k){ tmp[k] = msg[k]; });
|
1566
|
+
tmp.put = ':])([:';
|
1567
|
+
json(tmp, function(err, raw){
|
1568
|
+
if(err){ return } // TODO: Handle!!
|
1569
|
+
var S = +new Date;
|
1570
|
+
tmp = raw.indexOf('"put":":])([:"');
|
1571
|
+
res(u, raw = raw.slice(0, tmp+6) + put + raw.slice(tmp + 14));
|
1572
|
+
console.STAT && console.STAT(S, +new Date - S, 'say slice');
|
1573
|
+
});
|
1574
|
+
return;
|
1575
|
+
}
|
1576
|
+
json(msg, res);
|
1577
|
+
function res(err, raw){
|
1578
|
+
if(err){ return } // TODO: Handle!!
|
1579
|
+
meta.raw = raw; //if(meta && (raw||'').length < (999 * 99)){ meta.raw = raw } // HNPERF: If string too big, don't keep in memory.
|
1580
|
+
mesh.say(msg, peer);
|
1581
|
+
}
|
1582
|
+
};
|
1583
|
+
}());
|
1584
|
+
|
1585
|
+
function flush(peer){
|
1586
|
+
var tmp = peer.batch, t = 'string' == typeof tmp;
|
1587
|
+
if(t){ tmp += ']'; }// TODO: Prevent double JSON!
|
1588
|
+
peer.batch = peer.tail = null;
|
1589
|
+
if(!tmp){ return }
|
1590
|
+
if(t? 3 > tmp.length : !tmp.length){ return } // TODO: ^
|
1591
|
+
if(!t){try{tmp = (1 === tmp.length? tmp[0] : JSON.stringify(tmp));
|
1592
|
+
}catch(e){return opt.log('DAM JSON stringify error', e)}}
|
1593
|
+
if(!tmp){ return }
|
1594
|
+
send(tmp, peer);
|
1595
|
+
}
|
1596
|
+
// for now - find better place later.
|
1597
|
+
function send(raw, peer){ try{
|
1598
|
+
var wire = peer.wire;
|
1599
|
+
if(peer.say){
|
1600
|
+
peer.say(raw);
|
1601
|
+
} else
|
1602
|
+
if(wire.send){
|
1603
|
+
wire.send(raw);
|
1604
|
+
}
|
1605
|
+
mesh.say.d += raw.length||0; ++mesh.say.c; // STATS!
|
1606
|
+
}catch(e){
|
1607
|
+
(peer.queue = peer.queue || []).push(raw);
|
1608
|
+
}}
|
1609
|
+
|
1610
|
+
mesh.near = 0;
|
1611
|
+
mesh.hi = function(peer){
|
1612
|
+
var wire = peer.wire, tmp;
|
1613
|
+
if(!wire){ mesh.wire((peer.length && {url: peer, id: peer}) || peer); return }
|
1614
|
+
if(peer.id){
|
1615
|
+
opt.peers[peer.url || peer.id] = peer;
|
1616
|
+
} else {
|
1617
|
+
tmp = peer.id = peer.id || peer.url || String.random(9);
|
1618
|
+
mesh.say({dam: '?', pid: root.opt.pid}, opt.peers[tmp] = peer);
|
1619
|
+
delete dup.s[peer.last]; // IMPORTANT: see https://gun.eco/docs/DAM#self
|
1620
|
+
}
|
1621
|
+
if(!peer.met){
|
1622
|
+
mesh.near++;
|
1623
|
+
peer.met = +(new Date);
|
1624
|
+
root.on('hi', peer);
|
1625
|
+
}
|
1626
|
+
// @rogowski I need this here by default for now to fix go1dfish's bug
|
1627
|
+
tmp = peer.queue; peer.queue = [];
|
1628
|
+
setTimeout.each(tmp||[],function(msg){
|
1629
|
+
send(msg, peer);
|
1630
|
+
},0,9);
|
1631
|
+
//Type.obj.native && Type.obj.native(); // dirty place to check if other JS polluted.
|
1632
|
+
};
|
1633
|
+
mesh.bye = function(peer){
|
1634
|
+
peer.met && --mesh.near;
|
1635
|
+
delete peer.met;
|
1636
|
+
root.on('bye', peer);
|
1637
|
+
var tmp = +(new Date); tmp = (tmp - (peer.met||tmp));
|
1638
|
+
mesh.bye.time = ((mesh.bye.time || tmp) + tmp) / 2;
|
1639
|
+
};
|
1640
|
+
mesh.hear['!'] = function(msg, peer){ opt.log('Error:', msg.err); };
|
1641
|
+
mesh.hear['?'] = function(msg, peer){
|
1642
|
+
if(msg.pid){
|
1643
|
+
if(!peer.pid){ peer.pid = msg.pid; }
|
1644
|
+
if(msg['@']){ return }
|
1645
|
+
}
|
1646
|
+
mesh.say({dam: '?', pid: opt.pid, '@': msg['#']}, peer);
|
1647
|
+
delete dup.s[peer.last]; // IMPORTANT: see https://gun.eco/docs/DAM#self
|
1648
|
+
};
|
1649
|
+
mesh.hear['mob'] = function(msg, peer){ // NOTE: AXE will overload this with better logic.
|
1650
|
+
if(!msg.peers){ return }
|
1651
|
+
var peers = Object.keys(msg.peers), one = peers[(Math.random()*peers.length) >> 0];
|
1652
|
+
if(!one){ return }
|
1653
|
+
mesh.bye(peer);
|
1654
|
+
mesh.hi(one);
|
1655
|
+
};
|
1656
|
+
|
1657
|
+
root.on('create', function(root){
|
1658
|
+
root.opt.pid = root.opt.pid || String.random(9);
|
1659
|
+
this.to.next(root);
|
1660
|
+
root.on('out', mesh.say);
|
1661
|
+
});
|
1662
|
+
|
1663
|
+
root.on('bye', function(peer, tmp){
|
1664
|
+
peer = opt.peers[peer.id || peer] || peer;
|
1665
|
+
this.to.next(peer);
|
1666
|
+
peer.bye? peer.bye() : (tmp = peer.wire) && tmp.close && tmp.close();
|
1667
|
+
delete opt.peers[peer.id];
|
1668
|
+
peer.wire = null;
|
1669
|
+
});
|
1670
|
+
root.on('bye', function(peer, tmp){ this.to.next(peer);
|
1671
|
+
if(tmp = console.STAT){ tmp.peers = mesh.near; }
|
1672
|
+
if(!(tmp = peer.url)){ return } setTimeout(function(){ },opt.lack || 9000);
|
1673
|
+
});
|
1674
|
+
root.on('hi', function(peer, tmp){ this.to.next(peer);
|
1675
|
+
if(tmp = console.STAT){ tmp.peers = mesh.near; }
|
1676
|
+
if(opt.super){ return } // temporary (?) until we have better fix/solution?
|
1677
|
+
var souls = Object.keys(root.next||''); // TODO: .keys( is slow
|
1678
|
+
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()`."); }
|
1679
|
+
setTimeout.each(souls, function(soul){ var node = root.next[soul];
|
1680
|
+
if(opt.super || (node.ask||'')['']){ mesh.say({get: {'#': soul}}, peer); return }
|
1681
|
+
setTimeout.each(Object.keys(node.ask||''), function(key){ if(!key){ return }
|
1682
|
+
// is the lack of ## a !onion hint?
|
1683
|
+
mesh.say({'##': String.hash((root.graph[soul]||'')[key]), get: {'#': soul, '.': key}}, peer);
|
1684
|
+
// TODO: Switch this so Book could route?
|
1685
|
+
});
|
1686
|
+
});
|
1687
|
+
});
|
1688
|
+
|
1689
|
+
return mesh;
|
1690
|
+
}
|
1691
|
+
var u;
|
1692
|
+
|
1693
|
+
try{ module.exports = Mesh; }catch(e){}
|
1694
|
+
|
1695
|
+
})(USE, './mesh');
|
1696
|
+
USE(function(module){
|
1697
|
+
var Gun = USE('./index');
|
1698
|
+
Gun.Mesh = USE('./mesh');
|
1699
|
+
|
1700
|
+
// TODO: resync upon reconnect online/offline
|
1701
|
+
//window.ononline = window.onoffline = function(){ console.log('online?', navigator.onLine) }
|
1702
|
+
|
1703
|
+
Gun.on('opt', function(root){
|
1704
|
+
this.to.next(root);
|
1705
|
+
if(root.once){ return }
|
1706
|
+
var opt = root.opt;
|
1707
|
+
if(false === opt.WebSocket){ return }
|
1708
|
+
|
1709
|
+
var env = Gun.window || {};
|
1710
|
+
var websocket = opt.WebSocket || env.WebSocket || env.webkitWebSocket || env.mozWebSocket;
|
1711
|
+
if(!websocket){ return }
|
1712
|
+
opt.WebSocket = websocket;
|
1713
|
+
|
1714
|
+
var mesh = opt.mesh = opt.mesh || Gun.Mesh(root);
|
1715
|
+
|
1716
|
+
mesh.wire || opt.wire;
|
1717
|
+
mesh.wire = opt.wire = open;
|
1718
|
+
function open(peer){ try{
|
1719
|
+
if(!peer || !peer.url){ return wire && wire(peer) }
|
1720
|
+
var url = peer.url.replace(/^http/, 'ws');
|
1721
|
+
var wire = peer.wire = new opt.WebSocket(url);
|
1722
|
+
wire.onclose = function(){
|
1723
|
+
reconnect(peer);
|
1724
|
+
opt.mesh.bye(peer);
|
1725
|
+
};
|
1726
|
+
wire.onerror = function(err){
|
1727
|
+
reconnect(peer);
|
1728
|
+
};
|
1729
|
+
wire.onopen = function(){
|
1730
|
+
opt.mesh.hi(peer);
|
1731
|
+
};
|
1732
|
+
wire.onmessage = function(msg){
|
1733
|
+
if(!msg){ return }
|
1734
|
+
opt.mesh.hear(msg.data || msg, peer);
|
1735
|
+
};
|
1736
|
+
return wire;
|
1737
|
+
}catch(e){ opt.mesh.bye(peer); }}
|
1738
|
+
|
1739
|
+
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?
|
1740
|
+
|
1741
|
+
var wait = 2 * 999;
|
1742
|
+
function reconnect(peer){
|
1743
|
+
clearTimeout(peer.defer);
|
1744
|
+
if(!opt.peers[peer.url]){ return }
|
1745
|
+
if(doc && peer.retry <= 0){ return }
|
1746
|
+
peer.retry = (peer.retry || opt.retry+1 || 60) - ((-peer.tried + (peer.tried = +new Date) < wait*4)?1:0);
|
1747
|
+
peer.defer = setTimeout(function to(){
|
1748
|
+
if(doc && doc.hidden){ return setTimeout(to,wait) }
|
1749
|
+
open(peer);
|
1750
|
+
}, wait);
|
1751
|
+
}
|
1752
|
+
var doc = (''+u !== typeof document) && document;
|
1753
|
+
});
|
1754
|
+
var u;
|
1755
|
+
})(USE, './websocket');
|
1756
|
+
USE(function(module){
|
1757
|
+
if(typeof Gun === 'undefined'){ return }
|
1758
|
+
|
1759
|
+
var noop = function(){}, store;
|
1760
|
+
try{store = (Gun.window||noop).localStorage;}catch(e){}
|
1761
|
+
if(!store){
|
1762
|
+
Gun.log("Warning: No localStorage exists to persist data to!");
|
1763
|
+
store = {setItem: function(k,v){this[k]=v;}, removeItem: function(k){delete this[k];}, getItem: function(k){return this[k]}};
|
1764
|
+
}
|
1765
|
+
var json = JSON.stringifyAsync || function(v,cb,r,s){ var u; try{ cb(u, JSON.stringify(v,r,s)); }catch(e){ cb(e); } };
|
1766
|
+
|
1767
|
+
Gun.on('create', function lg(root){
|
1768
|
+
this.to.next(root);
|
1769
|
+
var opt = root.opt; root.graph; var acks = [], disk, to, size, stop;
|
1770
|
+
if(false === opt.localStorage){ return }
|
1771
|
+
opt.prefix = opt.file || 'gun/';
|
1772
|
+
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?
|
1773
|
+
}catch(e){ disk = lg[opt.prefix] = {}; }
|
1774
|
+
size = (size||'').length;
|
1775
|
+
|
1776
|
+
root.on('get', function(msg){
|
1777
|
+
this.to.next(msg);
|
1778
|
+
var lex = msg.get, soul, data, tmp, u;
|
1779
|
+
if(!lex || !(soul = lex['#'])){ return }
|
1780
|
+
data = disk[soul] || u;
|
1781
|
+
if(data && (tmp = lex['.']) && !Object.plain(tmp)){ // pluck!
|
1782
|
+
data = Gun.state.ify({}, tmp, Gun.state.is(data, tmp), data[tmp], soul);
|
1783
|
+
}
|
1784
|
+
//if(data){ (tmp = {})[soul] = data } // back into a graph.
|
1785
|
+
//setTimeout(function(){
|
1786
|
+
Gun.on.get.ack(msg, data); //root.on('in', {'@': msg['#'], put: tmp, lS:1});// || root.$});
|
1787
|
+
//}, Math.random() * 10); // FOR TESTING PURPOSES!
|
1788
|
+
});
|
1789
|
+
|
1790
|
+
root.on('put', function(msg){
|
1791
|
+
this.to.next(msg); // remember to call next middleware adapter
|
1792
|
+
var put = msg.put, soul = put['#'], key = put['.'], id = msg['#'], ok = msg.ok||''; // pull data off wire envelope
|
1793
|
+
disk[soul] = Gun.state.ify(disk[soul], key, put['>'], put[':'], soul); // merge into disk object
|
1794
|
+
if(stop && size > (4999880)){ root.on('in', {'@': id, err: "localStorage max!"}); return; }
|
1795
|
+
//if(!msg['@']){ acks.push(id) } // then ack any non-ack write. // TODO: use batch id.
|
1796
|
+
if(!msg['@'] && (!msg._.via || Math.random() < (ok['@'] / ok['/']))){ acks.push(id); } // then ack any non-ack write. // TODO: use batch id.
|
1797
|
+
if(to){ return }
|
1798
|
+
to = setTimeout(flush, 9+(size / 333)); // 0.1MB = 0.3s, 5MB = 15s
|
1799
|
+
});
|
1800
|
+
function flush(){
|
1801
|
+
if(!acks.length && ((setTimeout.turn||'').s||'').length){ setTimeout(flush,99); return; } // defer if "busy" && no saves.
|
1802
|
+
var ack = acks; clearTimeout(to); to = false; acks = [];
|
1803
|
+
json(disk, function(err, tmp){
|
1804
|
+
try{!err && store.setItem(opt.prefix, tmp);
|
1805
|
+
}catch(e){ err = stop = e || "localStorage failure"; }
|
1806
|
+
if(err){
|
1807
|
+
Gun.log(err + " Consider using GUN's IndexedDB plugin for RAD for more storage space, https://gun.eco/docs/RAD#install");
|
1808
|
+
root.on('localStorage:error', {err: err, get: opt.prefix, put: disk});
|
1809
|
+
}
|
1810
|
+
size = tmp.length;
|
1811
|
+
|
1812
|
+
//if(!err && !Object.empty(opt.peers)){ return } // only ack if there are no peers. // Switch this to probabilistic mode
|
1813
|
+
setTimeout.each(ack, function(id){
|
1814
|
+
root.on('in', {'@': id, err: err, ok: 0}); // localStorage isn't reliable, so make its `ok` code be a low number.
|
1815
|
+
},0,99);
|
1816
|
+
});
|
1817
|
+
}
|
1818
|
+
|
1819
|
+
});
|
1820
|
+
})(USE, './localStorage');
|
1821
|
+
|
1822
|
+
}());
|
1823
|
+
(function(){
|
1824
|
+
var u;
|
1825
|
+
if(''+u == typeof Gun){ return }
|
1826
|
+
var DEP = function(n){ console.warn("Warning! Deprecated internal utility will break in next version:", n); };
|
1827
|
+
// Generic javascript utilities.
|
1828
|
+
var Type = Gun;
|
1829
|
+
//Type.fns = Type.fn = {is: function(fn){ return (!!fn && fn instanceof Function) }}
|
1830
|
+
Type.fn = Type.fn || {is: function(fn){ DEP('fn'); return (!!fn && 'function' == typeof fn) }};
|
1831
|
+
Type.bi = Type.bi || {is: function(b){ DEP('bi');return (b instanceof Boolean || typeof b == 'boolean') }};
|
1832
|
+
Type.num = Type.num || {is: function(n){ DEP('num'); return !list_is(n) && ((n - parseFloat(n) + 1) >= 0 || Infinity === n || -Infinity === n) }};
|
1833
|
+
Type.text = Type.text || {is: function(t){ DEP('text'); return (typeof t == 'string') }};
|
1834
|
+
Type.text.ify = Type.text.ify || function(t){ DEP('text.ify');
|
1835
|
+
if(Type.text.is(t)){ return t }
|
1836
|
+
if(typeof JSON !== "undefined"){ return JSON.stringify(t) }
|
1837
|
+
return (t && t.toString)? t.toString() : t;
|
1838
|
+
};
|
1839
|
+
Type.text.random = Type.text.random || function(l, c){ DEP('text.random');
|
1840
|
+
var s = '';
|
1841
|
+
l = l || 24; // you are not going to make a 0 length random number, so no need to check type
|
1842
|
+
c = c || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXZabcdefghijklmnopqrstuvwxyz';
|
1843
|
+
while(l > 0){ s += c.charAt(Math.floor(Math.random() * c.length)); l--; }
|
1844
|
+
return s;
|
1845
|
+
};
|
1846
|
+
Type.text.match = Type.text.match || function(t, o){ var tmp, u; DEP('text.match');
|
1847
|
+
if('string' !== typeof t){ return false }
|
1848
|
+
if('string' == typeof o){ o = {'=': o}; }
|
1849
|
+
o = o || {};
|
1850
|
+
tmp = (o['='] || o['*'] || o['>'] || o['<']);
|
1851
|
+
if(t === tmp){ return true }
|
1852
|
+
if(u !== o['=']){ return false }
|
1853
|
+
tmp = (o['*'] || o['>'] || o['<']);
|
1854
|
+
if(t.slice(0, (tmp||'').length) === tmp){ return true }
|
1855
|
+
if(u !== o['*']){ return false }
|
1856
|
+
if(u !== o['>'] && u !== o['<']){
|
1857
|
+
return (t >= o['>'] && t <= o['<'])? true : false;
|
1858
|
+
}
|
1859
|
+
if(u !== o['>'] && t >= o['>']){ return true }
|
1860
|
+
if(u !== o['<'] && t <= o['<']){ return true }
|
1861
|
+
return false;
|
1862
|
+
};
|
1863
|
+
Type.text.hash = Type.text.hash || function(s, c){ // via SO
|
1864
|
+
DEP('text.hash');
|
1865
|
+
if(typeof s !== 'string'){ return }
|
1866
|
+
c = c || 0;
|
1867
|
+
if(!s.length){ return c }
|
1868
|
+
for(var i=0,l=s.length,n; i<l; ++i){
|
1869
|
+
n = s.charCodeAt(i);
|
1870
|
+
c = ((c<<5)-c)+n;
|
1871
|
+
c |= 0;
|
1872
|
+
}
|
1873
|
+
return c;
|
1874
|
+
};
|
1875
|
+
Type.list = Type.list || {is: function(l){ DEP('list'); return (l instanceof Array) }};
|
1876
|
+
Type.list.slit = Type.list.slit || Array.prototype.slice;
|
1877
|
+
Type.list.sort = Type.list.sort || function(k){ // creates a new sort function based off some key
|
1878
|
+
DEP('list.sort');
|
1879
|
+
return function(A,B){
|
1880
|
+
if(!A || !B){ return 0 } A = A[k]; B = B[k];
|
1881
|
+
if(A < B){ return -1 }else if(A > B){ return 1 }
|
1882
|
+
else { return 0 }
|
1883
|
+
}
|
1884
|
+
};
|
1885
|
+
Type.list.map = Type.list.map || function(l, c, _){ DEP('list.map'); return obj_map(l, c, _) };
|
1886
|
+
Type.list.index = 1; // change this to 0 if you want non-logical, non-mathematical, non-matrix, non-convenient array notation
|
1887
|
+
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 }};
|
1888
|
+
Type.obj.put = Type.obj.put || function(o, k, v){ DEP('obj.put'); return (o||{})[k] = v, o };
|
1889
|
+
Type.obj.has = Type.obj.has || function(o, k){ DEP('obj.has'); return o && Object.prototype.hasOwnProperty.call(o, k) };
|
1890
|
+
Type.obj.del = Type.obj.del || function(o, k){ DEP('obj.del');
|
1891
|
+
if(!o){ return }
|
1892
|
+
o[k] = null;
|
1893
|
+
delete o[k];
|
1894
|
+
return o;
|
1895
|
+
};
|
1896
|
+
Type.obj.as = Type.obj.as || function(o, k, v, u){ DEP('obj.as'); return o[k] = o[k] || (u === v? {} : v) };
|
1897
|
+
Type.obj.ify = Type.obj.ify || function(o){ DEP('obj.ify');
|
1898
|
+
if(obj_is(o)){ return o }
|
1899
|
+
try{o = JSON.parse(o);
|
1900
|
+
}catch(e){o={};} return o;
|
1901
|
+
}
|
1902
|
+
;(function(){ var u;
|
1903
|
+
function map(v,k){
|
1904
|
+
if(obj_has(this,k) && u !== this[k]){ return }
|
1905
|
+
this[k] = v;
|
1906
|
+
}
|
1907
|
+
Type.obj.to = Type.obj.to || function(from, to){ DEP('obj.to');
|
1908
|
+
to = to || {};
|
1909
|
+
obj_map(from, map, to);
|
1910
|
+
return to;
|
1911
|
+
};
|
1912
|
+
}());
|
1913
|
+
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
|
1914
|
+
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!
|
1915
|
+
}
|
1916
|
+
;(function(){
|
1917
|
+
function empty(v,i){ var n = this.n, u;
|
1918
|
+
if(n && (i === n || (obj_is(n) && obj_has(n, i)))){ return }
|
1919
|
+
if(u !== i){ return true }
|
1920
|
+
}
|
1921
|
+
Type.obj.empty = Type.obj.empty || function(o, n){ DEP('obj.empty');
|
1922
|
+
if(!o){ return true }
|
1923
|
+
return obj_map(o,empty,{n:n})? false : true;
|
1924
|
+
};
|
1925
|
+
}());
|
1926
|
+
(function(){
|
1927
|
+
function t(k,v){
|
1928
|
+
if(2 === arguments.length){
|
1929
|
+
t.r = t.r || {};
|
1930
|
+
t.r[k] = v;
|
1931
|
+
return;
|
1932
|
+
} t.r = t.r || [];
|
1933
|
+
t.r.push(k);
|
1934
|
+
} var keys = Object.keys, map;
|
1935
|
+
Object.keys = Object.keys || function(o){ return map(o, function(v,k,t){t(k);}) };
|
1936
|
+
Type.obj.map = map = Type.obj.map || function(l, c, _){ DEP('obj.map');
|
1937
|
+
var u, i = 0, x, r, ll, lle, f = 'function' == typeof c;
|
1938
|
+
t.r = u;
|
1939
|
+
if(keys && obj_is(l)){
|
1940
|
+
ll = keys(l); lle = true;
|
1941
|
+
}
|
1942
|
+
_ = _ || {};
|
1943
|
+
if(list_is(l) || ll){
|
1944
|
+
x = (ll || l).length;
|
1945
|
+
for(;i < x; i++){
|
1946
|
+
var ii = (i + Type.list.index);
|
1947
|
+
if(f){
|
1948
|
+
r = lle? c.call(_, l[ll[i]], ll[i], t) : c.call(_, l[i], ii, t);
|
1949
|
+
if(r !== u){ return r }
|
1950
|
+
} else {
|
1951
|
+
//if(Type.test.is(c,l[i])){ return ii } // should implement deep equality testing!
|
1952
|
+
if(c === l[lle? ll[i] : i]){ return ll? ll[i] : ii } // use this for now
|
1953
|
+
}
|
1954
|
+
}
|
1955
|
+
} else {
|
1956
|
+
for(i in l){
|
1957
|
+
if(f){
|
1958
|
+
if(obj_has(l,i)){
|
1959
|
+
r = _? c.call(_, l[i], i, t) : c(l[i], i, t);
|
1960
|
+
if(r !== u){ return r }
|
1961
|
+
}
|
1962
|
+
} else {
|
1963
|
+
//if(a.test.is(c,l[i])){ return i } // should implement deep equality testing!
|
1964
|
+
if(c === l[i]){ return i } // use this for now
|
1965
|
+
}
|
1966
|
+
}
|
1967
|
+
}
|
1968
|
+
return f? t.r : Type.list.index? 0 : -1;
|
1969
|
+
};
|
1970
|
+
}());
|
1971
|
+
Type.time = Type.time || {};
|
1972
|
+
Type.time.is = Type.time.is || function(t){ DEP('time'); return t? t instanceof Date : (+new Date().getTime()) };
|
1973
|
+
|
1974
|
+
var fn_is = Type.fn.is;
|
1975
|
+
var list_is = Type.list.is;
|
1976
|
+
var obj = Type.obj, obj_is = obj.is, obj_has = obj.has, obj_map = obj.map;
|
1977
|
+
|
1978
|
+
var Val = {};
|
1979
|
+
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.
|
1980
|
+
if(v === u){ return false }
|
1981
|
+
if(v === null){ return true } // "deletes", nulling out keys.
|
1982
|
+
if(v === Infinity){ return false } // we want this to be, but JSON does not support it, sad face.
|
1983
|
+
if(text_is(v) // by "text" we mean strings.
|
1984
|
+
|| bi_is(v) // by "binary" we mean boolean.
|
1985
|
+
|| num_is(v)){ // by "number" we mean integers or decimals.
|
1986
|
+
return true; // simple values are valid.
|
1987
|
+
}
|
1988
|
+
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.
|
1989
|
+
};
|
1990
|
+
Val.link = Val.rel = {_: '#'};
|
1991
|
+
(function(){
|
1992
|
+
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'}
|
1993
|
+
if(v && v[rel_] && !v._ && obj_is(v)){ // must be an object.
|
1994
|
+
var o = {};
|
1995
|
+
obj_map(v, map, o);
|
1996
|
+
if(o.id){ // a valid id was found.
|
1997
|
+
return o.id; // yay! Return it.
|
1998
|
+
}
|
1999
|
+
}
|
2000
|
+
return false; // the value was not a valid soul relation.
|
2001
|
+
};
|
2002
|
+
function map(s, k){ var o = this; // map over the object...
|
2003
|
+
if(o.id){ return o.id = false } // if ID is already defined AND we're still looping through the object, it is considered invalid.
|
2004
|
+
if(k == rel_ && text_is(s)){ // the key should be '#' and have a text value.
|
2005
|
+
o.id = s; // we found the soul!
|
2006
|
+
} else {
|
2007
|
+
return o.id = false; // if there exists anything else on the object that isn't the soul, then it is considered invalid.
|
2008
|
+
}
|
2009
|
+
}
|
2010
|
+
}());
|
2011
|
+
Val.link.ify = function(t){ DEP('val.link.ify'); return obj_put({}, rel_, t) }; // convert a soul into a relation and return it.
|
2012
|
+
Type.obj.has._ = '.';
|
2013
|
+
var rel_ = Val.link._, u;
|
2014
|
+
var bi_is = Type.bi.is;
|
2015
|
+
var num_is = Type.num.is;
|
2016
|
+
var text_is = Type.text.is;
|
2017
|
+
var obj = Type.obj, obj_is = obj.is, obj_put = obj.put, obj_map = obj.map;
|
2018
|
+
|
2019
|
+
Type.val = Type.val || Val;
|
2020
|
+
|
2021
|
+
var Node = {_: '_'};
|
2022
|
+
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.
|
2023
|
+
Node.soul.ify = function(n, o){ DEP('node.soul.ify'); // put a soul on an object.
|
2024
|
+
o = (typeof o === 'string')? {soul: o} : o || {};
|
2025
|
+
n = n || {}; // make sure it exists.
|
2026
|
+
n._ = n._ || {}; // make sure meta exists.
|
2027
|
+
n._[soul_] = o.soul || n._[soul_] || text_random(); // put the soul on it.
|
2028
|
+
return n;
|
2029
|
+
};
|
2030
|
+
Node.soul._ = Val.link._;
|
2031
|
+
(function(){
|
2032
|
+
Node.is = function(n, cb, as){ DEP('node.is'); var s; // checks to see if an object is a valid node.
|
2033
|
+
if(!obj_is(n)){ return false } // must be an object.
|
2034
|
+
if(s = Node.soul(n)){ // must have a soul on it.
|
2035
|
+
return !obj_map(n, map, {as:as,cb:cb,s:s,n:n});
|
2036
|
+
}
|
2037
|
+
return false; // nope! This was not a valid node.
|
2038
|
+
};
|
2039
|
+
function map(v, k){ // we invert this because the way we check for this is via a negation.
|
2040
|
+
if(k === Node._){ return } // skip over the metadata.
|
2041
|
+
if(!Val.is(v)){ return true } // it is true that this is an invalid node.
|
2042
|
+
if(this.cb){ this.cb.call(this.as, v, k, this.n, this.s); } // optionally callback each key/value.
|
2043
|
+
}
|
2044
|
+
}());
|
2045
|
+
(function(){
|
2046
|
+
Node.ify = function(obj, o, as){ DEP('node.ify'); // returns a node from a shallow object.
|
2047
|
+
if(!o){ o = {}; }
|
2048
|
+
else if(typeof o === 'string'){ o = {soul: o}; }
|
2049
|
+
else if('function' == typeof o){ o = {map: o}; }
|
2050
|
+
if(o.map){ o.node = o.map.call(as, obj, u, o.node || {}); }
|
2051
|
+
if(o.node = Node.soul.ify(o.node || {}, o)){
|
2052
|
+
obj_map(obj, map, {o:o,as:as});
|
2053
|
+
}
|
2054
|
+
return o.node; // This will only be a valid node if the object wasn't already deep!
|
2055
|
+
};
|
2056
|
+
function map(v, k){ var o = this.o, tmp, u; // iterate over each key/value.
|
2057
|
+
if(o.map){
|
2058
|
+
tmp = o.map.call(this.as, v, ''+k, o.node);
|
2059
|
+
if(u === tmp){
|
2060
|
+
obj_del(o.node, k);
|
2061
|
+
} else
|
2062
|
+
if(o.node){ o.node[k] = tmp; }
|
2063
|
+
return;
|
2064
|
+
}
|
2065
|
+
if(Val.is(v)){
|
2066
|
+
o.node[k] = v;
|
2067
|
+
}
|
2068
|
+
}
|
2069
|
+
}());
|
2070
|
+
var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_map = obj.map;
|
2071
|
+
var text = Type.text, text_random = text.random;
|
2072
|
+
var soul_ = Node.soul._;
|
2073
|
+
var u;
|
2074
|
+
Type.node = Type.node || Node;
|
2075
|
+
|
2076
|
+
var State = Type.state;
|
2077
|
+
State.lex = function(){ DEP('state.lex'); return State().toString(36).replace('.','') };
|
2078
|
+
State.to = function(from, k, to){ DEP('state.to');
|
2079
|
+
var val = (from||{})[k];
|
2080
|
+
if(obj_is(val)){
|
2081
|
+
val = obj_copy(val);
|
2082
|
+
}
|
2083
|
+
return State.ify(to, k, State.is(from, k), val, Node.soul(from));
|
2084
|
+
}
|
2085
|
+
;(function(){
|
2086
|
+
State.map = function(cb, s, as){ DEP('state.map'); var u; // for use with Node.ify
|
2087
|
+
var o = obj_is(o = cb || s)? o : null;
|
2088
|
+
cb = fn_is(cb = cb || s)? cb : null;
|
2089
|
+
if(o && !cb){
|
2090
|
+
s = num_is(s)? s : State();
|
2091
|
+
o[N_] = o[N_] || {};
|
2092
|
+
obj_map(o, map, {o:o,s:s});
|
2093
|
+
return o;
|
2094
|
+
}
|
2095
|
+
as = as || obj_is(s)? s : u;
|
2096
|
+
s = num_is(s)? s : State();
|
2097
|
+
return function(v, k, o, opt){
|
2098
|
+
if(!cb){
|
2099
|
+
map.call({o: o, s: s}, v,k);
|
2100
|
+
return v;
|
2101
|
+
}
|
2102
|
+
cb.call(as || this || {}, v, k, o, opt);
|
2103
|
+
if(obj_has(o,k) && u === o[k]){ return }
|
2104
|
+
map.call({o: o, s: s}, v,k);
|
2105
|
+
}
|
2106
|
+
};
|
2107
|
+
function map(v,k){
|
2108
|
+
if(N_ === k){ return }
|
2109
|
+
State.ify(this.o, k, this.s) ;
|
2110
|
+
}
|
2111
|
+
}());
|
2112
|
+
var obj = Type.obj; obj.as; var obj_has = obj.has, obj_is = obj.is, obj_map = obj.map, obj_copy = obj.copy;
|
2113
|
+
var num = Type.num, num_is = num.is;
|
2114
|
+
var fn = Type.fn, fn_is = fn.is;
|
2115
|
+
var N_ = Node._, u;
|
2116
|
+
|
2117
|
+
var Graph = {};
|
2118
|
+
(function(){
|
2119
|
+
Graph.is = function(g, cb, fn, as){ DEP('graph.is'); // checks to see if an object is a valid graph.
|
2120
|
+
if(!g || !obj_is(g) || obj_empty(g)){ return false } // must be an object.
|
2121
|
+
return !obj_map(g, map, {cb:cb,fn:fn,as:as}); // makes sure it wasn't an empty object.
|
2122
|
+
};
|
2123
|
+
function map(n, s){ // we invert this because the way'? we check for this is via a negation.
|
2124
|
+
if(!n || s !== Node.soul(n) || !Node.is(n, this.fn, this.as)){ return true } // it is true that this is an invalid graph.
|
2125
|
+
if(!this.cb){ return }
|
2126
|
+
nf.n = n; nf.as = this.as; // sequential race conditions aren't races.
|
2127
|
+
this.cb.call(nf.as, n, s, nf);
|
2128
|
+
}
|
2129
|
+
function nf(fn){ // optional callback for each node.
|
2130
|
+
if(fn){ Node.is(nf.n, fn, nf.as); } // where we then have an optional callback for each key/value.
|
2131
|
+
}
|
2132
|
+
}());
|
2133
|
+
(function(){
|
2134
|
+
Graph.ify = function(obj, env, as){ DEP('graph.ify');
|
2135
|
+
var at = {path: [], obj: obj};
|
2136
|
+
if(!env){
|
2137
|
+
env = {};
|
2138
|
+
} else
|
2139
|
+
if(typeof env === 'string'){
|
2140
|
+
env = {soul: env};
|
2141
|
+
} else
|
2142
|
+
if('function' == typeof env){
|
2143
|
+
env.map = env;
|
2144
|
+
}
|
2145
|
+
if(typeof as === 'string'){
|
2146
|
+
env.soul = env.soul || as;
|
2147
|
+
as = u;
|
2148
|
+
}
|
2149
|
+
if(env.soul){
|
2150
|
+
at.link = Val.link.ify(env.soul);
|
2151
|
+
}
|
2152
|
+
env.shell = (as||{}).shell;
|
2153
|
+
env.graph = env.graph || {};
|
2154
|
+
env.seen = env.seen || [];
|
2155
|
+
env.as = env.as || as;
|
2156
|
+
node(env, at);
|
2157
|
+
env.root = at.node;
|
2158
|
+
return env.graph;
|
2159
|
+
};
|
2160
|
+
function node(env, at){ var tmp;
|
2161
|
+
if(tmp = seen(env, at)){ return tmp }
|
2162
|
+
at.env = env;
|
2163
|
+
at.soul = soul;
|
2164
|
+
if(Node.ify(at.obj, map, at)){
|
2165
|
+
at.link = at.link || Val.link.ify(Node.soul(at.node));
|
2166
|
+
if(at.obj !== env.shell){
|
2167
|
+
env.graph[Val.link.is(at.link)] = at.node;
|
2168
|
+
}
|
2169
|
+
}
|
2170
|
+
return at;
|
2171
|
+
}
|
2172
|
+
function map(v,k,n){
|
2173
|
+
var at = this, env = at.env, is, tmp;
|
2174
|
+
if(Node._ === k && obj_has(v,Val.link._)){
|
2175
|
+
return n._; // TODO: Bug?
|
2176
|
+
}
|
2177
|
+
if(!(is = valid(v,k,n, at,env))){ return }
|
2178
|
+
if(!k){
|
2179
|
+
at.node = at.node || n || {};
|
2180
|
+
if(obj_has(v, Node._) && Node.soul(v)){ // ? for safety ?
|
2181
|
+
at.node._ = obj_copy(v._);
|
2182
|
+
}
|
2183
|
+
at.node = Node.soul.ify(at.node, Val.link.is(at.link));
|
2184
|
+
at.link = at.link || Val.link.ify(Node.soul(at.node));
|
2185
|
+
}
|
2186
|
+
if(tmp = env.map){
|
2187
|
+
tmp.call(env.as || {}, v,k,n, at);
|
2188
|
+
if(obj_has(n,k)){
|
2189
|
+
v = n[k];
|
2190
|
+
if(u === v){
|
2191
|
+
obj_del(n, k);
|
2192
|
+
return;
|
2193
|
+
}
|
2194
|
+
if(!(is = valid(v,k,n, at,env))){ return }
|
2195
|
+
}
|
2196
|
+
}
|
2197
|
+
if(!k){ return at.node }
|
2198
|
+
if(true === is){
|
2199
|
+
return v;
|
2200
|
+
}
|
2201
|
+
tmp = node(env, {obj: v, path: at.path.concat(k)});
|
2202
|
+
if(!tmp.node){ return }
|
2203
|
+
return tmp.link; //{'#': Node.soul(tmp.node)};
|
2204
|
+
}
|
2205
|
+
function soul(id){ var at = this;
|
2206
|
+
var prev = Val.link.is(at.link), graph = at.env.graph;
|
2207
|
+
at.link = at.link || Val.link.ify(id);
|
2208
|
+
at.link[Val.link._] = id;
|
2209
|
+
if(at.node && at.node[Node._]){
|
2210
|
+
at.node[Node._][Val.link._] = id;
|
2211
|
+
}
|
2212
|
+
if(obj_has(graph, prev)){
|
2213
|
+
graph[id] = graph[prev];
|
2214
|
+
obj_del(graph, prev);
|
2215
|
+
}
|
2216
|
+
}
|
2217
|
+
function valid(v,k,n, at,env){ var tmp;
|
2218
|
+
if(Val.is(v)){ return true }
|
2219
|
+
if(obj_is(v)){ return 1 }
|
2220
|
+
if(tmp = env.invalid){
|
2221
|
+
v = tmp.call(env.as || {}, v,k,n);
|
2222
|
+
return valid(v,k,n, at,env);
|
2223
|
+
}
|
2224
|
+
env.err = "Invalid value at '" + at.path.concat(k).join('.') + "'!";
|
2225
|
+
if(Type.list.is(v)){ env.err += " Use `.set(item)` instead of an Array."; }
|
2226
|
+
}
|
2227
|
+
function seen(env, at){
|
2228
|
+
var arr = env.seen, i = arr.length, has;
|
2229
|
+
while(i--){ has = arr[i];
|
2230
|
+
if(at.obj === has.obj){ return has }
|
2231
|
+
}
|
2232
|
+
arr.push(at);
|
2233
|
+
}
|
2234
|
+
}());
|
2235
|
+
Graph.node = function(node){ DEP('graph.node');
|
2236
|
+
var soul = Node.soul(node);
|
2237
|
+
if(!soul){ return }
|
2238
|
+
return obj_put({}, soul, node);
|
2239
|
+
}
|
2240
|
+
;(function(){
|
2241
|
+
Graph.to = function(graph, root, opt){ DEP('graph.to');
|
2242
|
+
if(!graph){ return }
|
2243
|
+
var obj = {};
|
2244
|
+
opt = opt || {seen: {}};
|
2245
|
+
obj_map(graph[root], map, {obj:obj, graph: graph, opt: opt});
|
2246
|
+
return obj;
|
2247
|
+
};
|
2248
|
+
function map(v,k){ var tmp, obj;
|
2249
|
+
if(Node._ === k){
|
2250
|
+
if(obj_empty(v, Val.link._)){
|
2251
|
+
return;
|
2252
|
+
}
|
2253
|
+
this.obj[k] = obj_copy(v);
|
2254
|
+
return;
|
2255
|
+
}
|
2256
|
+
if(!(tmp = Val.link.is(v))){
|
2257
|
+
this.obj[k] = v;
|
2258
|
+
return;
|
2259
|
+
}
|
2260
|
+
if(obj = this.opt.seen[tmp]){
|
2261
|
+
this.obj[k] = obj;
|
2262
|
+
return;
|
2263
|
+
}
|
2264
|
+
this.obj[k] = this.opt.seen[tmp] = Graph.to(this.graph, tmp, this.opt);
|
2265
|
+
}
|
2266
|
+
}());
|
2267
|
+
var fn_is = Type.fn.is;
|
2268
|
+
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;
|
2269
|
+
var u;
|
2270
|
+
Type.graph = Type.graph || Graph;
|
2271
|
+
}());
|
2272
|
+
} (gun));
|
2273
|
+
return gun.exports;
|
2274
|
+
}
|
2275
|
+
|
2276
|
+
(function (module) {
|
2277
|
+
(function (root, factory) {
|
2278
|
+
if (module.exports) {
|
2279
|
+
module.exports = factory(
|
2280
|
+
requireGun(),
|
2281
|
+
require$$1,
|
2282
|
+
require$$2
|
2283
|
+
);
|
2284
|
+
} else {
|
2285
|
+
factory(root.Gun, root.SEA, root.ethers);
|
2286
|
+
}
|
2287
|
+
})(typeof self !== "undefined" ? self : commonjsGlobal, function (Gun, SEA, ethers) {
|
2288
|
+
console.log("Factory del plugin Gun-Eth chiamata");
|
2289
|
+
|
2290
|
+
const MESSAGE_TO_SIGN = "Accesso a GunDB con Ethereum";
|
2291
|
+
|
2292
|
+
// Funzione per verificare se ethers è disponibile
|
2293
|
+
function checkEthers() {
|
2294
|
+
if (typeof ethers === "undefined") {
|
2295
|
+
console.error(
|
2296
|
+
"Ethers.js non è disponibile. Assicurati che sia caricato prima di questo script."
|
2297
|
+
);
|
2298
|
+
return false;
|
2299
|
+
}
|
2300
|
+
console.log("Ethers version:", ethers.version);
|
2301
|
+
return true;
|
2302
|
+
}
|
2303
|
+
|
2304
|
+
// Global variables
|
2305
|
+
let SHINE_ABI = [
|
2306
|
+
{
|
2307
|
+
anonymous: false,
|
2308
|
+
inputs: [
|
2309
|
+
{
|
2310
|
+
indexed: true,
|
2311
|
+
internalType: "bytes",
|
2312
|
+
name: "nodeId",
|
2313
|
+
type: "bytes",
|
2314
|
+
},
|
2315
|
+
{
|
2316
|
+
indexed: false,
|
2317
|
+
internalType: "bytes32",
|
2318
|
+
name: "contentHash",
|
2319
|
+
type: "bytes32",
|
2320
|
+
},
|
2321
|
+
{
|
2322
|
+
indexed: false,
|
2323
|
+
internalType: "address",
|
2324
|
+
name: "updater",
|
2325
|
+
type: "address",
|
2326
|
+
},
|
2327
|
+
],
|
2328
|
+
name: "DataUpdated",
|
2329
|
+
type: "event",
|
2330
|
+
},
|
2331
|
+
{
|
2332
|
+
inputs: [
|
2333
|
+
{
|
2334
|
+
internalType: "bytes[]",
|
2335
|
+
name: "nodeIds",
|
2336
|
+
type: "bytes[]",
|
2337
|
+
},
|
2338
|
+
{
|
2339
|
+
internalType: "bytes32[]",
|
2340
|
+
name: "contentHashes",
|
2341
|
+
type: "bytes32[]",
|
2342
|
+
},
|
2343
|
+
],
|
2344
|
+
name: "batchUpdateData",
|
2345
|
+
outputs: [],
|
2346
|
+
stateMutability: "nonpayable",
|
2347
|
+
type: "function",
|
2348
|
+
},
|
2349
|
+
{
|
2350
|
+
inputs: [
|
2351
|
+
{
|
2352
|
+
internalType: "bytes",
|
2353
|
+
name: "nodeId",
|
2354
|
+
type: "bytes",
|
2355
|
+
},
|
2356
|
+
],
|
2357
|
+
name: "getLatestRecord",
|
2358
|
+
outputs: [
|
2359
|
+
{
|
2360
|
+
internalType: "bytes32",
|
2361
|
+
name: "",
|
2362
|
+
type: "bytes32",
|
2363
|
+
},
|
2364
|
+
{
|
2365
|
+
internalType: "uint256",
|
2366
|
+
name: "",
|
2367
|
+
type: "uint256",
|
2368
|
+
},
|
2369
|
+
{
|
2370
|
+
internalType: "address",
|
2371
|
+
name: "",
|
2372
|
+
type: "address",
|
2373
|
+
},
|
2374
|
+
],
|
2375
|
+
stateMutability: "view",
|
2376
|
+
type: "function",
|
2377
|
+
},
|
2378
|
+
{
|
2379
|
+
inputs: [
|
2380
|
+
{
|
2381
|
+
internalType: "bytes",
|
2382
|
+
name: "",
|
2383
|
+
type: "bytes",
|
2384
|
+
},
|
2385
|
+
],
|
2386
|
+
name: "nodeData",
|
2387
|
+
outputs: [
|
2388
|
+
{
|
2389
|
+
internalType: "bytes32",
|
2390
|
+
name: "contentHash",
|
2391
|
+
type: "bytes32",
|
2392
|
+
},
|
2393
|
+
{
|
2394
|
+
internalType: "uint256",
|
2395
|
+
name: "timestamp",
|
2396
|
+
type: "uint256",
|
2397
|
+
},
|
2398
|
+
{
|
2399
|
+
internalType: "address",
|
2400
|
+
name: "updater",
|
2401
|
+
type: "address",
|
2402
|
+
},
|
2403
|
+
],
|
2404
|
+
stateMutability: "view",
|
2405
|
+
type: "function",
|
2406
|
+
},
|
2407
|
+
{
|
2408
|
+
inputs: [
|
2409
|
+
{
|
2410
|
+
internalType: "bytes",
|
2411
|
+
name: "nodeId",
|
2412
|
+
type: "bytes",
|
2413
|
+
},
|
2414
|
+
{
|
2415
|
+
internalType: "bytes32",
|
2416
|
+
name: "contentHash",
|
2417
|
+
type: "bytes32",
|
2418
|
+
},
|
2419
|
+
],
|
2420
|
+
name: "updateData",
|
2421
|
+
outputs: [],
|
2422
|
+
stateMutability: "nonpayable",
|
2423
|
+
type: "function",
|
2424
|
+
},
|
2425
|
+
{
|
2426
|
+
inputs: [
|
2427
|
+
{
|
2428
|
+
internalType: "bytes",
|
2429
|
+
name: "nodeId",
|
2430
|
+
type: "bytes",
|
2431
|
+
},
|
2432
|
+
{
|
2433
|
+
internalType: "bytes32",
|
2434
|
+
name: "contentHash",
|
2435
|
+
type: "bytes32",
|
2436
|
+
},
|
2437
|
+
],
|
2438
|
+
name: "verifyData",
|
2439
|
+
outputs: [
|
2440
|
+
{
|
2441
|
+
internalType: "bool",
|
2442
|
+
name: "",
|
2443
|
+
type: "bool",
|
2444
|
+
},
|
2445
|
+
{
|
2446
|
+
internalType: "uint256",
|
2447
|
+
name: "",
|
2448
|
+
type: "uint256",
|
2449
|
+
},
|
2450
|
+
{
|
2451
|
+
internalType: "address",
|
2452
|
+
name: "",
|
2453
|
+
type: "address",
|
2454
|
+
},
|
2455
|
+
],
|
2456
|
+
stateMutability: "view",
|
2457
|
+
type: "function",
|
2458
|
+
},
|
2459
|
+
];
|
2460
|
+
|
2461
|
+
let SHINE_OPTIMISM_SEPOLIA = "0x43D838b683F772F08f321E5FA265ad3e333BE9C2";
|
2462
|
+
let SHINE_CONTRACT_ADDRESS;
|
2463
|
+
let rpcUrl = "";
|
2464
|
+
let privateKey = "";
|
2465
|
+
|
2466
|
+
/**
|
2467
|
+
* Funzione per ottenere il signer
|
2468
|
+
* @returns {Promise<ethers.Signer>} Il signer.
|
2469
|
+
*/
|
2470
|
+
const getSigner = async () => {
|
2471
|
+
if (rpcUrl && privateKey) {
|
2472
|
+
// Modalità standalone
|
2473
|
+
const provider = new ethers.JsonRpcProvider(rpcUrl);
|
2474
|
+
return new ethers.Wallet(privateKey, provider);
|
2475
|
+
} else if (
|
2476
|
+
typeof window !== "undefined" &&
|
2477
|
+
typeof window.ethereum !== "undefined"
|
2478
|
+
) {
|
2479
|
+
// Modalità browser
|
2480
|
+
await window.ethereum.request({ method: "eth_requestAccounts" });
|
2481
|
+
const provider = new ethers.BrowserProvider(window.ethereum);
|
2482
|
+
return provider.getSigner();
|
2483
|
+
} else {
|
2484
|
+
throw new Error("No valid Ethereum provider found");
|
2485
|
+
}
|
2486
|
+
};
|
2487
|
+
|
2488
|
+
/**
|
2489
|
+
* Sets standalone configuration for Gun.
|
2490
|
+
* @param {string} newRpcUrl - The new RPC URL.
|
2491
|
+
* @param {string} newPrivateKey - The new private key.
|
2492
|
+
* @returns {Gun} The Gun instance for chaining.
|
2493
|
+
*/
|
2494
|
+
Gun.chain.setStandaloneConfig = function (newRpcUrl, newPrivateKey) {
|
2495
|
+
rpcUrl = newRpcUrl;
|
2496
|
+
privateKey = newPrivateKey;
|
2497
|
+
console.log("Standalone configuration set");
|
2498
|
+
return this;
|
2499
|
+
};
|
2500
|
+
|
2501
|
+
/**
|
2502
|
+
* Verifies an Ethereum signature.
|
2503
|
+
* @param {string} message - The original message that was signed.
|
2504
|
+
* @param {string} signature - The signature to verify.
|
2505
|
+
* @returns {Promise<string|null>} The recovered address or null if verification fails.
|
2506
|
+
*/
|
2507
|
+
Gun.chain.verifySignature = async function (message, signature) {
|
2508
|
+
try {
|
2509
|
+
const recoveredAddress = ethers.verifyMessage(message, signature);
|
2510
|
+
return recoveredAddress;
|
2511
|
+
} catch (error) {
|
2512
|
+
console.error("Error verifying signature:", error);
|
2513
|
+
return null;
|
2514
|
+
}
|
2515
|
+
};
|
2516
|
+
|
2517
|
+
/**
|
2518
|
+
* Generates a password from a signature.
|
2519
|
+
* @param {string} signature - The signature to derive the password from.
|
2520
|
+
* @returns {string|null} The generated password or null if generation fails.
|
2521
|
+
*/
|
2522
|
+
Gun.chain.generatePassword = function (signature) {
|
2523
|
+
try {
|
2524
|
+
const hexSignature = ethers.hexlify(signature);
|
2525
|
+
const hash = ethers.keccak256(hexSignature);
|
2526
|
+
console.log("Generated password:", hash);
|
2527
|
+
return hash;
|
2528
|
+
} catch (error) {
|
2529
|
+
console.error("Error generating password:", error);
|
2530
|
+
return null;
|
2531
|
+
}
|
2532
|
+
};
|
2533
|
+
|
2534
|
+
/**
|
2535
|
+
* Creates an Ethereum signature for a given message.
|
2536
|
+
* @param {string} message - The message to sign.
|
2537
|
+
* @returns {Promise<string|null>} The signature or null if signing fails.
|
2538
|
+
*/
|
2539
|
+
Gun.chain.createSignature = async function (message) {
|
2540
|
+
try {
|
2541
|
+
// Verifica se il messaggio è uguale a MESSAGE_TO_SIGN
|
2542
|
+
if (message !== MESSAGE_TO_SIGN) {
|
2543
|
+
throw new Error(
|
2544
|
+
"Invalid message, valid message is: " + MESSAGE_TO_SIGN
|
2545
|
+
);
|
2546
|
+
}
|
2547
|
+
const signer = await getSigner();
|
2548
|
+
const signature = await signer.signMessage(message);
|
2549
|
+
console.log("Signature created:", signature);
|
2550
|
+
return signature;
|
2551
|
+
} catch (error) {
|
2552
|
+
console.error("Error creating signature:", error);
|
2553
|
+
return null;
|
2554
|
+
}
|
2555
|
+
};
|
2556
|
+
|
2557
|
+
/**
|
2558
|
+
* Creates and stores an encrypted key pair for a given address.
|
2559
|
+
* @param {string} address - The Ethereum address to associate with the key pair.
|
2560
|
+
* @param {string} signature - The signature to use for encryption.
|
2561
|
+
* @returns {Promise<void>}
|
2562
|
+
*/
|
2563
|
+
Gun.chain.createAndStoreEncryptedPair = async function (address, signature) {
|
2564
|
+
try {
|
2565
|
+
const gun = this;
|
2566
|
+
const pair = await SEA.pair();
|
2567
|
+
const encryptedPair = await SEA.encrypt(JSON.stringify(pair), signature);
|
2568
|
+
await gun.get("gun-eth").get("users").get(address).put({ encryptedPair });
|
2569
|
+
console.log("Encrypted pair stored for:", address);
|
2570
|
+
} catch (error) {
|
2571
|
+
console.error("Error creating and storing encrypted pair:", error);
|
2572
|
+
}
|
2573
|
+
};
|
2574
|
+
|
2575
|
+
/**
|
2576
|
+
* Retrieves and decrypts a stored key pair for a given address.
|
2577
|
+
* @param {string} address - The Ethereum address associated with the key pair.
|
2578
|
+
* @param {string} signature - The signature to use for decryption.
|
2579
|
+
* @returns {Promise<Object|null>} The decrypted key pair or null if retrieval fails.
|
2580
|
+
*/
|
2581
|
+
Gun.chain.getAndDecryptPair = async function (address, signature) {
|
2582
|
+
try {
|
2583
|
+
const gun = this;
|
2584
|
+
const encryptedData = await gun
|
2585
|
+
.get("gun-eth")
|
2586
|
+
.get("users")
|
2587
|
+
.get(address)
|
2588
|
+
.get("encryptedPair")
|
2589
|
+
.then();
|
2590
|
+
if (!encryptedData) {
|
2591
|
+
throw new Error("No encrypted data found for this address");
|
2592
|
+
}
|
2593
|
+
const decryptedPair = await SEA.decrypt(encryptedData, signature);
|
2594
|
+
console.log(decryptedPair);
|
2595
|
+
return decryptedPair;
|
2596
|
+
} catch (error) {
|
2597
|
+
console.error("Error retrieving and decrypting pair:", error);
|
2598
|
+
return null;
|
2599
|
+
}
|
2600
|
+
};
|
2601
|
+
|
2602
|
+
/**
|
2603
|
+
* SHINE (Secure Hybrid Information and Network Environment) functionality.
|
2604
|
+
* @param {string} chain - The blockchain to use (e.g., "optimismSepolia").
|
2605
|
+
* @param {string} nodeId - The ID of the node to verify or write.
|
2606
|
+
* @param {Object} data - The data to write (if writing).
|
2607
|
+
* @param {Function} callback - Callback function to handle the result.
|
2608
|
+
* @returns {Gun} The Gun instance for chaining.
|
2609
|
+
*/
|
2610
|
+
Gun.chain.shine = function (chain, nodeId, data, callback) {
|
2611
|
+
console.log("SHINE plugin called with:", { chain, nodeId, data });
|
2612
|
+
|
2613
|
+
if (!checkEthers()) {
|
2614
|
+
if (callback) callback({ err: "Ethers.js non è disponibile" });
|
2615
|
+
return this;
|
2616
|
+
}
|
2617
|
+
|
2618
|
+
if (typeof callback !== "function") {
|
2619
|
+
console.error("Callback must be a function");
|
2620
|
+
return this;
|
2621
|
+
}
|
2622
|
+
|
2623
|
+
const gun = this;
|
2624
|
+
|
2625
|
+
// Seleziona l'indirizzo basato sulla catena
|
2626
|
+
if (chain === "optimismSepolia") {
|
2627
|
+
SHINE_CONTRACT_ADDRESS = SHINE_OPTIMISM_SEPOLIA;
|
2628
|
+
} else {
|
2629
|
+
throw new Error("Chain not supported");
|
2630
|
+
}
|
2631
|
+
|
2632
|
+
// Funzione per verificare on-chain
|
2633
|
+
const verifyOnChain = async (nodeId, contentHash) => {
|
2634
|
+
console.log("Verifying on chain:", { nodeId, contentHash });
|
2635
|
+
const signer = await getSigner();
|
2636
|
+
const contract = new ethers.Contract(
|
2637
|
+
SHINE_CONTRACT_ADDRESS,
|
2638
|
+
SHINE_ABI,
|
2639
|
+
signer
|
2640
|
+
);
|
2641
|
+
const [isValid, timestamp, updater] = await contract.verifyData(
|
2642
|
+
ethers.toUtf8Bytes(nodeId),
|
2643
|
+
contentHash
|
2644
|
+
);
|
2645
|
+
console.log("Verification result:", { isValid, timestamp, updater });
|
2646
|
+
return { isValid, timestamp, updater };
|
2647
|
+
};
|
2648
|
+
|
2649
|
+
// Funzione per scrivere on-chain
|
2650
|
+
const writeOnChain = async (nodeId, contentHash) => {
|
2651
|
+
console.log("Writing on chain:", { nodeId, contentHash });
|
2652
|
+
const signer = await getSigner();
|
2653
|
+
const contract = new ethers.Contract(
|
2654
|
+
SHINE_CONTRACT_ADDRESS,
|
2655
|
+
SHINE_ABI,
|
2656
|
+
signer
|
2657
|
+
);
|
2658
|
+
const tx = await contract.updateData(
|
2659
|
+
ethers.toUtf8Bytes(nodeId),
|
2660
|
+
contentHash
|
2661
|
+
);
|
2662
|
+
console.log("Transaction sent:", tx.hash);
|
2663
|
+
const receipt = await tx.wait();
|
2664
|
+
console.log("Transaction confirmed:", receipt);
|
2665
|
+
return tx;
|
2666
|
+
};
|
2667
|
+
|
2668
|
+
// Nuova funzione per ottenere l'ultimo record dalla blockchain
|
2669
|
+
const getLatestRecord = async (nodeId) => {
|
2670
|
+
const signer = await getSigner();
|
2671
|
+
const contract = new ethers.Contract(
|
2672
|
+
SHINE_CONTRACT_ADDRESS,
|
2673
|
+
SHINE_ABI,
|
2674
|
+
signer
|
2675
|
+
);
|
2676
|
+
const [contentHash, timestamp, updater] = await contract.getLatestRecord(
|
2677
|
+
ethers.toUtf8Bytes(nodeId)
|
2678
|
+
);
|
2679
|
+
console.log("Latest record from blockchain:", {
|
2680
|
+
nodeId,
|
2681
|
+
contentHash,
|
2682
|
+
timestamp,
|
2683
|
+
updater,
|
2684
|
+
});
|
2685
|
+
return { contentHash, timestamp, updater };
|
2686
|
+
};
|
2687
|
+
|
2688
|
+
// Processo SHINE
|
2689
|
+
if (nodeId && !data) {
|
2690
|
+
// Caso 1: Utente passa solo il nodo
|
2691
|
+
gun.get(nodeId).once(async (existingData) => {
|
2692
|
+
if (!existingData) {
|
2693
|
+
if (callback) callback({ err: "Node not found in GunDB" });
|
2694
|
+
return;
|
2695
|
+
}
|
2696
|
+
|
2697
|
+
console.log("existingData", existingData);
|
2698
|
+
|
2699
|
+
// Usa il contentHash memorizzato invece di ricalcolarlo
|
2700
|
+
const contentHash = existingData._contentHash;
|
2701
|
+
console.log("contentHash", contentHash);
|
2702
|
+
|
2703
|
+
if (!contentHash) {
|
2704
|
+
if (callback)
|
2705
|
+
callback({ err: "No content hash found for this node" });
|
2706
|
+
return;
|
2707
|
+
}
|
2708
|
+
|
2709
|
+
try {
|
2710
|
+
const { isValid, timestamp, updater } = await verifyOnChain(
|
2711
|
+
nodeId,
|
2712
|
+
contentHash
|
2713
|
+
);
|
2714
|
+
const latestRecord = await getLatestRecord(nodeId);
|
2715
|
+
|
2716
|
+
if (isValid) {
|
2717
|
+
if (callback)
|
2718
|
+
callback({
|
2719
|
+
ok: true,
|
2720
|
+
message: "Data verified on blockchain",
|
2721
|
+
timestamp,
|
2722
|
+
updater,
|
2723
|
+
latestRecord,
|
2724
|
+
});
|
2725
|
+
} else {
|
2726
|
+
if (callback)
|
2727
|
+
callback({
|
2728
|
+
ok: false,
|
2729
|
+
message: "Data not verified on blockchain",
|
2730
|
+
latestRecord,
|
2731
|
+
});
|
2732
|
+
}
|
2733
|
+
} catch (error) {
|
2734
|
+
if (callback) callback({ err: error.message });
|
2735
|
+
}
|
2736
|
+
});
|
2737
|
+
} else if (data && !nodeId) {
|
2738
|
+
// Caso 2: Utente passa solo il testo (data)
|
2739
|
+
const newNodeId = Gun.text.random();
|
2740
|
+
const dataString = JSON.stringify(data);
|
2741
|
+
const contentHash = ethers.keccak256(ethers.toUtf8Bytes(dataString));
|
2742
|
+
|
2743
|
+
gun
|
2744
|
+
.get(newNodeId)
|
2745
|
+
.put({ ...data, _contentHash: contentHash }, async (ack) => {
|
2746
|
+
console.log("ack", ack);
|
2747
|
+
if (ack.err) {
|
2748
|
+
if (callback) callback({ err: "Error saving data to GunDB" });
|
2749
|
+
return;
|
2750
|
+
}
|
2751
|
+
|
2752
|
+
try {
|
2753
|
+
const tx = await writeOnChain(newNodeId, contentHash);
|
2754
|
+
if (callback)
|
2755
|
+
callback({
|
2756
|
+
ok: true,
|
2757
|
+
message: "Data written to GunDB and blockchain",
|
2758
|
+
nodeId: newNodeId,
|
2759
|
+
txHash: tx.hash,
|
2760
|
+
});
|
2761
|
+
} catch (error) {
|
2762
|
+
if (callback) callback({ err: error.message });
|
2763
|
+
}
|
2764
|
+
});
|
2765
|
+
} else {
|
2766
|
+
if (callback)
|
2767
|
+
callback({
|
2768
|
+
err: "Invalid input. Provide either nodeId or data, not both.",
|
2769
|
+
});
|
2770
|
+
}
|
2771
|
+
|
2772
|
+
return gun;
|
2773
|
+
};
|
2774
|
+
|
2775
|
+
/**
|
2776
|
+
* Converts a Gun private key to an Ethereum account.
|
2777
|
+
* @param {string} gunPrivateKey - The Gun private key in base64url format.
|
2778
|
+
* @returns {Object} An object containing the Ethereum account and public key.
|
2779
|
+
*/
|
2780
|
+
Gun.chain.gunToEthAccount = function (gunPrivateKey) {
|
2781
|
+
// Function to convert base64url to hex
|
2782
|
+
const base64UrlToHex = (base64url) => {
|
2783
|
+
const padding = "=".repeat((4 - (base64url.length % 4)) % 4);
|
2784
|
+
const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/") + padding;
|
2785
|
+
const binary = atob(base64);
|
2786
|
+
return Array.from(binary, (char) =>
|
2787
|
+
char.charCodeAt(0).toString(16).padStart(2, "0")
|
2788
|
+
).join("");
|
2789
|
+
};
|
2790
|
+
|
2791
|
+
// Convert Gun private key to hex format
|
2792
|
+
const hexPrivateKey = "0x" + base64UrlToHex(gunPrivateKey);
|
2793
|
+
|
2794
|
+
// Create an Ethereum wallet from the private key
|
2795
|
+
const wallet = new ethers.Wallet(hexPrivateKey);
|
2796
|
+
|
2797
|
+
// Get the public address (public key)
|
2798
|
+
const publicKey = wallet.address;
|
2799
|
+
|
2800
|
+
return {
|
2801
|
+
account: wallet,
|
2802
|
+
publicKey: publicKey,
|
2803
|
+
};
|
2804
|
+
};
|
2805
|
+
|
2806
|
+
console.log("Plugin Gun-Eth successfully loaded");
|
2807
|
+
});
|
2808
|
+
} (gunEthBrowser));
|