gun-eth 1.4.23 → 1.4.25
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/gun-eth.min.js +1 -2
- package/package.json +19 -24
- package/dist/gun-eth.cjs.js +0 -2846
- package/dist/gun-eth.cjs.js.map +0 -1
- package/dist/gun-eth.esm.js +0 -2835
- package/dist/gun-eth.esm.js.map +0 -1
- package/dist/gun-eth.min.js.map +0 -1
package/dist/gun-eth.esm.js
DELETED
@@ -1,2835 +0,0 @@
|
|
1
|
-
import Gun from 'gun';
|
2
|
-
export { default } from 'gun';
|
3
|
-
import { ethers } from 'ethers';
|
4
|
-
|
5
|
-
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
6
|
-
|
7
|
-
function getDefaultExportFromCjs (x) {
|
8
|
-
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
9
|
-
}
|
10
|
-
|
11
|
-
function commonjsRequire(path) {
|
12
|
-
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.');
|
13
|
-
}
|
14
|
-
|
15
|
-
var sea = {exports: {}};
|
16
|
-
|
17
|
-
sea.exports;
|
18
|
-
|
19
|
-
(function (module) {
|
20
|
-
(function(){
|
21
|
-
|
22
|
-
/* UNBUILD */
|
23
|
-
function USE(arg, req){
|
24
|
-
return req? commonjsRequire(arg) : arg.slice? USE[R(arg)] : function(mod, path){
|
25
|
-
arg(mod = {exports: {}});
|
26
|
-
USE[R(path)] = mod.exports;
|
27
|
-
}
|
28
|
-
function R(p){
|
29
|
-
return p.split('/').slice(-1).toString().replace('.js','');
|
30
|
-
}
|
31
|
-
}
|
32
|
-
{ var MODULE = module; }
|
33
|
-
USE(function(module){
|
34
|
-
// Security, Encryption, and Authorization: SEA.js
|
35
|
-
// MANDATORY READING: https://gun.eco/explainers/data/security.html
|
36
|
-
// IT IS IMPLEMENTED IN A POLYFILL/SHIM APPROACH.
|
37
|
-
// THIS IS AN EARLY ALPHA!
|
38
|
-
|
39
|
-
if(typeof self !== "undefined"){ module.window = self; } // should be safe for at least browser/worker/nodejs, need to check other envs like RN etc.
|
40
|
-
if(typeof window !== "undefined"){ module.window = window; }
|
41
|
-
|
42
|
-
var tmp = module.window || module, u;
|
43
|
-
var SEA = tmp.SEA || {};
|
44
|
-
|
45
|
-
if(SEA.window = module.window){ SEA.window.SEA = SEA; }
|
46
|
-
|
47
|
-
try{ if(u+'' !== typeof MODULE){ MODULE.exports = SEA; } }catch(e){}
|
48
|
-
module.exports = SEA;
|
49
|
-
})(USE, './root');
|
50
|
-
USE(function(module){
|
51
|
-
var SEA = USE('./root');
|
52
|
-
try{ if(SEA.window){
|
53
|
-
if(location.protocol.indexOf('s') < 0
|
54
|
-
&& location.host.indexOf('localhost') < 0
|
55
|
-
&& ! /^127\.\d+\.\d+\.\d+$/.test(location.hostname)
|
56
|
-
&& location.protocol.indexOf('file:') < 0){
|
57
|
-
console.warn('HTTPS needed for WebCrypto in SEA, redirecting...');
|
58
|
-
location.protocol = 'https:'; // WebCrypto does NOT work without HTTPS!
|
59
|
-
}
|
60
|
-
} }catch(e){}
|
61
|
-
})(USE, './https');
|
62
|
-
USE(function(module){
|
63
|
-
var u;
|
64
|
-
if(u+''== typeof btoa){
|
65
|
-
if(u+'' == typeof Buffer){
|
66
|
-
try{ commonjsGlobal.Buffer = USE("buffer", 1).Buffer; }catch(e){ console.log("Please `npm install buffer` or add it to your package.json !"); }
|
67
|
-
}
|
68
|
-
commonjsGlobal.btoa = function(data){ return Buffer.from(data, "binary").toString("base64") };
|
69
|
-
commonjsGlobal.atob = function(data){ return Buffer.from(data, "base64").toString("binary") };
|
70
|
-
}
|
71
|
-
})(USE, './base64');
|
72
|
-
USE(function(module){
|
73
|
-
USE('./base64');
|
74
|
-
// This is Array extended to have .toString(['utf8'|'hex'|'base64'])
|
75
|
-
function SeaArray() {}
|
76
|
-
Object.assign(SeaArray, { from: Array.from });
|
77
|
-
SeaArray.prototype = Object.create(Array.prototype);
|
78
|
-
SeaArray.prototype.toString = function(enc, start, end) { enc = enc || 'utf8'; start = start || 0;
|
79
|
-
const length = this.length;
|
80
|
-
if (enc === 'hex') {
|
81
|
-
const buf = new Uint8Array(this);
|
82
|
-
return [ ...Array(((end && (end + 1)) || length) - start).keys()]
|
83
|
-
.map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('')
|
84
|
-
}
|
85
|
-
if (enc === 'utf8') {
|
86
|
-
return Array.from(
|
87
|
-
{ length: (end || length) - start },
|
88
|
-
(_, i) => String.fromCharCode(this[ i + start])
|
89
|
-
).join('')
|
90
|
-
}
|
91
|
-
if (enc === 'base64') {
|
92
|
-
return btoa(this)
|
93
|
-
}
|
94
|
-
};
|
95
|
-
module.exports = SeaArray;
|
96
|
-
})(USE, './array');
|
97
|
-
USE(function(module){
|
98
|
-
USE('./base64');
|
99
|
-
// This is Buffer implementation used in SEA. Functionality is mostly
|
100
|
-
// compatible with NodeJS 'safe-buffer' and is used for encoding conversions
|
101
|
-
// between binary and 'hex' | 'utf8' | 'base64'
|
102
|
-
// See documentation and validation for safe implementation in:
|
103
|
-
// https://github.com/feross/safe-buffer#update
|
104
|
-
var SeaArray = USE('./array');
|
105
|
-
function SafeBuffer(...props) {
|
106
|
-
console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()');
|
107
|
-
return SafeBuffer.from(...props)
|
108
|
-
}
|
109
|
-
SafeBuffer.prototype = Object.create(Array.prototype);
|
110
|
-
Object.assign(SafeBuffer, {
|
111
|
-
// (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64'
|
112
|
-
from() {
|
113
|
-
if (!Object.keys(arguments).length || arguments[0]==null) {
|
114
|
-
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
|
115
|
-
}
|
116
|
-
const input = arguments[0];
|
117
|
-
let buf;
|
118
|
-
if (typeof input === 'string') {
|
119
|
-
const enc = arguments[1] || 'utf8';
|
120
|
-
if (enc === 'hex') {
|
121
|
-
const bytes = input.match(/([\da-fA-F]{2})/g)
|
122
|
-
.map((byte) => parseInt(byte, 16));
|
123
|
-
if (!bytes || !bytes.length) {
|
124
|
-
throw new TypeError('Invalid first argument for type \'hex\'.')
|
125
|
-
}
|
126
|
-
buf = SeaArray.from(bytes);
|
127
|
-
} else if (enc === 'utf8' || 'binary' === enc) { // EDIT BY MARK: I think this is safe, tested it against a couple "binary" strings. This lets SafeBuffer match NodeJS Buffer behavior more where it safely btoas regular strings.
|
128
|
-
const length = input.length;
|
129
|
-
const words = new Uint16Array(length);
|
130
|
-
Array.from({ length: length }, (_, i) => words[i] = input.charCodeAt(i));
|
131
|
-
buf = SeaArray.from(words);
|
132
|
-
} else if (enc === 'base64') {
|
133
|
-
const dec = atob(input);
|
134
|
-
const length = dec.length;
|
135
|
-
const bytes = new Uint8Array(length);
|
136
|
-
Array.from({ length: length }, (_, i) => bytes[i] = dec.charCodeAt(i));
|
137
|
-
buf = SeaArray.from(bytes);
|
138
|
-
} else if (enc === 'binary') { // deprecated by above comment
|
139
|
-
buf = SeaArray.from(input); // some btoas were mishandled.
|
140
|
-
} else {
|
141
|
-
console.info('SafeBuffer.from unknown encoding: '+enc);
|
142
|
-
}
|
143
|
-
return buf
|
144
|
-
}
|
145
|
-
input.byteLength; // what is going on here? FOR MARTTI
|
146
|
-
const length = input.byteLength ? input.byteLength : input.length;
|
147
|
-
if (length) {
|
148
|
-
let buf;
|
149
|
-
if (input instanceof ArrayBuffer) {
|
150
|
-
buf = new Uint8Array(input);
|
151
|
-
}
|
152
|
-
return SeaArray.from(buf || input)
|
153
|
-
}
|
154
|
-
},
|
155
|
-
// This is 'safe-buffer.alloc' sans encoding support
|
156
|
-
alloc(length, fill = 0 /*, enc*/ ) {
|
157
|
-
return SeaArray.from(new Uint8Array(Array.from({ length: length }, () => fill)))
|
158
|
-
},
|
159
|
-
// This is normal UNSAFE 'buffer.alloc' or 'new Buffer(length)' - don't use!
|
160
|
-
allocUnsafe(length) {
|
161
|
-
return SeaArray.from(new Uint8Array(Array.from({ length : length })))
|
162
|
-
},
|
163
|
-
// This puts together array of array like members
|
164
|
-
concat(arr) { // octet array
|
165
|
-
if (!Array.isArray(arr)) {
|
166
|
-
throw new TypeError('First argument must be Array containing ArrayBuffer or Uint8Array instances.')
|
167
|
-
}
|
168
|
-
return SeaArray.from(arr.reduce((ret, item) => ret.concat(Array.from(item)), []))
|
169
|
-
}
|
170
|
-
});
|
171
|
-
SafeBuffer.prototype.from = SafeBuffer.from;
|
172
|
-
SafeBuffer.prototype.toString = SeaArray.prototype.toString;
|
173
|
-
|
174
|
-
module.exports = SafeBuffer;
|
175
|
-
})(USE, './buffer');
|
176
|
-
USE(function(module){
|
177
|
-
const SEA = USE('./root');
|
178
|
-
const api = {Buffer: USE('./buffer')};
|
179
|
-
var o = {}, u;
|
180
|
-
|
181
|
-
// ideally we can move away from JSON entirely? unlikely due to compatibility issues... oh well.
|
182
|
-
JSON.parseAsync = JSON.parseAsync || function(t,cb,r){ var u; try{ cb(u, JSON.parse(t,r)); }catch(e){ cb(e); } };
|
183
|
-
JSON.stringifyAsync = JSON.stringifyAsync || function(v,cb,r,s){ var u; try{ cb(u, JSON.stringify(v,r,s)); }catch(e){ cb(e); } };
|
184
|
-
|
185
|
-
api.parse = function(t,r){ return new Promise(function(res, rej){
|
186
|
-
JSON.parseAsync(t,function(err, raw){ err? rej(err) : res(raw); },r);
|
187
|
-
})};
|
188
|
-
api.stringify = function(v,r,s){ return new Promise(function(res, rej){
|
189
|
-
JSON.stringifyAsync(v,function(err, raw){ err? rej(err) : res(raw); },r,s);
|
190
|
-
})};
|
191
|
-
|
192
|
-
if(SEA.window){
|
193
|
-
api.crypto = SEA.window.crypto || SEA.window.msCrypto;
|
194
|
-
api.subtle = (api.crypto||o).subtle || (api.crypto||o).webkitSubtle;
|
195
|
-
api.TextEncoder = SEA.window.TextEncoder;
|
196
|
-
api.TextDecoder = SEA.window.TextDecoder;
|
197
|
-
api.random = (len) => api.Buffer.from(api.crypto.getRandomValues(new Uint8Array(api.Buffer.alloc(len))));
|
198
|
-
}
|
199
|
-
if(!api.TextDecoder)
|
200
|
-
{
|
201
|
-
const { TextEncoder, TextDecoder } = USE((u+'' == typeof MODULE?'.':'')+'./lib/text-encoding', 1);
|
202
|
-
api.TextDecoder = TextDecoder;
|
203
|
-
api.TextEncoder = TextEncoder;
|
204
|
-
}
|
205
|
-
if(!api.crypto)
|
206
|
-
{
|
207
|
-
try
|
208
|
-
{
|
209
|
-
var crypto = USE('crypto', 1);
|
210
|
-
Object.assign(api, {
|
211
|
-
crypto,
|
212
|
-
random: (len) => api.Buffer.from(crypto.randomBytes(len))
|
213
|
-
});
|
214
|
-
const { Crypto: WebCrypto } = USE('@peculiar/webcrypto', 1);
|
215
|
-
api.ossl = api.subtle = new WebCrypto({directory: 'ossl'}).subtle; // ECDH
|
216
|
-
}
|
217
|
-
catch(e){
|
218
|
-
console.log("Please `npm install @peculiar/webcrypto` or add it to your package.json !");
|
219
|
-
}}
|
220
|
-
|
221
|
-
module.exports = api;
|
222
|
-
})(USE, './shim');
|
223
|
-
USE(function(module){
|
224
|
-
var SEA = USE('./root');
|
225
|
-
var shim = USE('./shim');
|
226
|
-
var s = {};
|
227
|
-
s.pbkdf2 = {hash: {name : 'SHA-256'}, iter: 100000, ks: 64};
|
228
|
-
s.ecdsa = {
|
229
|
-
pair: {name: 'ECDSA', namedCurve: 'P-256'},
|
230
|
-
sign: {name: 'ECDSA', hash: {name: 'SHA-256'}}
|
231
|
-
};
|
232
|
-
s.ecdh = {name: 'ECDH', namedCurve: 'P-256'};
|
233
|
-
|
234
|
-
// This creates Web Cryptography API compliant JWK for sign/verify purposes
|
235
|
-
s.jwk = function(pub, d){ // d === priv
|
236
|
-
pub = pub.split('.');
|
237
|
-
var x = pub[0], y = pub[1];
|
238
|
-
var jwk = {kty: "EC", crv: "P-256", x: x, y: y, ext: true};
|
239
|
-
jwk.key_ops = d ? ['sign'] : ['verify'];
|
240
|
-
if(d){ jwk.d = d; }
|
241
|
-
return jwk;
|
242
|
-
};
|
243
|
-
|
244
|
-
s.keyToJwk = function(keyBytes) {
|
245
|
-
const keyB64 = keyBytes.toString('base64');
|
246
|
-
const k = keyB64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
|
247
|
-
return { kty: 'oct', k: k, ext: false, alg: 'A256GCM' };
|
248
|
-
};
|
249
|
-
|
250
|
-
s.recall = {
|
251
|
-
validity: 12 * 60 * 60, // internally in seconds : 12 hours
|
252
|
-
hook: function(props){ return props } // { iat, exp, alias, remember } // or return new Promise((resolve, reject) => resolve(props)
|
253
|
-
};
|
254
|
-
|
255
|
-
s.check = function(t){ return (typeof t == 'string') && ('SEA{' === t.slice(0,4)) };
|
256
|
-
s.parse = async function p(t){ try {
|
257
|
-
var yes = (typeof t == 'string');
|
258
|
-
if(yes && 'SEA{' === t.slice(0,4)){ t = t.slice(3); }
|
259
|
-
return yes ? await shim.parse(t) : t;
|
260
|
-
} catch (e) {}
|
261
|
-
return t;
|
262
|
-
};
|
263
|
-
|
264
|
-
SEA.opt = s;
|
265
|
-
module.exports = s;
|
266
|
-
})(USE, './settings');
|
267
|
-
USE(function(module){
|
268
|
-
var shim = USE('./shim');
|
269
|
-
module.exports = async function(d, o){
|
270
|
-
var t = (typeof d == 'string')? d : await shim.stringify(d);
|
271
|
-
var hash = await shim.subtle.digest({name: o||'SHA-256'}, new shim.TextEncoder().encode(t));
|
272
|
-
return shim.Buffer.from(hash);
|
273
|
-
};
|
274
|
-
})(USE, './sha256');
|
275
|
-
USE(function(module){
|
276
|
-
// This internal func returns SHA-1 hashed data for KeyID generation
|
277
|
-
const __shim = USE('./shim');
|
278
|
-
const subtle = __shim.subtle;
|
279
|
-
const ossl = __shim.ossl ? __shim.ossl : subtle;
|
280
|
-
const sha1hash = (b) => ossl.digest({name: 'SHA-1'}, new ArrayBuffer(b));
|
281
|
-
module.exports = sha1hash;
|
282
|
-
})(USE, './sha1');
|
283
|
-
USE(function(module){
|
284
|
-
var SEA = USE('./root');
|
285
|
-
var shim = USE('./shim');
|
286
|
-
var S = USE('./settings');
|
287
|
-
var sha = USE('./sha256');
|
288
|
-
var u;
|
289
|
-
|
290
|
-
SEA.work = SEA.work || (async (data, pair, cb, opt) => { try { // used to be named `proof`
|
291
|
-
var salt = (pair||{}).epub || pair; // epub not recommended, salt should be random!
|
292
|
-
opt = opt || {};
|
293
|
-
if(salt instanceof Function){
|
294
|
-
cb = salt;
|
295
|
-
salt = u;
|
296
|
-
}
|
297
|
-
data = (typeof data == 'string')? data : await shim.stringify(data);
|
298
|
-
if('sha' === (opt.name||'').toLowerCase().slice(0,3)){
|
299
|
-
var rsha = shim.Buffer.from(await sha(data, opt.name), 'binary').toString(opt.encode || 'base64');
|
300
|
-
if(cb){ try{ cb(rsha); }catch(e){console.log(e);} }
|
301
|
-
return rsha;
|
302
|
-
}
|
303
|
-
salt = salt || shim.random(9);
|
304
|
-
var key = await (shim.ossl || shim.subtle).importKey('raw', new shim.TextEncoder().encode(data), {name: opt.name || 'PBKDF2'}, false, ['deriveBits']);
|
305
|
-
var work = await (shim.ossl || shim.subtle).deriveBits({
|
306
|
-
name: opt.name || 'PBKDF2',
|
307
|
-
iterations: opt.iterations || S.pbkdf2.iter,
|
308
|
-
salt: new shim.TextEncoder().encode(opt.salt || salt),
|
309
|
-
hash: opt.hash || S.pbkdf2.hash,
|
310
|
-
}, key, opt.length || (S.pbkdf2.ks * 8));
|
311
|
-
data = shim.random(data.length); // Erase data in case of passphrase
|
312
|
-
var r = shim.Buffer.from(work, 'binary').toString(opt.encode || 'base64');
|
313
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
314
|
-
return r;
|
315
|
-
} catch(e) {
|
316
|
-
console.log(e);
|
317
|
-
SEA.err = e;
|
318
|
-
if(SEA.throw){ throw e }
|
319
|
-
if(cb){ cb(); }
|
320
|
-
return;
|
321
|
-
}});
|
322
|
-
|
323
|
-
module.exports = SEA.work;
|
324
|
-
})(USE, './work');
|
325
|
-
USE(function(module){
|
326
|
-
var SEA = USE('./root');
|
327
|
-
var shim = USE('./shim');
|
328
|
-
USE('./settings');
|
329
|
-
|
330
|
-
SEA.name = SEA.name || (async (cb, opt) => { try {
|
331
|
-
if(cb){ try{ cb(); }catch(e){console.log(e);} }
|
332
|
-
return;
|
333
|
-
} catch(e) {
|
334
|
-
console.log(e);
|
335
|
-
SEA.err = e;
|
336
|
-
if(SEA.throw){ throw e }
|
337
|
-
if(cb){ cb(); }
|
338
|
-
return;
|
339
|
-
}});
|
340
|
-
|
341
|
-
//SEA.pair = async (data, proof, cb) => { try {
|
342
|
-
SEA.pair = SEA.pair || (async (cb, opt) => { try {
|
343
|
-
|
344
|
-
var ecdhSubtle = shim.ossl || shim.subtle;
|
345
|
-
// First: ECDSA keys for signing/verifying...
|
346
|
-
var sa = await shim.subtle.generateKey({name: 'ECDSA', namedCurve: 'P-256'}, true, [ 'sign', 'verify' ])
|
347
|
-
.then(async (keys) => {
|
348
|
-
// privateKey scope doesn't leak out from here!
|
349
|
-
//const { d: priv } = await shim.subtle.exportKey('jwk', keys.privateKey)
|
350
|
-
var key = {};
|
351
|
-
key.priv = (await shim.subtle.exportKey('jwk', keys.privateKey)).d;
|
352
|
-
var pub = await shim.subtle.exportKey('jwk', keys.publicKey);
|
353
|
-
//const pub = Buff.from([ x, y ].join(':')).toString('base64') // old
|
354
|
-
key.pub = pub.x+'.'+pub.y; // new
|
355
|
-
// x and y are already base64
|
356
|
-
// pub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
|
357
|
-
// but split on a non-base64 letter.
|
358
|
-
return key;
|
359
|
-
});
|
360
|
-
|
361
|
-
// To include PGPv4 kind of keyId:
|
362
|
-
// const pubId = await SEA.keyid(keys.pub)
|
363
|
-
// Next: ECDH keys for encryption/decryption...
|
364
|
-
|
365
|
-
try{
|
366
|
-
var dh = await ecdhSubtle.generateKey({name: 'ECDH', namedCurve: 'P-256'}, true, ['deriveKey'])
|
367
|
-
.then(async (keys) => {
|
368
|
-
// privateKey scope doesn't leak out from here!
|
369
|
-
var key = {};
|
370
|
-
key.epriv = (await ecdhSubtle.exportKey('jwk', keys.privateKey)).d;
|
371
|
-
var pub = await ecdhSubtle.exportKey('jwk', keys.publicKey);
|
372
|
-
//const epub = Buff.from([ ex, ey ].join(':')).toString('base64') // old
|
373
|
-
key.epub = pub.x+'.'+pub.y; // new
|
374
|
-
// ex and ey are already base64
|
375
|
-
// epub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
|
376
|
-
// but split on a non-base64 letter.
|
377
|
-
return key;
|
378
|
-
});
|
379
|
-
}catch(e){
|
380
|
-
if(SEA.window){ throw e }
|
381
|
-
if(e == 'Error: ECDH is not a supported algorithm'){ console.log('Ignoring ECDH...'); }
|
382
|
-
else { throw e }
|
383
|
-
} dh = dh || {};
|
384
|
-
|
385
|
-
var r = { pub: sa.pub, priv: sa.priv, /* pubId, */ epub: dh.epub, epriv: dh.epriv };
|
386
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
387
|
-
return r;
|
388
|
-
} catch(e) {
|
389
|
-
console.log(e);
|
390
|
-
SEA.err = e;
|
391
|
-
if(SEA.throw){ throw e }
|
392
|
-
if(cb){ cb(); }
|
393
|
-
return;
|
394
|
-
}});
|
395
|
-
|
396
|
-
module.exports = SEA.pair;
|
397
|
-
})(USE, './pair');
|
398
|
-
USE(function(module){
|
399
|
-
var SEA = USE('./root');
|
400
|
-
var shim = USE('./shim');
|
401
|
-
var S = USE('./settings');
|
402
|
-
var sha = USE('./sha256');
|
403
|
-
var u;
|
404
|
-
|
405
|
-
SEA.sign = SEA.sign || (async (data, pair, cb, opt) => { try {
|
406
|
-
opt = opt || {};
|
407
|
-
if(!(pair||opt).priv){
|
408
|
-
if(!SEA.I){ throw 'No signing key.' }
|
409
|
-
pair = await SEA.I(null, {what: data, how: 'sign', why: opt.why});
|
410
|
-
}
|
411
|
-
if(u === data){ throw '`undefined` not allowed.' }
|
412
|
-
var json = await S.parse(data);
|
413
|
-
var check = opt.check = opt.check || json;
|
414
|
-
if(SEA.verify && (SEA.opt.check(check) || (check && check.s && check.m))
|
415
|
-
&& u !== await SEA.verify(check, pair)){ // don't sign if we already signed it.
|
416
|
-
var r = await S.parse(check);
|
417
|
-
if(!opt.raw){ r = 'SEA' + await shim.stringify(r); }
|
418
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
419
|
-
return r;
|
420
|
-
}
|
421
|
-
var pub = pair.pub;
|
422
|
-
var priv = pair.priv;
|
423
|
-
var jwk = S.jwk(pub, priv);
|
424
|
-
var hash = await sha(json);
|
425
|
-
var sig = await (shim.ossl || shim.subtle).importKey('jwk', jwk, {name: 'ECDSA', namedCurve: 'P-256'}, false, ['sign'])
|
426
|
-
.then((key) => (shim.ossl || shim.subtle).sign({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, new Uint8Array(hash))); // privateKey scope doesn't leak out from here!
|
427
|
-
var r = {m: json, s: shim.Buffer.from(sig, 'binary').toString(opt.encode || 'base64')};
|
428
|
-
if(!opt.raw){ r = 'SEA' + await shim.stringify(r); }
|
429
|
-
|
430
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
431
|
-
return r;
|
432
|
-
} catch(e) {
|
433
|
-
console.log(e);
|
434
|
-
SEA.err = e;
|
435
|
-
if(SEA.throw){ throw e }
|
436
|
-
if(cb){ cb(); }
|
437
|
-
return;
|
438
|
-
}});
|
439
|
-
|
440
|
-
module.exports = SEA.sign;
|
441
|
-
})(USE, './sign');
|
442
|
-
USE(function(module){
|
443
|
-
var SEA = USE('./root');
|
444
|
-
var shim = USE('./shim');
|
445
|
-
var S = USE('./settings');
|
446
|
-
var sha = USE('./sha256');
|
447
|
-
var u;
|
448
|
-
|
449
|
-
SEA.verify = SEA.verify || (async (data, pair, cb, opt) => { try {
|
450
|
-
var json = await S.parse(data);
|
451
|
-
if(false === pair){ // don't verify!
|
452
|
-
var raw = await S.parse(json.m);
|
453
|
-
if(cb){ try{ cb(raw); }catch(e){console.log(e);} }
|
454
|
-
return raw;
|
455
|
-
}
|
456
|
-
opt = opt || {};
|
457
|
-
// SEA.I // verify is free! Requires no user permission.
|
458
|
-
var pub = pair.pub || pair;
|
459
|
-
var key = SEA.opt.slow_leak? await SEA.opt.slow_leak(pub) : await (shim.ossl || shim.subtle).importKey('jwk', S.jwk(pub), {name: 'ECDSA', namedCurve: 'P-256'}, false, ['verify']);
|
460
|
-
var hash = await sha(json.m);
|
461
|
-
var buf, sig, check, tmp; try{
|
462
|
-
buf = shim.Buffer.from(json.s, opt.encode || 'base64'); // NEW DEFAULT!
|
463
|
-
sig = new Uint8Array(buf);
|
464
|
-
check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash));
|
465
|
-
if(!check){ throw "Signature did not match." }
|
466
|
-
}catch(e){
|
467
|
-
if(SEA.opt.fallback){
|
468
|
-
return await SEA.opt.fall_verify(data, pair, cb, opt);
|
469
|
-
}
|
470
|
-
}
|
471
|
-
var r = check? await S.parse(json.m) : u;
|
472
|
-
|
473
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
474
|
-
return r;
|
475
|
-
} catch(e) {
|
476
|
-
console.log(e); // mismatched owner FOR MARTTI
|
477
|
-
SEA.err = e;
|
478
|
-
if(SEA.throw){ throw e }
|
479
|
-
if(cb){ cb(); }
|
480
|
-
return;
|
481
|
-
}});
|
482
|
-
|
483
|
-
module.exports = SEA.verify;
|
484
|
-
// legacy & ossl memory leak mitigation:
|
485
|
-
|
486
|
-
var knownKeys = {};
|
487
|
-
SEA.opt.slow_leak = pair => {
|
488
|
-
if (knownKeys[pair]) return knownKeys[pair];
|
489
|
-
var jwk = S.jwk(pair);
|
490
|
-
knownKeys[pair] = (shim.ossl || shim.subtle).importKey("jwk", jwk, {name: 'ECDSA', namedCurve: 'P-256'}, false, ["verify"]);
|
491
|
-
return knownKeys[pair];
|
492
|
-
};
|
493
|
-
|
494
|
-
var O = SEA.opt;
|
495
|
-
SEA.opt.fall_verify = async function(data, pair, cb, opt, f){
|
496
|
-
if(f === SEA.opt.fallback){ throw "Signature did not match" } f = f || 1;
|
497
|
-
var tmp = data||'';
|
498
|
-
data = SEA.opt.unpack(data) || data;
|
499
|
-
var json = await S.parse(data), pub = pair.pub || pair, key = await SEA.opt.slow_leak(pub);
|
500
|
-
var hash = (f <= SEA.opt.fallback)? shim.Buffer.from(await shim.subtle.digest({name: 'SHA-256'}, new shim.TextEncoder().encode(await S.parse(json.m)))) : await sha(json.m); // this line is old bad buggy code but necessary for old compatibility.
|
501
|
-
var buf; var sig; var check; try{
|
502
|
-
buf = shim.Buffer.from(json.s, opt.encode || 'base64'); // NEW DEFAULT!
|
503
|
-
sig = new Uint8Array(buf);
|
504
|
-
check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash));
|
505
|
-
if(!check){ throw "Signature did not match." }
|
506
|
-
}catch(e){ try{
|
507
|
-
buf = shim.Buffer.from(json.s, 'utf8'); // AUTO BACKWARD OLD UTF8 DATA!
|
508
|
-
sig = new Uint8Array(buf);
|
509
|
-
check = await (shim.ossl || shim.subtle).verify({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, sig, new Uint8Array(hash));
|
510
|
-
}catch(e){
|
511
|
-
if(!check){ throw "Signature did not match." }
|
512
|
-
}
|
513
|
-
}
|
514
|
-
var r = check? await S.parse(json.m) : u;
|
515
|
-
O.fall_soul = tmp['#']; O.fall_key = tmp['.']; O.fall_val = data; O.fall_state = tmp['>'];
|
516
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
517
|
-
return r;
|
518
|
-
};
|
519
|
-
SEA.opt.fallback = 2;
|
520
|
-
|
521
|
-
})(USE, './verify');
|
522
|
-
USE(function(module){
|
523
|
-
var shim = USE('./shim');
|
524
|
-
var S = USE('./settings');
|
525
|
-
var sha256hash = USE('./sha256');
|
526
|
-
|
527
|
-
const importGen = async (key, salt, opt) => {
|
528
|
-
const combo = key + (salt || shim.random(8)).toString('utf8'); // new
|
529
|
-
const hash = shim.Buffer.from(await sha256hash(combo), 'binary');
|
530
|
-
|
531
|
-
const jwkKey = S.keyToJwk(hash);
|
532
|
-
return await shim.subtle.importKey('jwk', jwkKey, {name:'AES-GCM'}, false, ['encrypt', 'decrypt'])
|
533
|
-
};
|
534
|
-
module.exports = importGen;
|
535
|
-
})(USE, './aeskey');
|
536
|
-
USE(function(module){
|
537
|
-
var SEA = USE('./root');
|
538
|
-
var shim = USE('./shim');
|
539
|
-
USE('./settings');
|
540
|
-
var aeskey = USE('./aeskey');
|
541
|
-
var u;
|
542
|
-
|
543
|
-
SEA.encrypt = SEA.encrypt || (async (data, pair, cb, opt) => { try {
|
544
|
-
opt = opt || {};
|
545
|
-
var key = (pair||opt).epriv || pair;
|
546
|
-
if(u === data){ throw '`undefined` not allowed.' }
|
547
|
-
if(!key){
|
548
|
-
if(!SEA.I){ throw 'No encryption key.' }
|
549
|
-
pair = await SEA.I(null, {what: data, how: 'encrypt', why: opt.why});
|
550
|
-
key = pair.epriv || pair;
|
551
|
-
}
|
552
|
-
var msg = (typeof data == 'string')? data : await shim.stringify(data);
|
553
|
-
var rand = {s: shim.random(9), iv: shim.random(15)}; // consider making this 9 and 15 or 18 or 12 to reduce == padding.
|
554
|
-
var ct = await aeskey(key, rand.s, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).encrypt({ // Keeping the AES key scope as private as possible...
|
555
|
-
name: opt.name || 'AES-GCM', iv: new Uint8Array(rand.iv)
|
556
|
-
}, aes, new shim.TextEncoder().encode(msg)));
|
557
|
-
var r = {
|
558
|
-
ct: shim.Buffer.from(ct, 'binary').toString(opt.encode || 'base64'),
|
559
|
-
iv: rand.iv.toString(opt.encode || 'base64'),
|
560
|
-
s: rand.s.toString(opt.encode || 'base64')
|
561
|
-
};
|
562
|
-
if(!opt.raw){ r = 'SEA' + await shim.stringify(r); }
|
563
|
-
|
564
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
565
|
-
return r;
|
566
|
-
} catch(e) {
|
567
|
-
console.log(e);
|
568
|
-
SEA.err = e;
|
569
|
-
if(SEA.throw){ throw e }
|
570
|
-
if(cb){ cb(); }
|
571
|
-
return;
|
572
|
-
}});
|
573
|
-
|
574
|
-
module.exports = SEA.encrypt;
|
575
|
-
})(USE, './encrypt');
|
576
|
-
USE(function(module){
|
577
|
-
var SEA = USE('./root');
|
578
|
-
var shim = USE('./shim');
|
579
|
-
var S = USE('./settings');
|
580
|
-
var aeskey = USE('./aeskey');
|
581
|
-
|
582
|
-
SEA.decrypt = SEA.decrypt || (async (data, pair, cb, opt) => { try {
|
583
|
-
opt = opt || {};
|
584
|
-
var key = (pair||opt).epriv || pair;
|
585
|
-
if(!key){
|
586
|
-
if(!SEA.I){ throw 'No decryption key.' }
|
587
|
-
pair = await SEA.I(null, {what: data, how: 'decrypt', why: opt.why});
|
588
|
-
key = pair.epriv || pair;
|
589
|
-
}
|
590
|
-
var json = await S.parse(data);
|
591
|
-
var buf, bufiv, bufct; try{
|
592
|
-
buf = shim.Buffer.from(json.s, opt.encode || 'base64');
|
593
|
-
bufiv = shim.Buffer.from(json.iv, opt.encode || 'base64');
|
594
|
-
bufct = shim.Buffer.from(json.ct, opt.encode || 'base64');
|
595
|
-
var ct = await aeskey(key, buf, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).decrypt({ // Keeping aesKey scope as private as possible...
|
596
|
-
name: opt.name || 'AES-GCM', iv: new Uint8Array(bufiv), tagLength: 128
|
597
|
-
}, aes, new Uint8Array(bufct)));
|
598
|
-
}catch(e){
|
599
|
-
if('utf8' === opt.encode){ throw "Could not decrypt" }
|
600
|
-
if(SEA.opt.fallback){
|
601
|
-
opt.encode = 'utf8';
|
602
|
-
return await SEA.decrypt(data, pair, cb, opt);
|
603
|
-
}
|
604
|
-
}
|
605
|
-
var r = await S.parse(new shim.TextDecoder('utf8').decode(ct));
|
606
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
607
|
-
return r;
|
608
|
-
} catch(e) {
|
609
|
-
console.log(e);
|
610
|
-
SEA.err = e;
|
611
|
-
if(SEA.throw){ throw e }
|
612
|
-
if(cb){ cb(); }
|
613
|
-
return;
|
614
|
-
}});
|
615
|
-
|
616
|
-
module.exports = SEA.decrypt;
|
617
|
-
})(USE, './decrypt');
|
618
|
-
USE(function(module){
|
619
|
-
var SEA = USE('./root');
|
620
|
-
var shim = USE('./shim');
|
621
|
-
USE('./settings');
|
622
|
-
// Derive shared secret from other's pub and my epub/epriv
|
623
|
-
SEA.secret = SEA.secret || (async (key, pair, cb, opt) => { try {
|
624
|
-
opt = opt || {};
|
625
|
-
if(!pair || !pair.epriv || !pair.epub){
|
626
|
-
if(!SEA.I){ throw 'No secret mix.' }
|
627
|
-
pair = await SEA.I(null, {what: key, how: 'secret', why: opt.why});
|
628
|
-
}
|
629
|
-
var pub = key.epub || key;
|
630
|
-
var epub = pair.epub;
|
631
|
-
var epriv = pair.epriv;
|
632
|
-
var ecdhSubtle = shim.ossl || shim.subtle;
|
633
|
-
var pubKeyData = keysToEcdhJwk(pub);
|
634
|
-
var props = Object.assign({ public: await ecdhSubtle.importKey(...pubKeyData, true, []) },{name: 'ECDH', namedCurve: 'P-256'}); // Thanks to @sirpy !
|
635
|
-
var privKeyData = keysToEcdhJwk(epub, epriv);
|
636
|
-
var derived = await ecdhSubtle.importKey(...privKeyData, false, ['deriveBits']).then(async (privKey) => {
|
637
|
-
// privateKey scope doesn't leak out from here!
|
638
|
-
var derivedBits = await ecdhSubtle.deriveBits(props, privKey, 256);
|
639
|
-
var rawBits = new Uint8Array(derivedBits);
|
640
|
-
var derivedKey = await ecdhSubtle.importKey('raw', rawBits,{ name: 'AES-GCM', length: 256 }, true, [ 'encrypt', 'decrypt' ]);
|
641
|
-
return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k);
|
642
|
-
});
|
643
|
-
var r = derived;
|
644
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
645
|
-
return r;
|
646
|
-
} catch(e) {
|
647
|
-
console.log(e);
|
648
|
-
SEA.err = e;
|
649
|
-
if(SEA.throw){ throw e }
|
650
|
-
if(cb){ cb(); }
|
651
|
-
return;
|
652
|
-
}});
|
653
|
-
|
654
|
-
// can this be replaced with settings.jwk?
|
655
|
-
var keysToEcdhJwk = (pub, d) => { // d === priv
|
656
|
-
//var [ x, y ] = shim.Buffer.from(pub, 'base64').toString('utf8').split(':') // old
|
657
|
-
var [ x, y ] = pub.split('.'); // new
|
658
|
-
var jwk = d ? { d: d } : {};
|
659
|
-
return [ // Use with spread returned value...
|
660
|
-
'jwk',
|
661
|
-
Object.assign(
|
662
|
-
jwk,
|
663
|
-
{ x: x, y: y, kty: 'EC', crv: 'P-256', ext: true }
|
664
|
-
), // ??? refactor
|
665
|
-
{name: 'ECDH', namedCurve: 'P-256'}
|
666
|
-
]
|
667
|
-
};
|
668
|
-
|
669
|
-
module.exports = SEA.secret;
|
670
|
-
})(USE, './secret');
|
671
|
-
USE(function(module){
|
672
|
-
var SEA = USE('./root');
|
673
|
-
// This is to certify that a group of "certificants" can "put" anything at a group of matched "paths" to the certificate authority's graph
|
674
|
-
SEA.certify = SEA.certify || (async (certificants, policy = {}, authority, cb, opt = {}) => { try {
|
675
|
-
/*
|
676
|
-
The Certify Protocol was made out of love by a Vietnamese code enthusiast. Vietnamese people around the world deserve respect!
|
677
|
-
IMPORTANT: A Certificate is like a Signature. No one knows who (authority) created/signed a cert until you put it into their graph.
|
678
|
-
"certificants": '*' or a String (Bob.pub) || an Object that contains "pub" as a key || an array of [object || string]. These people will have the rights.
|
679
|
-
"policy": A string ('inbox'), or a RAD/LEX object {'*': 'inbox'}, or an Array of RAD/LEX objects or strings. RAD/LEX object can contain key "?" with indexOf("*") > -1 to force key equals certificant pub. This rule is used to check against soul+'/'+key using Gun.text.match or String.match.
|
680
|
-
"authority": Key pair or priv of the certificate authority.
|
681
|
-
"cb": A callback function after all things are done.
|
682
|
-
"opt": If opt.expiry (a timestamp) is set, SEA won't sync data after opt.expiry. If opt.block is set, SEA will look for block before syncing.
|
683
|
-
*/
|
684
|
-
console.log('SEA.certify() is an early experimental community supported method that may change API behavior without warning in any future version.');
|
685
|
-
|
686
|
-
certificants = (() => {
|
687
|
-
var data = [];
|
688
|
-
if (certificants) {
|
689
|
-
if ((typeof certificants === 'string' || Array.isArray(certificants)) && certificants.indexOf('*') > -1) return '*'
|
690
|
-
if (typeof certificants === 'string') return certificants
|
691
|
-
if (Array.isArray(certificants)) {
|
692
|
-
if (certificants.length === 1 && certificants[0]) return typeof certificants[0] === 'object' && certificants[0].pub ? certificants[0].pub : typeof certificants[0] === 'string' ? certificants[0] : null
|
693
|
-
certificants.map(certificant => {
|
694
|
-
if (typeof certificant ==='string') data.push(certificant);
|
695
|
-
else if (typeof certificant === 'object' && certificant.pub) data.push(certificant.pub);
|
696
|
-
});
|
697
|
-
}
|
698
|
-
|
699
|
-
if (typeof certificants === 'object' && certificants.pub) return certificants.pub
|
700
|
-
return data.length > 0 ? data : null
|
701
|
-
}
|
702
|
-
return
|
703
|
-
})();
|
704
|
-
|
705
|
-
if (!certificants) return console.log("No certificant found.")
|
706
|
-
|
707
|
-
const expiry = opt.expiry && (typeof opt.expiry === 'number' || typeof opt.expiry === 'string') ? parseFloat(opt.expiry) : null;
|
708
|
-
const readPolicy = (policy || {}).read ? policy.read : null;
|
709
|
-
const writePolicy = (policy || {}).write ? policy.write : typeof policy === 'string' || Array.isArray(policy) || policy["+"] || policy["#"] || policy["."] || policy["="] || policy["*"] || policy[">"] || policy["<"] ? policy : null;
|
710
|
-
// The "blacklist" feature is now renamed to "block". Why ? BECAUSE BLACK LIVES MATTER!
|
711
|
-
// We can now use 3 keys: block, blacklist, ban
|
712
|
-
const block = (opt || {}).block || (opt || {}).blacklist || (opt || {}).ban || {};
|
713
|
-
const readBlock = block.read && (typeof block.read === 'string' || (block.read || {})['#']) ? block.read : null;
|
714
|
-
const writeBlock = typeof block === 'string' ? block : block.write && (typeof block.write === 'string' || block.write['#']) ? block.write : null;
|
715
|
-
|
716
|
-
if (!readPolicy && !writePolicy) return console.log("No policy found.")
|
717
|
-
|
718
|
-
// reserved keys: c, e, r, w, rb, wb
|
719
|
-
const data = JSON.stringify({
|
720
|
-
c: certificants,
|
721
|
-
...(expiry ? {e: expiry} : {}), // inject expiry if possible
|
722
|
-
...(readPolicy ? {r: readPolicy } : {}), // "r" stands for read, which means read permission.
|
723
|
-
...(writePolicy ? {w: writePolicy} : {}), // "w" stands for write, which means write permission.
|
724
|
-
...(readBlock ? {rb: readBlock} : {}), // inject READ block if possible
|
725
|
-
...(writeBlock ? {wb: writeBlock} : {}), // inject WRITE block if possible
|
726
|
-
});
|
727
|
-
|
728
|
-
const certificate = await SEA.sign(data, authority, null, {raw:1});
|
729
|
-
|
730
|
-
var r = certificate;
|
731
|
-
if(!opt.raw){ r = 'SEA'+JSON.stringify(r); }
|
732
|
-
if(cb){ try{ cb(r); }catch(e){console.log(e);} }
|
733
|
-
return r;
|
734
|
-
} catch(e) {
|
735
|
-
SEA.err = e;
|
736
|
-
if(SEA.throw){ throw e }
|
737
|
-
if(cb){ cb(); }
|
738
|
-
return;
|
739
|
-
}});
|
740
|
-
|
741
|
-
module.exports = SEA.certify;
|
742
|
-
})(USE, './certify');
|
743
|
-
USE(function(module){
|
744
|
-
var shim = USE('./shim');
|
745
|
-
// Practical examples about usage found in tests.
|
746
|
-
var SEA = USE('./root');
|
747
|
-
SEA.work = USE('./work');
|
748
|
-
SEA.sign = USE('./sign');
|
749
|
-
SEA.verify = USE('./verify');
|
750
|
-
SEA.encrypt = USE('./encrypt');
|
751
|
-
SEA.decrypt = USE('./decrypt');
|
752
|
-
SEA.certify = USE('./certify');
|
753
|
-
//SEA.opt.aeskey = USE('./aeskey'); // not official! // this causes problems in latest WebCrypto.
|
754
|
-
|
755
|
-
SEA.random = SEA.random || shim.random;
|
756
|
-
|
757
|
-
// This is Buffer used in SEA and usable from Gun/SEA application also.
|
758
|
-
// For documentation see https://nodejs.org/api/buffer.html
|
759
|
-
SEA.Buffer = SEA.Buffer || USE('./buffer');
|
760
|
-
|
761
|
-
// These SEA functions support now ony Promises or
|
762
|
-
// async/await (compatible) code, use those like Promises.
|
763
|
-
//
|
764
|
-
// Creates a wrapper library around Web Crypto API
|
765
|
-
// for various AES, ECDSA, PBKDF2 functions we called above.
|
766
|
-
// Calculate public key KeyID aka PGPv4 (result: 8 bytes as hex string)
|
767
|
-
SEA.keyid = SEA.keyid || (async (pub) => {
|
768
|
-
try {
|
769
|
-
// base64('base64(x):base64(y)') => shim.Buffer(xy)
|
770
|
-
const pb = shim.Buffer.concat(
|
771
|
-
pub.replace(/-/g, '+').replace(/_/g, '/').split('.')
|
772
|
-
.map((t) => shim.Buffer.from(t, 'base64'))
|
773
|
-
);
|
774
|
-
// id is PGPv4 compliant raw key
|
775
|
-
const id = shim.Buffer.concat([
|
776
|
-
shim.Buffer.from([0x99, pb.length / 0x100, pb.length % 0x100]), pb
|
777
|
-
]);
|
778
|
-
const sha1 = await sha1hash(id);
|
779
|
-
const hash = shim.Buffer.from(sha1, 'binary');
|
780
|
-
return hash.toString('hex', hash.length - 8) // 16-bit ID as hex
|
781
|
-
} catch (e) {
|
782
|
-
console.log(e);
|
783
|
-
throw e
|
784
|
-
}
|
785
|
-
});
|
786
|
-
// all done!
|
787
|
-
// Obviously it is missing MANY necessary features. This is only an alpha release.
|
788
|
-
// Please experiment with it, audit what I've done so far, and complain about what needs to be added.
|
789
|
-
// SEA should be a full suite that is easy and seamless to use.
|
790
|
-
// Again, scroll naer the top, where I provide an EXAMPLE of how to create a user and sign in.
|
791
|
-
// Once logged in, the rest of the code you just read handled automatically signing/validating data.
|
792
|
-
// But all other behavior needs to be equally easy, like opinionated ways of
|
793
|
-
// Adding friends (trusted public keys), sending private messages, etc.
|
794
|
-
// Cheers! Tell me what you think.
|
795
|
-
((SEA.window||{}).GUN||{}).SEA = SEA;
|
796
|
-
|
797
|
-
module.exports = SEA;
|
798
|
-
// -------------- END SEA MODULES --------------------
|
799
|
-
// -- BEGIN SEA+GUN MODULES: BUNDLED BY DEFAULT UNTIL OTHERS USE SEA ON OWN -------
|
800
|
-
})(USE, './sea');
|
801
|
-
USE(function(module){
|
802
|
-
var SEA = USE('./sea'), Gun, u;
|
803
|
-
if(SEA.window){
|
804
|
-
Gun = SEA.window.GUN || {chain:{}};
|
805
|
-
} else {
|
806
|
-
Gun = USE((u+'' == typeof MODULE?'.':'')+'./gun', 1);
|
807
|
-
}
|
808
|
-
SEA.GUN = Gun;
|
809
|
-
|
810
|
-
function User(root){
|
811
|
-
this._ = {$: this};
|
812
|
-
}
|
813
|
-
User.prototype = (function(){ function F(){} F.prototype = Gun.chain; return new F() }()); // Object.create polyfill
|
814
|
-
User.prototype.constructor = User;
|
815
|
-
|
816
|
-
// let's extend the gun chain with a `user` function.
|
817
|
-
// only one user can be logged in at a time, per gun instance.
|
818
|
-
Gun.chain.user = function(pub){
|
819
|
-
var gun = this, root = gun.back(-1), user;
|
820
|
-
if(pub){
|
821
|
-
pub = SEA.opt.pub((pub._||'')['#']) || pub;
|
822
|
-
return root.get('~'+pub);
|
823
|
-
}
|
824
|
-
if(user = root.back('user')){ return user }
|
825
|
-
var root = (root._), at = root, uuid = at.opt.uuid || lex;
|
826
|
-
(at = (user = at.user = gun.chain(new User))._).opt = {};
|
827
|
-
at.opt.uuid = function(cb){
|
828
|
-
var id = uuid(), pub = root.user;
|
829
|
-
if(!pub || !(pub = pub.is) || !(pub = pub.pub)){ return id }
|
830
|
-
id = '~' + pub + '/' + id;
|
831
|
-
if(cb && cb.call){ cb(null, id); }
|
832
|
-
return id;
|
833
|
-
};
|
834
|
-
return user;
|
835
|
-
};
|
836
|
-
function lex(){ return Gun.state().toString(36).replace('.','') }
|
837
|
-
Gun.User = User;
|
838
|
-
User.GUN = Gun;
|
839
|
-
User.SEA = Gun.SEA = SEA;
|
840
|
-
module.exports = User;
|
841
|
-
})(USE, './user');
|
842
|
-
USE(function(module){
|
843
|
-
var u, Gun = (''+u != typeof GUN)? (GUN||{chain:{}}) : USE((''+u === typeof MODULE?'.':'')+'./gun', 1);
|
844
|
-
Gun.chain.then = function(cb, opt){
|
845
|
-
var gun = this, p = (new Promise(function(res, rej){
|
846
|
-
gun.once(res, opt);
|
847
|
-
}));
|
848
|
-
return cb? p.then(cb) : p;
|
849
|
-
};
|
850
|
-
})(USE, './then');
|
851
|
-
USE(function(module){
|
852
|
-
var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};
|
853
|
-
|
854
|
-
// Well first we have to actually create a user. That is what this function does.
|
855
|
-
User.prototype.create = function(...args){
|
856
|
-
var pair = typeof args[0] === 'object' && (args[0].pub || args[0].epub) ? args[0] : typeof args[1] === 'object' && (args[1].pub || args[1].epub) ? args[1] : null;
|
857
|
-
var alias = pair && (pair.pub || pair.epub) ? pair.pub : typeof args[0] === 'string' ? args[0] : null;
|
858
|
-
var pass = pair && (pair.pub || pair.epub) ? pair : alias && typeof args[1] === 'string' ? args[1] : null;
|
859
|
-
var cb = args.filter(arg => typeof arg === 'function')[0] || null; // cb now can stand anywhere, after alias/pass or pair
|
860
|
-
var opt = args && args.length > 1 && typeof args[args.length-1] === 'object' ? args[args.length-1] : {}; // opt is always the last parameter which typeof === 'object' and stands after cb
|
861
|
-
|
862
|
-
var gun = this, cat = (gun._), root = gun.back(-1);
|
863
|
-
cb = cb || noop;
|
864
|
-
opt = opt || {};
|
865
|
-
if(false !== opt.check){
|
866
|
-
var err;
|
867
|
-
if(!alias){ err = "No user."; }
|
868
|
-
if((pass||'').length < 8){ err = "Password too short!"; }
|
869
|
-
if(err){
|
870
|
-
cb({err: Gun.log(err)});
|
871
|
-
return gun;
|
872
|
-
}
|
873
|
-
}
|
874
|
-
if(cat.ing){
|
875
|
-
(cb || noop)({err: Gun.log("User is already being created or authenticated!"), wait: true});
|
876
|
-
return gun;
|
877
|
-
}
|
878
|
-
cat.ing = true;
|
879
|
-
var act = {};
|
880
|
-
act.a = function(pubs){
|
881
|
-
act.pubs = pubs;
|
882
|
-
if(pubs && !opt.already){
|
883
|
-
// If we can enforce that a user name is already taken, it might be nice to try, but this is not guaranteed.
|
884
|
-
var ack = {err: Gun.log('User already created!')};
|
885
|
-
cat.ing = false;
|
886
|
-
(cb || noop)(ack);
|
887
|
-
gun.leave();
|
888
|
-
return;
|
889
|
-
}
|
890
|
-
act.salt = String.random(64); // pseudo-randomly create a salt, then use PBKDF2 function to extend the password with it.
|
891
|
-
SEA.work(pass, act.salt, act.b); // this will take some short amount of time to produce a proof, which slows brute force attacks.
|
892
|
-
};
|
893
|
-
act.b = function(proof){
|
894
|
-
act.proof = proof;
|
895
|
-
pair ? act.c(pair) : SEA.pair(act.c); // generate a brand new key pair or use the existing.
|
896
|
-
};
|
897
|
-
act.c = function(pair){
|
898
|
-
var tmp;
|
899
|
-
act.pair = pair || {};
|
900
|
-
if(tmp = cat.root.user){
|
901
|
-
tmp._.sea = pair;
|
902
|
-
tmp.is = {pub: pair.pub, epub: pair.epub, alias: alias};
|
903
|
-
}
|
904
|
-
// the user's public key doesn't need to be signed. But everything else needs to be signed with it! // we have now automated it! clean up these extra steps now!
|
905
|
-
act.data = {pub: pair.pub};
|
906
|
-
act.d();
|
907
|
-
};
|
908
|
-
act.d = function(){
|
909
|
-
act.data.alias = alias;
|
910
|
-
act.e();
|
911
|
-
};
|
912
|
-
act.e = function(){
|
913
|
-
act.data.epub = act.pair.epub;
|
914
|
-
SEA.encrypt({priv: act.pair.priv, epriv: act.pair.epriv}, act.proof, act.f, {raw:1}); // to keep the private key safe, we AES encrypt it with the proof of work!
|
915
|
-
};
|
916
|
-
act.f = function(auth){
|
917
|
-
act.data.auth = JSON.stringify({ek: auth, s: act.salt});
|
918
|
-
act.g(act.data.auth);
|
919
|
-
};
|
920
|
-
act.g = function(auth){ var tmp;
|
921
|
-
act.data.auth = act.data.auth || auth;
|
922
|
-
root.get(tmp = '~'+act.pair.pub).put(act.data).on(act.h); // awesome, now we can actually save the user with their public key as their ID.
|
923
|
-
var link = {}; link[tmp] = {'#': tmp}; root.get('~@'+alias).put(link).get(tmp).on(act.i); // next up, we want to associate the alias with the public key. So we add it to the alias list.
|
924
|
-
};
|
925
|
-
act.h = function(data, key, msg, eve){
|
926
|
-
eve.off(); act.h.ok = 1; act.i();
|
927
|
-
};
|
928
|
-
act.i = function(data, key, msg, eve){
|
929
|
-
if(eve){ act.i.ok = 1; eve.off(); }
|
930
|
-
if(!act.h.ok || !act.i.ok){ return }
|
931
|
-
cat.ing = false;
|
932
|
-
cb({ok: 0, pub: act.pair.pub}); // callback that the user has been created. (Note: ok = 0 because we didn't wait for disk to ack)
|
933
|
-
if(noop === cb){ pair ? gun.auth(pair) : gun.auth(alias, pass); } // if no callback is passed, auto-login after signing up.
|
934
|
-
};
|
935
|
-
root.get('~@'+alias).once(act.a);
|
936
|
-
return gun;
|
937
|
-
};
|
938
|
-
User.prototype.leave = function(opt, cb){
|
939
|
-
var gun = this, user = (gun.back(-1)._).user;
|
940
|
-
if(user){
|
941
|
-
delete user.is;
|
942
|
-
delete user._.is;
|
943
|
-
delete user._.sea;
|
944
|
-
}
|
945
|
-
if(SEA.window){
|
946
|
-
try{var sS = {};
|
947
|
-
sS = SEA.window.sessionStorage;
|
948
|
-
delete sS.recall;
|
949
|
-
delete sS.pair;
|
950
|
-
}catch(e){} }
|
951
|
-
return gun;
|
952
|
-
};
|
953
|
-
})(USE, './create');
|
954
|
-
USE(function(module){
|
955
|
-
var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};
|
956
|
-
// now that we have created a user, we want to authenticate them!
|
957
|
-
User.prototype.auth = function(...args){ // TODO: this PR with arguments need to be cleaned up / refactored.
|
958
|
-
var pair = typeof args[0] === 'object' && (args[0].pub || args[0].epub) ? args[0] : typeof args[1] === 'object' && (args[1].pub || args[1].epub) ? args[1] : null;
|
959
|
-
var alias = !pair && typeof args[0] === 'string' ? args[0] : null;
|
960
|
-
var pass = (alias || (pair && !(pair.priv && pair.epriv))) && typeof args[1] === 'string' ? args[1] : null;
|
961
|
-
var cb = args.filter(arg => typeof arg === 'function')[0] || null; // cb now can stand anywhere, after alias/pass or pair
|
962
|
-
var opt = args && args.length > 1 && typeof args[args.length-1] === 'object' ? args[args.length-1] : {}; // opt is always the last parameter which typeof === 'object' and stands after cb
|
963
|
-
|
964
|
-
var gun = this, cat = (gun._), root = gun.back(-1);
|
965
|
-
|
966
|
-
if(cat.ing){
|
967
|
-
(cb || noop)({err: Gun.log("User is already being created or authenticated!"), wait: true});
|
968
|
-
return gun;
|
969
|
-
}
|
970
|
-
cat.ing = true;
|
971
|
-
|
972
|
-
var act = {}, u, tries = 9;
|
973
|
-
act.a = function(data){
|
974
|
-
if(!data){ return act.b() }
|
975
|
-
if(!data.pub){
|
976
|
-
var tmp = []; Object.keys(data).forEach(function(k){ if('_'==k){ return } tmp.push(data[k]); });
|
977
|
-
return act.b(tmp);
|
978
|
-
}
|
979
|
-
if(act.name){ return act.f(data) }
|
980
|
-
act.c((act.data = data).auth);
|
981
|
-
};
|
982
|
-
act.b = function(list){
|
983
|
-
var get = (act.list = (act.list||[]).concat(list||[])).shift();
|
984
|
-
if(u === get){
|
985
|
-
if(act.name){ return act.err('Your user account is not published for dApps to access, please consider syncing it online, or allowing local access by adding your device as a peer.') }
|
986
|
-
if(alias && tries--){
|
987
|
-
root.get('~@'+alias).once(act.a);
|
988
|
-
return;
|
989
|
-
}
|
990
|
-
return act.err('Wrong user or password.')
|
991
|
-
}
|
992
|
-
root.get(get).once(act.a);
|
993
|
-
};
|
994
|
-
act.c = function(auth){
|
995
|
-
if(u === auth){ return act.b() }
|
996
|
-
if('string' == typeof auth){ return act.c(obj_ify(auth)) } // in case of legacy
|
997
|
-
SEA.work(pass, (act.auth = auth).s, act.d, act.enc); // the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force.
|
998
|
-
};
|
999
|
-
act.d = function(proof){
|
1000
|
-
SEA.decrypt(act.auth.ek, proof, act.e, act.enc);
|
1001
|
-
};
|
1002
|
-
act.e = function(half){
|
1003
|
-
if(u === half){
|
1004
|
-
if(!act.enc){ // try old format
|
1005
|
-
act.enc = {encode: 'utf8'};
|
1006
|
-
return act.c(act.auth);
|
1007
|
-
} act.enc = null; // end backwards
|
1008
|
-
return act.b();
|
1009
|
-
}
|
1010
|
-
act.half = half;
|
1011
|
-
act.f(act.data);
|
1012
|
-
};
|
1013
|
-
act.f = function(pair){
|
1014
|
-
var half = act.half || {}, data = act.data || {};
|
1015
|
-
act.g(act.lol = {pub: pair.pub || data.pub, epub: pair.epub || data.epub, priv: pair.priv || half.priv, epriv: pair.epriv || half.epriv});
|
1016
|
-
};
|
1017
|
-
act.g = function(pair){
|
1018
|
-
if(!pair || !pair.pub || !pair.epub){ return act.b() }
|
1019
|
-
act.pair = pair;
|
1020
|
-
var user = (root._).user, at = (user._);
|
1021
|
-
at.tag;
|
1022
|
-
var upt = at.opt;
|
1023
|
-
at = user._ = root.get('~'+pair.pub)._;
|
1024
|
-
at.opt = upt;
|
1025
|
-
// add our credentials in-memory only to our root user instance
|
1026
|
-
user.is = {pub: pair.pub, epub: pair.epub, alias: alias || pair.pub};
|
1027
|
-
at.sea = act.pair;
|
1028
|
-
cat.ing = false;
|
1029
|
-
try{if(pass && u == (obj_ify(cat.root.graph['~'+pair.pub].auth)||'')[':']){ opt.shuffle = opt.change = pass; } }catch(e){} // migrate UTF8 & Shuffle!
|
1030
|
-
opt.change? act.z() : (cb || noop)(at);
|
1031
|
-
if(SEA.window && ((gun.back('user')._).opt||opt).remember){
|
1032
|
-
// TODO: this needs to be modular.
|
1033
|
-
try{var sS = {};
|
1034
|
-
sS = SEA.window.sessionStorage; // TODO: FIX BUG putting on `.is`!
|
1035
|
-
sS.recall = true;
|
1036
|
-
sS.pair = JSON.stringify(pair); // auth using pair is more reliable than alias/pass
|
1037
|
-
}catch(e){}
|
1038
|
-
}
|
1039
|
-
try{
|
1040
|
-
if(root._.tag.auth){ // auth handle might not be registered yet
|
1041
|
-
(root._).on('auth', at); // TODO: Deprecate this, emit on user instead! Update docs when you do.
|
1042
|
-
} else { setTimeout(function(){ (root._).on('auth', at); },1); } // if not, hackily add a timeout.
|
1043
|
-
//at.on('auth', at) // Arrgh, this doesn't work without event "merge" code, but "merge" code causes stack overflow and crashes after logging in & trying to write data.
|
1044
|
-
}catch(e){
|
1045
|
-
Gun.log("Your 'auth' callback crashed with:", e);
|
1046
|
-
}
|
1047
|
-
};
|
1048
|
-
act.h = function(data){
|
1049
|
-
if(!data){ return act.b() }
|
1050
|
-
alias = data.alias;
|
1051
|
-
if(!alias)
|
1052
|
-
alias = data.alias = "~" + pair.pub;
|
1053
|
-
if(!data.auth){
|
1054
|
-
return act.g(pair);
|
1055
|
-
}
|
1056
|
-
pair = null;
|
1057
|
-
act.c((act.data = data).auth);
|
1058
|
-
};
|
1059
|
-
act.z = function(){
|
1060
|
-
// password update so encrypt private key using new pwd + salt
|
1061
|
-
act.salt = String.random(64); // pseudo-random
|
1062
|
-
SEA.work(opt.change, act.salt, act.y);
|
1063
|
-
};
|
1064
|
-
act.y = function(proof){
|
1065
|
-
SEA.encrypt({priv: act.pair.priv, epriv: act.pair.epriv}, proof, act.x, {raw:1});
|
1066
|
-
};
|
1067
|
-
act.x = function(auth){
|
1068
|
-
act.w(JSON.stringify({ek: auth, s: act.salt}));
|
1069
|
-
};
|
1070
|
-
act.w = function(auth){
|
1071
|
-
if(opt.shuffle){ // delete in future!
|
1072
|
-
console.log('migrate core account from UTF8 & shuffle');
|
1073
|
-
var tmp = {}; Object.keys(act.data).forEach(function(k){ tmp[k] = act.data[k]; });
|
1074
|
-
delete tmp._;
|
1075
|
-
tmp.auth = auth;
|
1076
|
-
root.get('~'+act.pair.pub).put(tmp);
|
1077
|
-
} // end delete
|
1078
|
-
root.get('~'+act.pair.pub).get('auth').put(auth, cb || noop);
|
1079
|
-
};
|
1080
|
-
act.err = function(e){
|
1081
|
-
var ack = {err: Gun.log(e || 'User cannot be found!')};
|
1082
|
-
cat.ing = false;
|
1083
|
-
(cb || noop)(ack);
|
1084
|
-
};
|
1085
|
-
act.plugin = function(name){
|
1086
|
-
if(!(act.name = name)){ return act.err() }
|
1087
|
-
var tmp = [name];
|
1088
|
-
if('~' !== name[0]){
|
1089
|
-
tmp[1] = '~'+name;
|
1090
|
-
tmp[2] = '~@'+name;
|
1091
|
-
}
|
1092
|
-
act.b(tmp);
|
1093
|
-
};
|
1094
|
-
if(pair){
|
1095
|
-
if(pair.priv && pair.epriv)
|
1096
|
-
act.g(pair);
|
1097
|
-
else
|
1098
|
-
root.get('~'+pair.pub).once(act.h);
|
1099
|
-
} else
|
1100
|
-
if(alias){
|
1101
|
-
root.get('~@'+alias).once(act.a);
|
1102
|
-
} else
|
1103
|
-
if(!alias && !pass){
|
1104
|
-
SEA.name(act.plugin);
|
1105
|
-
}
|
1106
|
-
return gun;
|
1107
|
-
};
|
1108
|
-
function obj_ify(o){
|
1109
|
-
if('string' != typeof o){ return o }
|
1110
|
-
try{o = JSON.parse(o);
|
1111
|
-
}catch(e){o={};} return o;
|
1112
|
-
}
|
1113
|
-
})(USE, './auth');
|
1114
|
-
USE(function(module){
|
1115
|
-
var User = USE('./user'), SEA = User.SEA; User.GUN;
|
1116
|
-
User.prototype.recall = function(opt, cb){
|
1117
|
-
var gun = this, root = gun.back(-1);
|
1118
|
-
opt = opt || {};
|
1119
|
-
if(opt && opt.sessionStorage){
|
1120
|
-
if(SEA.window){
|
1121
|
-
try{
|
1122
|
-
var sS = {};
|
1123
|
-
sS = SEA.window.sessionStorage; // TODO: FIX BUG putting on `.is`!
|
1124
|
-
if(sS){
|
1125
|
-
(root._).opt.remember = true;
|
1126
|
-
((gun.back('user')._).opt||opt).remember = true;
|
1127
|
-
if(sS.recall || sS.pair) root.user().auth(JSON.parse(sS.pair), cb); // pair is more reliable than alias/pass
|
1128
|
-
}
|
1129
|
-
}catch(e){}
|
1130
|
-
}
|
1131
|
-
return gun;
|
1132
|
-
}
|
1133
|
-
/*
|
1134
|
-
TODO: copy mhelander's expiry code back in.
|
1135
|
-
Although, we should check with community,
|
1136
|
-
should expiry be core or a plugin?
|
1137
|
-
*/
|
1138
|
-
return gun;
|
1139
|
-
};
|
1140
|
-
})(USE, './recall');
|
1141
|
-
USE(function(module){
|
1142
|
-
var User = USE('./user'), SEA = User.SEA, Gun = User.GUN, noop = function(){};
|
1143
|
-
User.prototype.pair = function(){
|
1144
|
-
var user = this, proxy; // undeprecated, hiding with proxies.
|
1145
|
-
try{ proxy = new Proxy({DANGER:'\u2620'}, {get: function(t,p,r){
|
1146
|
-
if(!user.is || !(user._||'').sea){ return }
|
1147
|
-
return user._.sea[p];
|
1148
|
-
}});}catch(e){}
|
1149
|
-
return proxy;
|
1150
|
-
};
|
1151
|
-
// If authenticated user wants to delete his/her account, let's support it!
|
1152
|
-
User.prototype.delete = async function(alias, pass, cb){
|
1153
|
-
console.log("user.delete() IS DEPRECATED AND WILL BE MOVED TO A MODULE!!!");
|
1154
|
-
var gun = this; gun.back(-1); var user = gun.back('user');
|
1155
|
-
try {
|
1156
|
-
user.auth(alias, pass, function(ack){
|
1157
|
-
var pub = (user.is||{}).pub;
|
1158
|
-
// Delete user data
|
1159
|
-
user.map().once(function(){ this.put(null); });
|
1160
|
-
// Wipe user data from memory
|
1161
|
-
user.leave();
|
1162
|
-
(cb || noop)({ok: 0});
|
1163
|
-
});
|
1164
|
-
} catch (e) {
|
1165
|
-
Gun.log('User.delete failed! Error:', e);
|
1166
|
-
}
|
1167
|
-
return gun;
|
1168
|
-
};
|
1169
|
-
User.prototype.alive = async function(){
|
1170
|
-
console.log("user.alive() IS DEPRECATED!!!");
|
1171
|
-
const gunRoot = this.back(-1);
|
1172
|
-
try {
|
1173
|
-
// All is good. Should we do something more with actual recalled data?
|
1174
|
-
await authRecall(gunRoot);
|
1175
|
-
return gunRoot._.user._
|
1176
|
-
} catch (e) {
|
1177
|
-
const err = 'No session!';
|
1178
|
-
Gun.log(err);
|
1179
|
-
throw { err }
|
1180
|
-
}
|
1181
|
-
};
|
1182
|
-
User.prototype.trust = async function(user){
|
1183
|
-
console.log("`.trust` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
|
1184
|
-
// TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too.
|
1185
|
-
//gun.get('alice').get('age').trust(bob);
|
1186
|
-
if (Gun.is(user)) {
|
1187
|
-
user.get('pub').get((ctx, ev) => {
|
1188
|
-
console.log(ctx, ev);
|
1189
|
-
});
|
1190
|
-
}
|
1191
|
-
user.get('trust').get(path).put(theirPubkey);
|
1192
|
-
|
1193
|
-
// do a lookup on this gun chain directly (that gets bob's copy of the data)
|
1194
|
-
// do a lookup on the metadata trust table for this path (that gets all the pubkeys allowed to write on this path)
|
1195
|
-
// do a lookup on each of those pubKeys ON the path (to get the collab data "layers")
|
1196
|
-
// THEN you perform Jachen's mix operation
|
1197
|
-
// and return the result of that to...
|
1198
|
-
};
|
1199
|
-
User.prototype.grant = function(to, cb){
|
1200
|
-
console.log("`.grant` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
|
1201
|
-
var gun = this, user = gun.back(-1).user(), pair = user._.sea, path = '';
|
1202
|
-
gun.back(function(at){ if(at.is){ return } path += (at.get||''); });
|
1203
|
-
(async function(){
|
1204
|
-
var enc, sec = await user.get('grant').get(pair.pub).get(path).then();
|
1205
|
-
sec = await SEA.decrypt(sec, pair);
|
1206
|
-
if(!sec){
|
1207
|
-
sec = SEA.random(16).toString();
|
1208
|
-
enc = await SEA.encrypt(sec, pair);
|
1209
|
-
user.get('grant').get(pair.pub).get(path).put(enc);
|
1210
|
-
}
|
1211
|
-
var pub = to.get('pub').then();
|
1212
|
-
var epub = to.get('epub').then();
|
1213
|
-
pub = await pub; epub = await epub;
|
1214
|
-
var dh = await SEA.secret(epub, pair);
|
1215
|
-
enc = await SEA.encrypt(sec, dh);
|
1216
|
-
user.get('grant').get(pub).get(path).put(enc, cb);
|
1217
|
-
}());
|
1218
|
-
return gun;
|
1219
|
-
};
|
1220
|
-
User.prototype.secret = function(data, cb){
|
1221
|
-
console.log("`.secret` API MAY BE DELETED OR CHANGED OR RENAMED, DO NOT USE!");
|
1222
|
-
var gun = this, user = gun.back(-1).user(), pair = user.pair(), path = '';
|
1223
|
-
gun.back(function(at){ if(at.is){ return } path += (at.get||''); });
|
1224
|
-
(async function(){
|
1225
|
-
var enc, sec = await user.get('trust').get(pair.pub).get(path).then();
|
1226
|
-
sec = await SEA.decrypt(sec, pair);
|
1227
|
-
if(!sec){
|
1228
|
-
sec = SEA.random(16).toString();
|
1229
|
-
enc = await SEA.encrypt(sec, pair);
|
1230
|
-
user.get('trust').get(pair.pub).get(path).put(enc);
|
1231
|
-
}
|
1232
|
-
enc = await SEA.encrypt(data, sec);
|
1233
|
-
gun.put(enc, cb);
|
1234
|
-
}());
|
1235
|
-
return gun;
|
1236
|
-
};
|
1237
|
-
|
1238
|
-
/**
|
1239
|
-
* returns the decrypted value, encrypted by secret
|
1240
|
-
* @returns {Promise<any>}
|
1241
|
-
// Mark needs to review 1st before officially supported
|
1242
|
-
User.prototype.decrypt = function(cb) {
|
1243
|
-
let gun = this,
|
1244
|
-
path = ''
|
1245
|
-
gun.back(function(at) {
|
1246
|
-
if (at.is) {
|
1247
|
-
return
|
1248
|
-
}
|
1249
|
-
path += at.get || ''
|
1250
|
-
})
|
1251
|
-
return gun
|
1252
|
-
.then(async data => {
|
1253
|
-
if (data == null) {
|
1254
|
-
return
|
1255
|
-
}
|
1256
|
-
const user = gun.back(-1).user()
|
1257
|
-
const pair = user.pair()
|
1258
|
-
let sec = await user
|
1259
|
-
.get('trust')
|
1260
|
-
.get(pair.pub)
|
1261
|
-
.get(path)
|
1262
|
-
sec = await SEA.decrypt(sec, pair)
|
1263
|
-
if (!sec) {
|
1264
|
-
return data
|
1265
|
-
}
|
1266
|
-
let decrypted = await SEA.decrypt(data, sec)
|
1267
|
-
return decrypted
|
1268
|
-
})
|
1269
|
-
.then(res => {
|
1270
|
-
cb && cb(res)
|
1271
|
-
return res
|
1272
|
-
})
|
1273
|
-
}
|
1274
|
-
*/
|
1275
|
-
module.exports = User;
|
1276
|
-
})(USE, './share');
|
1277
|
-
USE(function(module){
|
1278
|
-
var SEA = USE('./sea'), S = USE('./settings'), u;
|
1279
|
-
var Gun = (SEA.window||'').GUN || USE((''+u === typeof MODULE?'.':'')+'./gun', 1);
|
1280
|
-
// After we have a GUN extension to make user registration/login easy, we then need to handle everything else.
|
1281
|
-
|
1282
|
-
// We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change)
|
1283
|
-
Gun.on('opt', function(at){
|
1284
|
-
if(!at.sea){ // only add SEA once per instance, on the "at" context.
|
1285
|
-
at.sea = {own: {}};
|
1286
|
-
at.on('put', check, at); // SEA now runs its firewall on HAM diffs, not all i/o.
|
1287
|
-
}
|
1288
|
-
this.to.next(at); // make sure to call the "next" middleware adapter.
|
1289
|
-
});
|
1290
|
-
|
1291
|
-
// Alright, this next adapter gets run at the per node level in the graph database.
|
1292
|
-
// correction: 2020 it gets run on each key/value pair in a node upon a HAM diff.
|
1293
|
-
// This will let us verify that every property on a node has a value signed by a public key we trust.
|
1294
|
-
// If the signature does not match, the data is just `undefined` so it doesn't get passed on.
|
1295
|
-
// If it does match, then we transform the in-memory "view" of the data into its plain value (without the signature).
|
1296
|
-
// Now NOTE! Some data is "system" data, not user data. Example: List of public keys, aliases, etc.
|
1297
|
-
// This data is self-enforced (the value can only match its ID), but that is handled in the `security` function.
|
1298
|
-
// From the self-enforced data, we can see all the edges in the graph that belong to a public key.
|
1299
|
-
// Example: ~ASDF is the ID of a node with ASDF as its public key, signed alias and salt, and
|
1300
|
-
// its encrypted private key, but it might also have other signed values on it like `profile = <ID>` edge.
|
1301
|
-
// Using that directed edge's ID, we can then track (in memory) which IDs belong to which keys.
|
1302
|
-
// Here is a problem: Multiple public keys can "claim" any node's ID, so this is dangerous!
|
1303
|
-
// This means we should ONLY trust our "friends" (our key ring) public keys, not any ones.
|
1304
|
-
// I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile!
|
1305
|
-
|
1306
|
-
function check(msg){ // REVISE / IMPROVE, NO NEED TO PASS MSG/EVE EACH SUB?
|
1307
|
-
var eve = this, at = eve.as, put = msg.put, soul = put['#'], key = put['.'], val = put[':'], state = put['>'], id = msg['#'], tmp;
|
1308
|
-
if(!soul || !key){ return }
|
1309
|
-
if((msg._||'').faith && (at.opt||'').faith && 'function' == typeof msg._){
|
1310
|
-
SEA.opt.pack(put, function(raw){
|
1311
|
-
SEA.verify(raw, false, function(data){ // this is synchronous if false
|
1312
|
-
put['='] = SEA.opt.unpack(data);
|
1313
|
-
eve.to.next(msg);
|
1314
|
-
});});
|
1315
|
-
return
|
1316
|
-
}
|
1317
|
-
var no = function(why){ at.on('in', {'@': id, err: msg.err = why}); }; // exploit internal relay stun for now, maybe violates spec, but testing for now. // Note: this may be only the sharded message, not original batch.
|
1318
|
-
//var no = function(why){ msg.ack(why) };
|
1319
|
-
(msg._||'').DBG && ((msg._||'').DBG.c = +new Date);
|
1320
|
-
if(0 <= soul.indexOf('<?')){ // special case for "do not sync data X old" forget
|
1321
|
-
// 'a~pub.key/b<?9'
|
1322
|
-
tmp = parseFloat(soul.split('<?')[1]||'');
|
1323
|
-
if(tmp && (state < (Gun.state() - (tmp * 1000)))){ // sec to ms
|
1324
|
-
(tmp = msg._) && (tmp.stun) && (tmp.stun--); // THIS IS BAD CODE! It assumes GUN internals do something that will probably change in future, but hacking in now.
|
1325
|
-
return; // omit!
|
1326
|
-
}
|
1327
|
-
}
|
1328
|
-
|
1329
|
-
if('~@' === soul){ // special case for shared system data, the list of aliases.
|
1330
|
-
check.alias(eve, msg, val, key, soul, at, no); return;
|
1331
|
-
}
|
1332
|
-
if('~@' === soul.slice(0,2)){ // special case for shared system data, the list of public keys for an alias.
|
1333
|
-
check.pubs(eve, msg, val, key, soul, at, no); return;
|
1334
|
-
}
|
1335
|
-
//if('~' === soul.slice(0,1) && 2 === (tmp = soul.slice(1)).split('.').length){ // special case, account data for a public key.
|
1336
|
-
if(tmp = SEA.opt.pub(soul)){ // special case, account data for a public key.
|
1337
|
-
check.pub(eve, msg, val, key, soul, at, no, at.user||'', tmp); return;
|
1338
|
-
}
|
1339
|
-
if(0 <= soul.indexOf('#')){ // special case for content addressing immutable hashed data.
|
1340
|
-
check.hash(eve, msg, val, key, soul, at, no); return;
|
1341
|
-
}
|
1342
|
-
check.any(eve, msg, val, key, soul, at, no, at.user||''); return;
|
1343
|
-
}
|
1344
|
-
check.hash = function(eve, msg, val, key, soul, at, no){ // mark unbuilt @i001962 's epic hex contrib!
|
1345
|
-
SEA.work(val, null, function(data){
|
1346
|
-
function hexToBase64(hexStr) {
|
1347
|
-
let base64 = "";
|
1348
|
-
for(let i = 0; i < hexStr.length; i++) {
|
1349
|
-
base64 += !(i - 1 & 1) ? String.fromCharCode(parseInt(hexStr.substring(i - 1, i + 1), 16)) : "";}
|
1350
|
-
return btoa(base64);}
|
1351
|
-
if(data && data === key.split('#').slice(-1)[0]){ return eve.to.next(msg) }
|
1352
|
-
else if (data && data === hexToBase64(key.split('#').slice(-1)[0])){
|
1353
|
-
return eve.to.next(msg) }
|
1354
|
-
no("Data hash not same as hash!");
|
1355
|
-
}, {name: 'SHA-256'});
|
1356
|
-
};
|
1357
|
-
check.alias = function(eve, msg, val, key, soul, at, no){ // Example: {_:#~@, ~@alice: {#~@alice}}
|
1358
|
-
if(!val){ return no("Data must exist!") } // data MUST exist
|
1359
|
-
if('~@'+key === link_is(val)){ return eve.to.next(msg) } // in fact, it must be EXACTLY equal to itself
|
1360
|
-
no("Alias not same!"); // if it isn't, reject.
|
1361
|
-
};
|
1362
|
-
check.pubs = function(eve, msg, val, key, soul, at, no){ // Example: {_:#~@alice, ~asdf: {#~asdf}}
|
1363
|
-
if(!val){ return no("Alias must exist!") } // data MUST exist
|
1364
|
-
if(key === link_is(val)){ return eve.to.next(msg) } // and the ID must be EXACTLY equal to its property
|
1365
|
-
no("Alias not same!"); // that way nobody can tamper with the list of public keys.
|
1366
|
-
};
|
1367
|
-
check.pub = async function(eve, msg, val, key, soul, at, no, user, pub){ var tmp; // Example: {_:#~asdf, hello:'world'~fdsa}}
|
1368
|
-
const raw = await S.parse(val) || {};
|
1369
|
-
const verify = (certificate, certificant, cb) => {
|
1370
|
-
if (certificate.m && certificate.s && certificant && pub)
|
1371
|
-
// now verify certificate
|
1372
|
-
return SEA.verify(certificate, pub, data => { // check if "pub" (of the graph owner) really issued this cert
|
1373
|
-
if (u !== data && u !== data.e && msg.put['>'] && msg.put['>'] > parseFloat(data.e)) return no("Certificate expired.") // certificate expired
|
1374
|
-
// "data.c" = a list of certificants/certified users
|
1375
|
-
// "data.w" = lex WRITE permission, in the future, there will be "data.r" which means lex READ permission
|
1376
|
-
if (u !== data && data.c && data.w && (data.c === certificant || data.c.indexOf('*' ) > -1)) {
|
1377
|
-
// ok, now "certificant" is in the "certificants" list, but is "path" allowed? Check path
|
1378
|
-
let path = soul.indexOf('/') > -1 ? soul.replace(soul.substring(0, soul.indexOf('/') + 1), '') : '';
|
1379
|
-
String.match = String.match || Gun.text.match;
|
1380
|
-
const w = Array.isArray(data.w) ? data.w : typeof data.w === 'object' || typeof data.w === 'string' ? [data.w] : [];
|
1381
|
-
for (const lex of w) {
|
1382
|
-
if ((String.match(path, lex['#']) && String.match(key, lex['.'])) || (!lex['.'] && String.match(path, lex['#'])) || (!lex['#'] && String.match(key, lex['.'])) || String.match((path ? path + '/' + key : key), lex['#'] || lex)) {
|
1383
|
-
// is Certificant forced to present in Path
|
1384
|
-
if (lex['+'] && lex['+'].indexOf('*') > -1 && path && path.indexOf(certificant) == -1 && key.indexOf(certificant) == -1) return no(`Path "${path}" or key "${key}" must contain string "${certificant}".`)
|
1385
|
-
// path is allowed, but is there any WRITE block? Check it out
|
1386
|
-
if (data.wb && (typeof data.wb === 'string' || ((data.wb || {})['#']))) { // "data.wb" = path to the WRITE block
|
1387
|
-
var root = eve.as.root.$.back(-1);
|
1388
|
-
if (typeof data.wb === 'string' && '~' !== data.wb.slice(0, 1)) root = root.get('~' + pub);
|
1389
|
-
return root.get(data.wb).get(certificant).once(value => { // TODO: INTENT TO DEPRECATE.
|
1390
|
-
if (value && (value === 1 || value === true)) return no(`Certificant ${certificant} blocked.`)
|
1391
|
-
return cb(data)
|
1392
|
-
})
|
1393
|
-
}
|
1394
|
-
return cb(data)
|
1395
|
-
}
|
1396
|
-
}
|
1397
|
-
return no("Certificate verification fail.")
|
1398
|
-
}
|
1399
|
-
})
|
1400
|
-
return
|
1401
|
-
};
|
1402
|
-
|
1403
|
-
if ('pub' === key && '~' + pub === soul) {
|
1404
|
-
if (val === pub) return eve.to.next(msg) // the account MUST match `pub` property that equals the ID of the public key.
|
1405
|
-
return no("Account not same!")
|
1406
|
-
}
|
1407
|
-
|
1408
|
-
if ((tmp = user.is) && tmp.pub && !raw['*'] && !raw['+'] && (pub === tmp.pub || (pub !== tmp.pub && ((msg._.msg || {}).opt || {}).cert))){
|
1409
|
-
SEA.opt.pack(msg.put, packed => {
|
1410
|
-
SEA.sign(packed, (user._).sea, async function(data) {
|
1411
|
-
if (u === data) return no(SEA.err || 'Signature fail.')
|
1412
|
-
msg.put[':'] = {':': tmp = SEA.opt.unpack(data.m), '~': data.s};
|
1413
|
-
msg.put['='] = tmp;
|
1414
|
-
|
1415
|
-
// if writing to own graph, just allow it
|
1416
|
-
if (pub === user.is.pub) {
|
1417
|
-
if (tmp = link_is(val)) (at.sea.own[tmp] = at.sea.own[tmp] || {})[pub] = 1;
|
1418
|
-
JSON.stringifyAsync(msg.put[':'], function(err,s){
|
1419
|
-
if(err){ return no(err || "Stringify error.") }
|
1420
|
-
msg.put[':'] = s;
|
1421
|
-
return eve.to.next(msg);
|
1422
|
-
});
|
1423
|
-
return
|
1424
|
-
}
|
1425
|
-
|
1426
|
-
// if writing to other's graph, check if cert exists then try to inject cert into put, also inject self pub so that everyone can verify the put
|
1427
|
-
if (pub !== user.is.pub && ((msg._.msg || {}).opt || {}).cert) {
|
1428
|
-
const cert = await S.parse(msg._.msg.opt.cert);
|
1429
|
-
// even if cert exists, we must verify it
|
1430
|
-
if (cert && cert.m && cert.s)
|
1431
|
-
verify(cert, user.is.pub, _ => {
|
1432
|
-
msg.put[':']['+'] = cert; // '+' is a certificate
|
1433
|
-
msg.put[':']['*'] = user.is.pub; // '*' is pub of the user who puts
|
1434
|
-
JSON.stringifyAsync(msg.put[':'], function(err,s){
|
1435
|
-
if(err){ return no(err || "Stringify error.") }
|
1436
|
-
msg.put[':'] = s;
|
1437
|
-
return eve.to.next(msg);
|
1438
|
-
});
|
1439
|
-
return
|
1440
|
-
});
|
1441
|
-
}
|
1442
|
-
}, {raw: 1});
|
1443
|
-
});
|
1444
|
-
return;
|
1445
|
-
}
|
1446
|
-
|
1447
|
-
SEA.opt.pack(msg.put, packed => {
|
1448
|
-
SEA.verify(packed, raw['*'] || pub, function(data){ var tmp;
|
1449
|
-
data = SEA.opt.unpack(data);
|
1450
|
-
if (u === data) return no("Unverified data.") // make sure the signature matches the account it claims to be on. // reject any updates that are signed with a mismatched account.
|
1451
|
-
if ((tmp = link_is(data)) && pub === SEA.opt.pub(tmp)) (at.sea.own[tmp] = at.sea.own[tmp] || {})[pub] = 1;
|
1452
|
-
|
1453
|
-
// check if cert ('+') and putter's pub ('*') exist
|
1454
|
-
if (raw['+'] && raw['+']['m'] && raw['+']['s'] && raw['*'])
|
1455
|
-
// now verify certificate
|
1456
|
-
verify(raw['+'], raw['*'], _ => {
|
1457
|
-
msg.put['='] = data;
|
1458
|
-
return eve.to.next(msg);
|
1459
|
-
});
|
1460
|
-
else {
|
1461
|
-
msg.put['='] = data;
|
1462
|
-
return eve.to.next(msg);
|
1463
|
-
}
|
1464
|
-
});
|
1465
|
-
});
|
1466
|
-
return
|
1467
|
-
};
|
1468
|
-
check.any = function(eve, msg, val, key, soul, at, no, user){ if(at.opt.secure){ return no("Soul missing public key at '" + key + "'.") }
|
1469
|
-
// TODO: Ask community if should auto-sign non user-graph data.
|
1470
|
-
at.on('secure', function(msg){ this.off();
|
1471
|
-
if(!at.opt.secure){ return eve.to.next(msg) }
|
1472
|
-
no("Data cannot be changed.");
|
1473
|
-
}).on.on('secure', msg);
|
1474
|
-
return;
|
1475
|
-
};
|
1476
|
-
|
1477
|
-
var valid = Gun.valid, link_is = function(d,l){ return 'string' == typeof (l = valid(d)) && l }; (Gun.state||'').ify;
|
1478
|
-
|
1479
|
-
var pubcut = /[^\w_-]/; // anything not alphanumeric or _ -
|
1480
|
-
SEA.opt.pub = function(s){
|
1481
|
-
if(!s){ return }
|
1482
|
-
s = s.split('~');
|
1483
|
-
if(!s || !(s = s[1])){ return }
|
1484
|
-
s = s.split(pubcut).slice(0,2);
|
1485
|
-
if(!s || 2 != s.length){ return }
|
1486
|
-
if('@' === (s[0]||'')[0]){ return }
|
1487
|
-
s = s.slice(0,2).join('.');
|
1488
|
-
return s;
|
1489
|
-
};
|
1490
|
-
SEA.opt.stringy = function(t){
|
1491
|
-
// TODO: encrypt etc. need to check string primitive. Make as breaking change.
|
1492
|
-
};
|
1493
|
-
SEA.opt.pack = function(d,cb,k, n,s){ var tmp, f; // pack for verifying
|
1494
|
-
if(SEA.opt.check(d)){ return cb(d) }
|
1495
|
-
if(d && d['#'] && d['.'] && d['>']){ tmp = d[':']; f = 1; }
|
1496
|
-
JSON.parseAsync(f? tmp : d, function(err, meta){
|
1497
|
-
var sig = ((u !== (meta||'')[':']) && (meta||'')['~']); // or just ~ check?
|
1498
|
-
if(!sig){ cb(d); return }
|
1499
|
-
cb({m: {'#':s||d['#'],'.':k||d['.'],':':(meta||'')[':'],'>':d['>']||Gun.state.is(n, k)}, s: sig});
|
1500
|
-
});
|
1501
|
-
};
|
1502
|
-
var O = SEA.opt;
|
1503
|
-
SEA.opt.unpack = function(d, k, n){ var tmp;
|
1504
|
-
if(u === d){ return }
|
1505
|
-
if(d && (u !== (tmp = d[':']))){ return tmp }
|
1506
|
-
k = k || O.fall_key; if(!n && O.fall_val){ n = {}; n[k] = O.fall_val; }
|
1507
|
-
if(!k || !n){ return }
|
1508
|
-
if(d === n[k]){ return d }
|
1509
|
-
if(!SEA.opt.check(n[k])){ return d }
|
1510
|
-
var soul = (n && n._ && n._['#']) || O.fall_soul, s = Gun.state.is(n, k) || O.fall_state;
|
1511
|
-
if(d && 4 === d.length && soul === d[0] && k === d[1] && fl(s) === fl(d[3])){
|
1512
|
-
return d[2];
|
1513
|
-
}
|
1514
|
-
if(s < SEA.opt.shuffle_attack){
|
1515
|
-
return d;
|
1516
|
-
}
|
1517
|
-
};
|
1518
|
-
SEA.opt.shuffle_attack = 1546329600000; // Jan 1, 2019
|
1519
|
-
var fl = Math.floor; // TODO: Still need to fix inconsistent state issue.
|
1520
|
-
// TODO: Potential bug? If pub/priv key starts with `-`? IDK how possible.
|
1521
|
-
|
1522
|
-
})(USE, './index');
|
1523
|
-
}());
|
1524
|
-
} (sea));
|
1525
|
-
|
1526
|
-
var seaExports = sea.exports;
|
1527
|
-
var SEA = /*@__PURE__*/getDefaultExportFromCjs(seaExports);
|
1528
|
-
|
1529
|
-
let contractAddresses$1 = {
|
1530
|
-
PROOF_OF_INTEGRITY_ADDRESS: "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512",
|
1531
|
-
STEALTH_ANNOUNCER_ADDRESS: "0x5FbDB2315678afecb367f032d93F642f64180aa3"
|
1532
|
-
};
|
1533
|
-
|
1534
|
-
if (typeof window === 'undefined') {
|
1535
|
-
try {
|
1536
|
-
const { fileURLToPath } = require('url');
|
1537
|
-
const { dirname, join } = require('path');
|
1538
|
-
const { readFileSync } = require('fs');
|
1539
|
-
|
1540
|
-
const __filename = fileURLToPath(import.meta.url);
|
1541
|
-
const __dirname = dirname(__filename);
|
1542
|
-
|
1543
|
-
const rawdata = readFileSync(join(__dirname, 'contract-address.json'));
|
1544
|
-
contractAddresses$1 = JSON.parse(rawdata);
|
1545
|
-
console.log("Loaded contract addresses:", contractAddresses$1);
|
1546
|
-
} catch (error) {
|
1547
|
-
console.warn("Warning: contract-address.json not found or invalid");
|
1548
|
-
}
|
1549
|
-
}
|
1550
|
-
|
1551
|
-
const LOCAL_CONFIG = {
|
1552
|
-
CHAIN_ID: 1337,
|
1553
|
-
PROOF_OF_INTEGRITY_ADDRESS: contractAddresses$1.PROOF_OF_INTEGRITY_ADDRESS,
|
1554
|
-
STEALTH_ANNOUNCER_ADDRESS: contractAddresses$1.STEALTH_ANNOUNCER_ADDRESS,
|
1555
|
-
RPC_URL: "http://127.0.0.1:8545",
|
1556
|
-
GUN_PEER: "http://localhost:8765/gun"
|
1557
|
-
};
|
1558
|
-
|
1559
|
-
const STEALTH_ANNOUNCER_ABI = [
|
1560
|
-
{
|
1561
|
-
"inputs": [
|
1562
|
-
{
|
1563
|
-
"internalType": "address",
|
1564
|
-
"name": "_devAddress",
|
1565
|
-
"type": "address"
|
1566
|
-
}
|
1567
|
-
],
|
1568
|
-
"stateMutability": "nonpayable",
|
1569
|
-
"type": "constructor"
|
1570
|
-
},
|
1571
|
-
{
|
1572
|
-
"anonymous": false,
|
1573
|
-
"inputs": [
|
1574
|
-
{
|
1575
|
-
"internalType": "string",
|
1576
|
-
"name": "senderPublicKey",
|
1577
|
-
"type": "string"
|
1578
|
-
},
|
1579
|
-
{
|
1580
|
-
"internalType": "string",
|
1581
|
-
"name": "spendingPublicKey",
|
1582
|
-
"type": "string"
|
1583
|
-
},
|
1584
|
-
{
|
1585
|
-
"internalType": "address",
|
1586
|
-
"name": "stealthAddress",
|
1587
|
-
"type": "address"
|
1588
|
-
},
|
1589
|
-
{
|
1590
|
-
"internalType": "uint256",
|
1591
|
-
"name": "timestamp",
|
1592
|
-
"type": "uint256"
|
1593
|
-
}
|
1594
|
-
],
|
1595
|
-
"name": "StealthPaymentAnnounced",
|
1596
|
-
"type": "event"
|
1597
|
-
},
|
1598
|
-
{
|
1599
|
-
"anonymous": false,
|
1600
|
-
"inputs": [
|
1601
|
-
{
|
1602
|
-
"internalType": "address",
|
1603
|
-
"name": "newAddress",
|
1604
|
-
"type": "address"
|
1605
|
-
}
|
1606
|
-
],
|
1607
|
-
"name": "DevAddressUpdated",
|
1608
|
-
"type": "event"
|
1609
|
-
},
|
1610
|
-
{
|
1611
|
-
"anonymous": false,
|
1612
|
-
"inputs": [
|
1613
|
-
{
|
1614
|
-
"internalType": "uint256",
|
1615
|
-
"name": "newFee",
|
1616
|
-
"type": "uint256"
|
1617
|
-
}
|
1618
|
-
],
|
1619
|
-
"name": "DevFeeUpdated",
|
1620
|
-
"type": "event"
|
1621
|
-
},
|
1622
|
-
{
|
1623
|
-
"inputs": [
|
1624
|
-
{
|
1625
|
-
"internalType": "string",
|
1626
|
-
"name": "senderPublicKey",
|
1627
|
-
"type": "string"
|
1628
|
-
},
|
1629
|
-
{
|
1630
|
-
"internalType": "string",
|
1631
|
-
"name": "spendingPublicKey",
|
1632
|
-
"type": "string"
|
1633
|
-
},
|
1634
|
-
{
|
1635
|
-
"internalType": "address",
|
1636
|
-
"name": "stealthAddress",
|
1637
|
-
"type": "address"
|
1638
|
-
}
|
1639
|
-
],
|
1640
|
-
"name": "announcePayment",
|
1641
|
-
"outputs": [],
|
1642
|
-
"stateMutability": "payable",
|
1643
|
-
"type": "function"
|
1644
|
-
},
|
1645
|
-
{
|
1646
|
-
"inputs": [],
|
1647
|
-
"name": "devAddress",
|
1648
|
-
"outputs": [
|
1649
|
-
{
|
1650
|
-
"internalType": "address",
|
1651
|
-
"name": "",
|
1652
|
-
"type": "address"
|
1653
|
-
}
|
1654
|
-
],
|
1655
|
-
"stateMutability": "view",
|
1656
|
-
"type": "function"
|
1657
|
-
},
|
1658
|
-
{
|
1659
|
-
"inputs": [],
|
1660
|
-
"name": "devFee",
|
1661
|
-
"outputs": [
|
1662
|
-
{
|
1663
|
-
"internalType": "uint256",
|
1664
|
-
"name": "",
|
1665
|
-
"type": "uint256"
|
1666
|
-
}
|
1667
|
-
],
|
1668
|
-
"stateMutability": "view",
|
1669
|
-
"type": "function"
|
1670
|
-
},
|
1671
|
-
{
|
1672
|
-
"inputs": [],
|
1673
|
-
"name": "getAnnouncementsCount",
|
1674
|
-
"outputs": [
|
1675
|
-
{
|
1676
|
-
"internalType": "uint256",
|
1677
|
-
"name": "",
|
1678
|
-
"type": "uint256"
|
1679
|
-
}
|
1680
|
-
],
|
1681
|
-
"stateMutability": "view",
|
1682
|
-
"type": "function"
|
1683
|
-
},
|
1684
|
-
{
|
1685
|
-
"inputs": [
|
1686
|
-
{
|
1687
|
-
"internalType": "uint256",
|
1688
|
-
"name": "fromIndex",
|
1689
|
-
"type": "uint256"
|
1690
|
-
},
|
1691
|
-
{
|
1692
|
-
"internalType": "uint256",
|
1693
|
-
"name": "toIndex",
|
1694
|
-
"type": "uint256"
|
1695
|
-
}
|
1696
|
-
],
|
1697
|
-
"name": "getAnnouncementsInRange",
|
1698
|
-
"outputs": [
|
1699
|
-
{
|
1700
|
-
"components": [
|
1701
|
-
{
|
1702
|
-
"internalType": "string",
|
1703
|
-
"name": "senderPublicKey",
|
1704
|
-
"type": "string"
|
1705
|
-
},
|
1706
|
-
{
|
1707
|
-
"internalType": "string",
|
1708
|
-
"name": "spendingPublicKey",
|
1709
|
-
"type": "string"
|
1710
|
-
},
|
1711
|
-
{
|
1712
|
-
"internalType": "address",
|
1713
|
-
"name": "stealthAddress",
|
1714
|
-
"type": "address"
|
1715
|
-
},
|
1716
|
-
{
|
1717
|
-
"internalType": "uint256",
|
1718
|
-
"name": "timestamp",
|
1719
|
-
"type": "uint256"
|
1720
|
-
}
|
1721
|
-
],
|
1722
|
-
"internalType": "struct StealthAnnouncer.StealthAnnouncement[]",
|
1723
|
-
"name": "",
|
1724
|
-
"type": "tuple[]"
|
1725
|
-
}
|
1726
|
-
],
|
1727
|
-
"stateMutability": "view",
|
1728
|
-
"type": "function"
|
1729
|
-
},
|
1730
|
-
{
|
1731
|
-
"inputs": [
|
1732
|
-
{
|
1733
|
-
"internalType": "uint256",
|
1734
|
-
"name": "_newFee",
|
1735
|
-
"type": "uint256"
|
1736
|
-
}
|
1737
|
-
],
|
1738
|
-
"name": "updateDevFee",
|
1739
|
-
"outputs": [],
|
1740
|
-
"stateMutability": "nonpayable",
|
1741
|
-
"type": "function"
|
1742
|
-
},
|
1743
|
-
{
|
1744
|
-
"inputs": [
|
1745
|
-
{
|
1746
|
-
"internalType": "address",
|
1747
|
-
"name": "_newAddress",
|
1748
|
-
"type": "address"
|
1749
|
-
}
|
1750
|
-
],
|
1751
|
-
"name": "updateDevAddress",
|
1752
|
-
"outputs": [],
|
1753
|
-
"stateMutability": "nonpayable",
|
1754
|
-
"type": "function"
|
1755
|
-
},
|
1756
|
-
{
|
1757
|
-
"inputs": [],
|
1758
|
-
"name": "withdrawStuckETH",
|
1759
|
-
"outputs": [],
|
1760
|
-
"stateMutability": "nonpayable",
|
1761
|
-
"type": "function"
|
1762
|
-
}
|
1763
|
-
];
|
1764
|
-
|
1765
|
-
const PROOF_OF_INTEGRITY_ABI = [
|
1766
|
-
{
|
1767
|
-
"inputs": [
|
1768
|
-
{
|
1769
|
-
"internalType": "bytes[]",
|
1770
|
-
"name": "nodeIds",
|
1771
|
-
"type": "bytes[]"
|
1772
|
-
},
|
1773
|
-
{
|
1774
|
-
"internalType": "bytes32[]",
|
1775
|
-
"name": "contentHashes",
|
1776
|
-
"type": "bytes32[]"
|
1777
|
-
}
|
1778
|
-
],
|
1779
|
-
"name": "batchUpdateData",
|
1780
|
-
"outputs": [],
|
1781
|
-
"stateMutability": "nonpayable",
|
1782
|
-
"type": "function"
|
1783
|
-
},
|
1784
|
-
{
|
1785
|
-
"anonymous": false,
|
1786
|
-
"inputs": [
|
1787
|
-
{
|
1788
|
-
"indexed": true,
|
1789
|
-
"internalType": "bytes",
|
1790
|
-
"name": "nodeId",
|
1791
|
-
"type": "bytes"
|
1792
|
-
},
|
1793
|
-
{
|
1794
|
-
"indexed": false,
|
1795
|
-
"internalType": "bytes32",
|
1796
|
-
"name": "contentHash",
|
1797
|
-
"type": "bytes32"
|
1798
|
-
},
|
1799
|
-
{
|
1800
|
-
"indexed": false,
|
1801
|
-
"internalType": "address",
|
1802
|
-
"name": "updater",
|
1803
|
-
"type": "address"
|
1804
|
-
}
|
1805
|
-
],
|
1806
|
-
"name": "DataUpdated",
|
1807
|
-
"type": "event"
|
1808
|
-
},
|
1809
|
-
{
|
1810
|
-
"inputs": [
|
1811
|
-
{
|
1812
|
-
"internalType": "bytes",
|
1813
|
-
"name": "nodeId",
|
1814
|
-
"type": "bytes"
|
1815
|
-
}
|
1816
|
-
],
|
1817
|
-
"name": "getLatestRecord",
|
1818
|
-
"outputs": [
|
1819
|
-
{
|
1820
|
-
"internalType": "bytes32",
|
1821
|
-
"name": "",
|
1822
|
-
"type": "bytes32"
|
1823
|
-
},
|
1824
|
-
{
|
1825
|
-
"internalType": "uint256",
|
1826
|
-
"name": "",
|
1827
|
-
"type": "uint256"
|
1828
|
-
},
|
1829
|
-
{
|
1830
|
-
"internalType": "address",
|
1831
|
-
"name": "",
|
1832
|
-
"type": "address"
|
1833
|
-
}
|
1834
|
-
],
|
1835
|
-
"stateMutability": "view",
|
1836
|
-
"type": "function"
|
1837
|
-
},
|
1838
|
-
{
|
1839
|
-
"inputs": [
|
1840
|
-
{
|
1841
|
-
"internalType": "bytes",
|
1842
|
-
"name": "nodeId",
|
1843
|
-
"type": "bytes"
|
1844
|
-
},
|
1845
|
-
{
|
1846
|
-
"internalType": "bytes32",
|
1847
|
-
"name": "contentHash",
|
1848
|
-
"type": "bytes32"
|
1849
|
-
}
|
1850
|
-
],
|
1851
|
-
"name": "updateData",
|
1852
|
-
"outputs": [],
|
1853
|
-
"stateMutability": "nonpayable",
|
1854
|
-
"type": "function"
|
1855
|
-
},
|
1856
|
-
{
|
1857
|
-
"inputs": [
|
1858
|
-
{
|
1859
|
-
"internalType": "bytes",
|
1860
|
-
"name": "nodeId",
|
1861
|
-
"type": "bytes"
|
1862
|
-
},
|
1863
|
-
{
|
1864
|
-
"internalType": "bytes32",
|
1865
|
-
"name": "contentHash",
|
1866
|
-
"type": "bytes32"
|
1867
|
-
}
|
1868
|
-
],
|
1869
|
-
"name": "verifyData",
|
1870
|
-
"outputs": [
|
1871
|
-
{
|
1872
|
-
"internalType": "bool",
|
1873
|
-
"name": "",
|
1874
|
-
"type": "bool"
|
1875
|
-
},
|
1876
|
-
{
|
1877
|
-
"internalType": "uint256",
|
1878
|
-
"name": "",
|
1879
|
-
"type": "uint256"
|
1880
|
-
},
|
1881
|
-
{
|
1882
|
-
"internalType": "address",
|
1883
|
-
"name": "",
|
1884
|
-
"type": "address"
|
1885
|
-
}
|
1886
|
-
],
|
1887
|
-
"stateMutability": "view",
|
1888
|
-
"type": "function"
|
1889
|
-
}
|
1890
|
-
];
|
1891
|
-
const STEALTH_ANNOUNCER_ADDRESS = "...";
|
1892
|
-
|
1893
|
-
// =============================================
|
1894
|
-
// IMPORTS AND GLOBAL VARIABLES
|
1895
|
-
// =============================================
|
1896
|
-
|
1897
|
-
let PROOF_CONTRACT_ADDRESS;
|
1898
|
-
let rpcUrl = "";
|
1899
|
-
let privateKey = "";
|
1900
|
-
|
1901
|
-
const MESSAGE_TO_SIGN = "Access GunDB with Ethereum";
|
1902
|
-
|
1903
|
-
let contractAddresses = {
|
1904
|
-
PROOF_OF_INTEGRITY_ADDRESS: null,
|
1905
|
-
STEALTH_ANNOUNCER_ADDRESS: STEALTH_ANNOUNCER_ADDRESS
|
1906
|
-
};
|
1907
|
-
|
1908
|
-
// Solo per Node.js
|
1909
|
-
if (typeof window === 'undefined') {
|
1910
|
-
const { fileURLToPath } = require('url');
|
1911
|
-
const { dirname } = require('path');
|
1912
|
-
const { readFileSync } = require('fs');
|
1913
|
-
const path = require('path');
|
1914
|
-
|
1915
|
-
const __filename = fileURLToPath(import.meta.url);
|
1916
|
-
const __dirname = dirname(__filename);
|
1917
|
-
|
1918
|
-
try {
|
1919
|
-
const rawdata = readFileSync(path.join(__dirname, 'contract-address.json'), 'utf8');
|
1920
|
-
contractAddresses = JSON.parse(rawdata);
|
1921
|
-
console.log('Loaded contract addresses:', contractAddresses);
|
1922
|
-
} catch (err) {
|
1923
|
-
console.warn('Warning: contract-address.json not found or invalid');
|
1924
|
-
}
|
1925
|
-
}
|
1926
|
-
|
1927
|
-
// =============================================
|
1928
|
-
// UTILITY FUNCTIONS
|
1929
|
-
// =============================================
|
1930
|
-
/**
|
1931
|
-
* Generates a random node ID for GunDB
|
1932
|
-
* @returns {string} A random hexadecimal string
|
1933
|
-
*/
|
1934
|
-
function generateRandomId() {
|
1935
|
-
return ethers.hexlify(ethers.randomBytes(32)).slice(2);
|
1936
|
-
}
|
1937
|
-
|
1938
|
-
/**
|
1939
|
-
* Generates a password from a signature.
|
1940
|
-
* @param {string} signature - The signature to derive the password from.
|
1941
|
-
* @returns {string|null} The generated password or null if generation fails.
|
1942
|
-
*/
|
1943
|
-
function generatePassword(signature) {
|
1944
|
-
try {
|
1945
|
-
const hexSignature = ethers.hexlify(signature);
|
1946
|
-
const hash = ethers.keccak256(hexSignature);
|
1947
|
-
console.log("Generated password:", hash);
|
1948
|
-
return hash;
|
1949
|
-
} catch (error) {
|
1950
|
-
console.error("Error generating password:", error);
|
1951
|
-
return null;
|
1952
|
-
}
|
1953
|
-
}
|
1954
|
-
|
1955
|
-
/**
|
1956
|
-
* Converts a Gun private key to an Ethereum account.
|
1957
|
-
* @param {string} gunPrivateKey - The Gun private key in base64url format.
|
1958
|
-
* @returns {Object} An object containing the Ethereum account and public key.
|
1959
|
-
*/
|
1960
|
-
function gunToEthAccount(gunPrivateKey) {
|
1961
|
-
// Function to convert base64url to hex
|
1962
|
-
const base64UrlToHex = (base64url) => {
|
1963
|
-
const padding = "=".repeat((4 - (base64url.length % 4)) % 4);
|
1964
|
-
const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/") + padding;
|
1965
|
-
const binary = atob(base64);
|
1966
|
-
return Array.from(binary, (char) =>
|
1967
|
-
char.charCodeAt(0).toString(16).padStart(2, "0")
|
1968
|
-
).join("");
|
1969
|
-
};
|
1970
|
-
|
1971
|
-
// Convert Gun private key to hex format
|
1972
|
-
const hexPrivateKey = "0x" + base64UrlToHex(gunPrivateKey);
|
1973
|
-
|
1974
|
-
// Create an Ethereum wallet from the private key
|
1975
|
-
const wallet = new ethers.Wallet(hexPrivateKey);
|
1976
|
-
|
1977
|
-
// Get the public address (public key)
|
1978
|
-
const publicKey = wallet.address;
|
1979
|
-
|
1980
|
-
return {
|
1981
|
-
account: wallet,
|
1982
|
-
publicKey: publicKey,
|
1983
|
-
privateKey: hexPrivateKey,
|
1984
|
-
};
|
1985
|
-
}
|
1986
|
-
|
1987
|
-
/**
|
1988
|
-
* Gets an Ethereum signer based on current configuration
|
1989
|
-
* @returns {Promise<ethers.Signer>} The configured signer
|
1990
|
-
* @throws {Error} If no valid provider is found
|
1991
|
-
*/
|
1992
|
-
const getSigner = async () => {
|
1993
|
-
if (rpcUrl && privateKey) {
|
1994
|
-
// Standalone mode with local provider
|
1995
|
-
const provider = new ethers.JsonRpcProvider(rpcUrl, {
|
1996
|
-
chainId: LOCAL_CONFIG.CHAIN_ID,
|
1997
|
-
name: "localhost"
|
1998
|
-
});
|
1999
|
-
return new ethers.Wallet(privateKey, provider);
|
2000
|
-
} else if (
|
2001
|
-
typeof window !== "undefined" &&
|
2002
|
-
typeof window.ethereum !== "undefined"
|
2003
|
-
) {
|
2004
|
-
// Browser mode
|
2005
|
-
await window.ethereum.request({ method: "eth_requestAccounts" });
|
2006
|
-
const provider = new ethers.BrowserProvider(window.ethereum);
|
2007
|
-
return provider.getSigner();
|
2008
|
-
} else {
|
2009
|
-
throw new Error("No valid Ethereum provider found");
|
2010
|
-
}
|
2011
|
-
};
|
2012
|
-
|
2013
|
-
/**
|
2014
|
-
* Utility function to generate stealth address
|
2015
|
-
* @param {string} sharedSecret - The shared secret
|
2016
|
-
* @param {string} spendingPublicKey - The spending public key
|
2017
|
-
* @returns {Object} The stealth address and private key
|
2018
|
-
*/
|
2019
|
-
function deriveStealthAddress(sharedSecret, spendingPublicKey) {
|
2020
|
-
try {
|
2021
|
-
// Convert shared secret to bytes
|
2022
|
-
const sharedSecretBytes = Buffer.from(sharedSecret, 'base64');
|
2023
|
-
|
2024
|
-
// Generate stealth private key using shared secret and spending public key
|
2025
|
-
const stealthPrivateKey = ethers.keccak256(
|
2026
|
-
ethers.concat([
|
2027
|
-
sharedSecretBytes,
|
2028
|
-
ethers.getBytes(spendingPublicKey)
|
2029
|
-
])
|
2030
|
-
);
|
2031
|
-
|
2032
|
-
// Create stealth wallet
|
2033
|
-
const stealthWallet = new ethers.Wallet(stealthPrivateKey);
|
2034
|
-
|
2035
|
-
console.log("Debug deriveStealthAddress:", {
|
2036
|
-
sharedSecretHex: ethers.hexlify(sharedSecretBytes),
|
2037
|
-
spendingPublicKey,
|
2038
|
-
stealthPrivateKey,
|
2039
|
-
stealthAddress: stealthWallet.address
|
2040
|
-
});
|
2041
|
-
|
2042
|
-
return {
|
2043
|
-
stealthPrivateKey,
|
2044
|
-
stealthAddress: stealthWallet.address,
|
2045
|
-
wallet: stealthWallet
|
2046
|
-
};
|
2047
|
-
} catch (error) {
|
2048
|
-
console.error("Error in deriveStealthAddress:", error);
|
2049
|
-
throw error;
|
2050
|
-
}
|
2051
|
-
}
|
2052
|
-
|
2053
|
-
// =============================================
|
2054
|
-
// BASIC GUN-ETH CHAIN METHODS
|
2055
|
-
// =============================================
|
2056
|
-
|
2057
|
-
// Set the message to sign
|
2058
|
-
Gun.chain.MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;
|
2059
|
-
|
2060
|
-
/**
|
2061
|
-
* Sets standalone configuration for Gun.
|
2062
|
-
* @param {string} newRpcUrl - The new RPC URL.
|
2063
|
-
* @param {string} newPrivateKey - The new private key.
|
2064
|
-
* @returns {Gun} The Gun instance for chaining.
|
2065
|
-
*/
|
2066
|
-
Gun.chain.setSigner = function (newRpcUrl, newPrivateKey) {
|
2067
|
-
rpcUrl = newRpcUrl;
|
2068
|
-
privateKey = newPrivateKey;
|
2069
|
-
console.log("Standalone configuration set");
|
2070
|
-
return this;
|
2071
|
-
};
|
2072
|
-
|
2073
|
-
Gun.chain.getSigner = getSigner();
|
2074
|
-
|
2075
|
-
/**
|
2076
|
-
* Verifies an Ethereum signature.
|
2077
|
-
* @param {string} message - The original message that was signed.
|
2078
|
-
* @param {string} signature - The signature to verify.
|
2079
|
-
* @returns {Promise<string|null>} The recovered address or null if verification fails.
|
2080
|
-
*/
|
2081
|
-
Gun.chain.verifySignature = async function (message, signature) {
|
2082
|
-
try {
|
2083
|
-
const recoveredAddress = ethers.verifyMessage(message, signature);
|
2084
|
-
return recoveredAddress;
|
2085
|
-
} catch (error) {
|
2086
|
-
console.error("Error verifying signature:", error);
|
2087
|
-
return null;
|
2088
|
-
}
|
2089
|
-
};
|
2090
|
-
|
2091
|
-
/**
|
2092
|
-
* Generates a password from a signature.
|
2093
|
-
* @param {string} signature - The signature to derive the password from.
|
2094
|
-
* @returns {string|null} The generated password or null if generation fails.
|
2095
|
-
*/
|
2096
|
-
Gun.chain.generatePassword = function (signature) {
|
2097
|
-
return generatePassword(signature);
|
2098
|
-
};
|
2099
|
-
|
2100
|
-
/**
|
2101
|
-
* Creates an Ethereum signature for a given message.
|
2102
|
-
* @param {string} message - The message to sign.
|
2103
|
-
* @returns {Promise<string|null>} The signature or null if signing fails.
|
2104
|
-
*/
|
2105
|
-
Gun.chain.createSignature = async function (message) {
|
2106
|
-
try {
|
2107
|
-
// Check if message matches MESSAGE_TO_SIGN
|
2108
|
-
if (message !== MESSAGE_TO_SIGN) {
|
2109
|
-
throw new Error("Invalid message, valid message is: " + MESSAGE_TO_SIGN);
|
2110
|
-
}
|
2111
|
-
const signer = await getSigner();
|
2112
|
-
const signature = await signer.signMessage(message);
|
2113
|
-
console.log("Signature created:", signature);
|
2114
|
-
return signature;
|
2115
|
-
} catch (error) {
|
2116
|
-
console.error("Error creating signature:", error);
|
2117
|
-
return null;
|
2118
|
-
}
|
2119
|
-
};
|
2120
|
-
|
2121
|
-
// =============================================
|
2122
|
-
// KEY PAIR MANAGEMENT
|
2123
|
-
// =============================================
|
2124
|
-
/**
|
2125
|
-
* Creates and stores an encrypted key pair for a given address.
|
2126
|
-
* @param {string} address - The Ethereum address to associate with the key pair.
|
2127
|
-
* @param {string} signature - The signature to use for encryption.
|
2128
|
-
* @returns {Promise<void>}
|
2129
|
-
*/
|
2130
|
-
Gun.chain.createAndStoreEncryptedPair = async function (address, signature) {
|
2131
|
-
try {
|
2132
|
-
const gun = this;
|
2133
|
-
const pair = await SEA.pair();
|
2134
|
-
const v_pair = await SEA.pair();
|
2135
|
-
const s_pair = await SEA.pair();
|
2136
|
-
const password = generatePassword(signature);
|
2137
|
-
|
2138
|
-
// Save original SEA pairs
|
2139
|
-
const encryptedPair = await SEA.encrypt(JSON.stringify(pair), password);
|
2140
|
-
const encryptedV_pair = await SEA.encrypt(JSON.stringify(v_pair), password);
|
2141
|
-
const encryptedS_pair = await SEA.encrypt(JSON.stringify(s_pair), password);
|
2142
|
-
|
2143
|
-
// Convert only to get Ethereum addresses
|
2144
|
-
const viewingAccount = gunToEthAccount(v_pair.priv);
|
2145
|
-
const spendingAccount = gunToEthAccount(s_pair.priv);
|
2146
|
-
|
2147
|
-
gun.get("gun-eth").get("users").get(address).put({
|
2148
|
-
pair: encryptedPair,
|
2149
|
-
v_pair: encryptedV_pair,
|
2150
|
-
s_pair: encryptedS_pair,
|
2151
|
-
publicKeys: {
|
2152
|
-
viewingPublicKey: v_pair.epub, // Use SEA encryption public key
|
2153
|
-
viewingPublicKey: v_pair.epub, // Use SEA encryption public key
|
2154
|
-
spendingPublicKey: spendingAccount.publicKey, // Use Ethereum address
|
2155
|
-
ethViewingAddress: viewingAccount.publicKey // Also save Ethereum address
|
2156
|
-
}
|
2157
|
-
});
|
2158
|
-
|
2159
|
-
console.log("Encrypted pairs and public keys stored for:", address);
|
2160
|
-
} catch (error) {
|
2161
|
-
console.error("Error creating and storing encrypted pair:", error);
|
2162
|
-
throw error;
|
2163
|
-
}
|
2164
|
-
};
|
2165
|
-
|
2166
|
-
/**
|
2167
|
-
* Retrieves and decrypts a stored key pair for a given address.
|
2168
|
-
* @param {string} address - The Ethereum address associated with the key pair.
|
2169
|
-
* @param {string} signature - The signature to use for decryption.
|
2170
|
-
* @returns {Promise<Object|null>} The decrypted key pair or null if retrieval fails.
|
2171
|
-
*/
|
2172
|
-
Gun.chain.getAndDecryptPair = async function (address, signature) {
|
2173
|
-
try {
|
2174
|
-
const gun = this;
|
2175
|
-
const encryptedData = await gun
|
2176
|
-
.get("gun-eth")
|
2177
|
-
.get("users")
|
2178
|
-
.get(address)
|
2179
|
-
.get("pair")
|
2180
|
-
.then();
|
2181
|
-
if (!encryptedData) {
|
2182
|
-
throw new Error("No encrypted data found for this address");
|
2183
|
-
}
|
2184
|
-
const password = generatePassword(signature);
|
2185
|
-
const decryptedPair = await SEA.decrypt(encryptedData, password);
|
2186
|
-
console.log(decryptedPair);
|
2187
|
-
return decryptedPair;
|
2188
|
-
} catch (error) {
|
2189
|
-
console.error("Error retrieving and decrypting pair:", error);
|
2190
|
-
return null;
|
2191
|
-
}
|
2192
|
-
};
|
2193
|
-
|
2194
|
-
// =============================================
|
2195
|
-
// PROOF OF INTEGRITY
|
2196
|
-
// =============================================
|
2197
|
-
/**
|
2198
|
-
* Proof of Integrity
|
2199
|
-
* @param {string} chain - The blockchain to use (e.g., "optimismSepolia").
|
2200
|
-
* @param {string} nodeId - The ID of the node to verify or write.
|
2201
|
-
* @param {Object} data - The data to write (if writing).
|
2202
|
-
* @param {Function} callback - Callback function to handle the result.
|
2203
|
-
* @returns {Gun} The Gun instance for chaining.
|
2204
|
-
*/
|
2205
|
-
Gun.chain.proof = function (chain, nodeId, data, callback) {
|
2206
|
-
console.log("Proof plugin called with:", { chain, nodeId, data });
|
2207
|
-
|
2208
|
-
if (typeof callback !== "function") {
|
2209
|
-
console.error("Callback must be a function");
|
2210
|
-
return this;
|
2211
|
-
}
|
2212
|
-
|
2213
|
-
try {
|
2214
|
-
// Se siamo in localhost e in development, usa automaticamente la chain locale
|
2215
|
-
const targetChain = isLocalEnvironment() ? 'localhost' : chain;
|
2216
|
-
const chainConfig = getAddressesForChain(targetChain);
|
2217
|
-
|
2218
|
-
console.log(`Using ${targetChain} configuration:`, chainConfig);
|
2219
|
-
|
2220
|
-
// Usa gli indirizzi dalla configurazione
|
2221
|
-
const contract = new ethers.Contract(
|
2222
|
-
chainConfig.PROOF_OF_INTEGRITY_ADDRESS,
|
2223
|
-
PROOF_OF_INTEGRITY_ABI,
|
2224
|
-
signer
|
2225
|
-
);
|
2226
|
-
|
2227
|
-
// Funzione per verificare on-chain
|
2228
|
-
const verifyOnChain = async (nodeId, contentHash) => {
|
2229
|
-
console.log("Verifying on chain:", { nodeId, contentHash });
|
2230
|
-
const signer = await getSigner();
|
2231
|
-
const contract = new ethers.Contract(
|
2232
|
-
PROOF_CONTRACT_ADDRESS,
|
2233
|
-
PROOF_OF_INTEGRITY_ABI,
|
2234
|
-
signer
|
2235
|
-
);
|
2236
|
-
const [isValid, timestamp, updater] = await contract.verifyData(
|
2237
|
-
ethers.toUtf8Bytes(nodeId),
|
2238
|
-
contentHash
|
2239
|
-
);
|
2240
|
-
console.log("Verification result:", { isValid, timestamp, updater });
|
2241
|
-
return { isValid, timestamp, updater };
|
2242
|
-
};
|
2243
|
-
|
2244
|
-
// Funzione per scrivere on-chain
|
2245
|
-
const writeOnChain = async (nodeId, contentHash) => {
|
2246
|
-
console.log("Writing on chain:", { nodeId, contentHash });
|
2247
|
-
const signer = await getSigner();
|
2248
|
-
const contract = new ethers.Contract(
|
2249
|
-
PROOF_CONTRACT_ADDRESS,
|
2250
|
-
PROOF_OF_INTEGRITY_ABI,
|
2251
|
-
signer
|
2252
|
-
);
|
2253
|
-
const tx = await contract.updateData(
|
2254
|
-
ethers.toUtf8Bytes(nodeId),
|
2255
|
-
contentHash
|
2256
|
-
);
|
2257
|
-
console.log("Transaction sent:", tx.hash);
|
2258
|
-
const receipt = await tx.wait();
|
2259
|
-
console.log("Transaction confirmed:", receipt);
|
2260
|
-
return tx;
|
2261
|
-
};
|
2262
|
-
|
2263
|
-
// Funzione per ottenere l'ultimo record
|
2264
|
-
const getLatestRecord = async (nodeId) => {
|
2265
|
-
const signer = await getSigner();
|
2266
|
-
const contract = new ethers.Contract(
|
2267
|
-
PROOF_CONTRACT_ADDRESS,
|
2268
|
-
PROOF_OF_INTEGRITY_ABI,
|
2269
|
-
signer
|
2270
|
-
);
|
2271
|
-
const [contentHash, timestamp, updater] = await contract.getLatestRecord(
|
2272
|
-
ethers.toUtf8Bytes(nodeId)
|
2273
|
-
);
|
2274
|
-
console.log("Latest record from blockchain:", {
|
2275
|
-
nodeId,
|
2276
|
-
contentHash,
|
2277
|
-
timestamp,
|
2278
|
-
updater,
|
2279
|
-
});
|
2280
|
-
return { contentHash, timestamp, updater };
|
2281
|
-
};
|
2282
|
-
|
2283
|
-
|
2284
|
-
if (nodeId && !data) {
|
2285
|
-
// Case 1: User passes only node
|
2286
|
-
gun.get(nodeId).once(async (existingData) => {
|
2287
|
-
if (!existingData) {
|
2288
|
-
if (callback) callback({ err: "Node not found in GunDB" });
|
2289
|
-
return;
|
2290
|
-
}
|
2291
|
-
|
2292
|
-
console.log("existingData", existingData);
|
2293
|
-
|
2294
|
-
// Use stored contentHash instead of recalculating
|
2295
|
-
const contentHash = existingData._contentHash;
|
2296
|
-
console.log("contentHash", contentHash);
|
2297
|
-
|
2298
|
-
if (!contentHash) {
|
2299
|
-
if (callback) callback({ err: "No content hash found for this node" });
|
2300
|
-
return;
|
2301
|
-
}
|
2302
|
-
|
2303
|
-
try {
|
2304
|
-
const { isValid, timestamp, updater } = await verifyOnChain(
|
2305
|
-
nodeId,
|
2306
|
-
contentHash
|
2307
|
-
);
|
2308
|
-
const latestRecord = await getLatestRecord(nodeId);
|
2309
|
-
|
2310
|
-
if (isValid) {
|
2311
|
-
if (callback)
|
2312
|
-
callback({
|
2313
|
-
ok: true,
|
2314
|
-
message: "Data verified on blockchain",
|
2315
|
-
timestamp,
|
2316
|
-
updater,
|
2317
|
-
latestRecord,
|
2318
|
-
});
|
2319
|
-
} else {
|
2320
|
-
if (callback)
|
2321
|
-
callback({
|
2322
|
-
ok: false,
|
2323
|
-
message: "Data not verified on blockchain",
|
2324
|
-
latestRecord,
|
2325
|
-
});
|
2326
|
-
}
|
2327
|
-
} catch (error) {
|
2328
|
-
if (callback) callback({ err: error.message });
|
2329
|
-
}
|
2330
|
-
});
|
2331
|
-
} else if (data && !nodeId) {
|
2332
|
-
// Case 2: User passes only text (data)
|
2333
|
-
const newNodeId = generateRandomId();
|
2334
|
-
const dataString = JSON.stringify(data);
|
2335
|
-
const contentHash = ethers.keccak256(ethers.toUtf8Bytes(dataString));
|
2336
|
-
|
2337
|
-
gun
|
2338
|
-
.get(newNodeId)
|
2339
|
-
.put({ ...data, _contentHash: contentHash }, async (ack) => {
|
2340
|
-
console.log("ack", ack);
|
2341
|
-
if (ack.err) {
|
2342
|
-
if (callback) callback({ err: "Error saving data to GunDB" });
|
2343
|
-
return;
|
2344
|
-
}
|
2345
|
-
|
2346
|
-
try {
|
2347
|
-
const tx = await writeOnChain(newNodeId, contentHash);
|
2348
|
-
if (callback)
|
2349
|
-
callback({
|
2350
|
-
ok: true,
|
2351
|
-
message: "Data written to GunDB and blockchain",
|
2352
|
-
nodeId: newNodeId,
|
2353
|
-
txHash: tx.hash,
|
2354
|
-
});
|
2355
|
-
} catch (error) {
|
2356
|
-
if (callback) callback({ err: error.message });
|
2357
|
-
}
|
2358
|
-
});
|
2359
|
-
} else {
|
2360
|
-
if (callback)
|
2361
|
-
callback({
|
2362
|
-
err: "Invalid input. Provide either nodeId or data, not both.",
|
2363
|
-
});
|
2364
|
-
}
|
2365
|
-
|
2366
|
-
return gun;
|
2367
|
-
} catch (error) {
|
2368
|
-
callback({ err: error.message });
|
2369
|
-
return this;
|
2370
|
-
}
|
2371
|
-
};
|
2372
|
-
|
2373
|
-
// =============================================
|
2374
|
-
// STEALTH ADDRESS CORE FUNCTIONS
|
2375
|
-
// =============================================
|
2376
|
-
/**
|
2377
|
-
* Converts a Gun private key to an Ethereum account.
|
2378
|
-
* @param {string} gunPrivateKey - The Gun private key in base64url format.
|
2379
|
-
* @returns {Object} An object containing the Ethereum account and public key.
|
2380
|
-
*/
|
2381
|
-
Gun.chain.gunToEthAccount = function (gunPrivateKey) {
|
2382
|
-
return gunToEthAccount(gunPrivateKey);
|
2383
|
-
};
|
2384
|
-
|
2385
|
-
/**
|
2386
|
-
* Generate a stealth key and related key pairs
|
2387
|
-
* @param {string} recipientAddress - The recipient's Ethereum address
|
2388
|
-
* @param {string} signature - The sender's signature to access their keys
|
2389
|
-
* @returns {Promise<Object>} Object containing stealth addresses and keys
|
2390
|
-
*/
|
2391
|
-
Gun.chain.generateStealthAddress = async function (recipientAddress, signature) {
|
2392
|
-
try {
|
2393
|
-
const gun = this;
|
2394
|
-
|
2395
|
-
// Get recipient's public keys
|
2396
|
-
const recipientData = await gun
|
2397
|
-
.get("gun-eth")
|
2398
|
-
.get("users")
|
2399
|
-
.get(recipientAddress)
|
2400
|
-
.get("publicKeys")
|
2401
|
-
.then();
|
2402
|
-
|
2403
|
-
if (!recipientData || !recipientData.viewingPublicKey || !recipientData.spendingPublicKey) {
|
2404
|
-
throw new Error("Recipient's public keys not found");
|
2405
|
-
}
|
2406
|
-
|
2407
|
-
// Get sender's keys
|
2408
|
-
const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);
|
2409
|
-
const password = generatePassword(signature);
|
2410
|
-
|
2411
|
-
const senderData = await gun
|
2412
|
-
.get("gun-eth")
|
2413
|
-
.get("users")
|
2414
|
-
.get(senderAddress)
|
2415
|
-
.then();
|
2416
|
-
|
2417
|
-
if (!senderData || !senderData.s_pair) {
|
2418
|
-
throw new Error("Sender's keys not found");
|
2419
|
-
}
|
2420
|
-
|
2421
|
-
// Decrypt sender's spending pair
|
2422
|
-
let spendingKeyPair;
|
2423
|
-
try {
|
2424
|
-
const decryptedData = await SEA.decrypt(senderData.s_pair, password);
|
2425
|
-
spendingKeyPair = typeof decryptedData === 'string' ?
|
2426
|
-
JSON.parse(decryptedData) :
|
2427
|
-
decryptedData;
|
2428
|
-
} catch (error) {
|
2429
|
-
console.error("Error decrypting spending pair:", error);
|
2430
|
-
throw new Error("Unable to decrypt spending pair");
|
2431
|
-
}
|
2432
|
-
|
2433
|
-
// Generate shared secret using SEA ECDH with encryption public key
|
2434
|
-
const sharedSecret = await SEA.secret(recipientData.viewingPublicKey, spendingKeyPair);
|
2435
|
-
|
2436
|
-
if (!sharedSecret) {
|
2437
|
-
throw new Error("Unable to generate shared secret");
|
2438
|
-
}
|
2439
|
-
|
2440
|
-
console.log("Generate shared secret:", sharedSecret);
|
2441
|
-
|
2442
|
-
const { stealthAddress } = deriveStealthAddress(
|
2443
|
-
sharedSecret,
|
2444
|
-
recipientData.spendingPublicKey
|
2445
|
-
);
|
2446
|
-
|
2447
|
-
return {
|
2448
|
-
stealthAddress,
|
2449
|
-
senderPublicKey: spendingKeyPair.epub, // Use encryption public key
|
2450
|
-
spendingPublicKey: recipientData.spendingPublicKey
|
2451
|
-
};
|
2452
|
-
|
2453
|
-
} catch (error) {
|
2454
|
-
console.error("Error generating stealth address:", error);
|
2455
|
-
throw error;
|
2456
|
-
}
|
2457
|
-
};
|
2458
|
-
|
2459
|
-
/**
|
2460
|
-
* Publish public keys needed to receive stealth payments
|
2461
|
-
* @param {string} signature - The signature to authenticate the user
|
2462
|
-
* @returns {Promise<void>}
|
2463
|
-
*/
|
2464
|
-
Gun.chain.publishStealthKeys = async function (signature) {
|
2465
|
-
try {
|
2466
|
-
const gun = this;
|
2467
|
-
const address = await this.verifySignature(MESSAGE_TO_SIGN, signature);
|
2468
|
-
const password = generatePassword(signature);
|
2469
|
-
|
2470
|
-
// Get encrypted key pairs
|
2471
|
-
const encryptedData = await gun
|
2472
|
-
.get("gun-eth")
|
2473
|
-
.get("users")
|
2474
|
-
.get(address)
|
2475
|
-
.then();
|
2476
|
-
|
2477
|
-
if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {
|
2478
|
-
throw new Error("Keys not found");
|
2479
|
-
}
|
2480
|
-
|
2481
|
-
// Decrypt viewing and spending pairs
|
2482
|
-
const viewingKeyPair = JSON.parse(
|
2483
|
-
await SEA.decrypt(encryptedData.v_pair, password)
|
2484
|
-
);
|
2485
|
-
const spendingKeyPair = JSON.parse(
|
2486
|
-
await SEA.decrypt(encryptedData.s_pair, password)
|
2487
|
-
);
|
2488
|
-
|
2489
|
-
const viewingAccount = gunToEthAccount(viewingKeyPair.priv);
|
2490
|
-
const spendingAccount = gunToEthAccount(spendingKeyPair.priv);
|
2491
|
-
|
2492
|
-
// Publish only public keys
|
2493
|
-
gun.get("gun-eth").get("users").get(address).get("publicKeys").put({
|
2494
|
-
viewingPublicKey: viewingAccount.publicKey,
|
2495
|
-
spendingPublicKey: spendingAccount.publicKey,
|
2496
|
-
});
|
2497
|
-
|
2498
|
-
console.log("Stealth public keys published successfully");
|
2499
|
-
} catch (error) {
|
2500
|
-
console.error("Error publishing stealth keys:", error);
|
2501
|
-
throw error;
|
2502
|
-
}
|
2503
|
-
};
|
2504
|
-
|
2505
|
-
// =============================================
|
2506
|
-
// STEALTH PAYMENT FUNCTIONS
|
2507
|
-
// =============================================
|
2508
|
-
/**
|
2509
|
-
* Recover funds from a stealth address
|
2510
|
-
* @param {string} stealthAddress - The stealth address to recover funds from
|
2511
|
-
* @param {string} senderPublicKey - The sender's public key used to generate the address
|
2512
|
-
* @param {string} signature - The signature to decrypt private keys
|
2513
|
-
* @returns {Promise<Object>} Object containing wallet to access funds
|
2514
|
-
*/
|
2515
|
-
Gun.chain.recoverStealthFunds = async function (
|
2516
|
-
stealthAddress,
|
2517
|
-
senderPublicKey,
|
2518
|
-
signature,
|
2519
|
-
spendingPublicKey
|
2520
|
-
) {
|
2521
|
-
try {
|
2522
|
-
const gun = this;
|
2523
|
-
const password = generatePassword(signature);
|
2524
|
-
|
2525
|
-
// Get own key pairs
|
2526
|
-
const myAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);
|
2527
|
-
const encryptedData = await gun
|
2528
|
-
.get("gun-eth")
|
2529
|
-
.get("users")
|
2530
|
-
.get(myAddress)
|
2531
|
-
.then();
|
2532
|
-
|
2533
|
-
if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {
|
2534
|
-
throw new Error("Keys not found");
|
2535
|
-
}
|
2536
|
-
|
2537
|
-
// Decrypt viewing and spending pairs
|
2538
|
-
let viewingKeyPair;
|
2539
|
-
try {
|
2540
|
-
const decryptedViewingData = await SEA.decrypt(encryptedData.v_pair, password);
|
2541
|
-
viewingKeyPair = typeof decryptedViewingData === 'string' ?
|
2542
|
-
JSON.parse(decryptedViewingData) :
|
2543
|
-
decryptedViewingData;
|
2544
|
-
} catch (error) {
|
2545
|
-
console.error("Error decrypting keys:", error);
|
2546
|
-
throw new Error("Unable to decrypt keys");
|
2547
|
-
}
|
2548
|
-
|
2549
|
-
// Generate shared secret using SEA ECDH
|
2550
|
-
const sharedSecret = await SEA.secret(senderPublicKey, viewingKeyPair);
|
2551
|
-
|
2552
|
-
if (!sharedSecret) {
|
2553
|
-
throw new Error("Unable to generate shared secret");
|
2554
|
-
}
|
2555
|
-
|
2556
|
-
console.log("Recover shared secret:", sharedSecret);
|
2557
|
-
|
2558
|
-
const { wallet, stealthAddress: recoveredAddress } = deriveStealthAddress(
|
2559
|
-
sharedSecret,
|
2560
|
-
spendingPublicKey
|
2561
|
-
);
|
2562
|
-
|
2563
|
-
// Verify address matches
|
2564
|
-
if (recoveredAddress.toLowerCase() !== stealthAddress.toLowerCase()) {
|
2565
|
-
console.error("Mismatch:", {
|
2566
|
-
recovered: recoveredAddress,
|
2567
|
-
expected: stealthAddress,
|
2568
|
-
sharedSecret
|
2569
|
-
});
|
2570
|
-
throw new Error("Recovered stealth address does not match");
|
2571
|
-
}
|
2572
|
-
|
2573
|
-
return {
|
2574
|
-
wallet,
|
2575
|
-
address: recoveredAddress,
|
2576
|
-
};
|
2577
|
-
} catch (error) {
|
2578
|
-
console.error("Error recovering stealth funds:", error);
|
2579
|
-
throw error;
|
2580
|
-
}
|
2581
|
-
};
|
2582
|
-
|
2583
|
-
/**
|
2584
|
-
* Announce a stealth payment
|
2585
|
-
* @param {string} stealthAddress - The generated stealth address
|
2586
|
-
* @param {string} senderPublicKey - The sender's public key
|
2587
|
-
* @param {string} spendingPublicKey - The spending public key
|
2588
|
-
* @param {string} signature - The sender's signature
|
2589
|
-
* @returns {Promise<void>}
|
2590
|
-
*/
|
2591
|
-
Gun.chain.announceStealthPayment = async function (
|
2592
|
-
stealthAddress,
|
2593
|
-
senderPublicKey,
|
2594
|
-
spendingPublicKey,
|
2595
|
-
signature,
|
2596
|
-
options = { onChain: false, chain: 'optimismSepolia' }
|
2597
|
-
) {
|
2598
|
-
try {
|
2599
|
-
const gun = this;
|
2600
|
-
const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);
|
2601
|
-
|
2602
|
-
if (options.onChain) {
|
2603
|
-
// On-chain announcement
|
2604
|
-
const signer = await getSigner();
|
2605
|
-
const chainAddresses = getAddressesForChain(options.chain);
|
2606
|
-
const contractAddress = chainAddresses.STEALTH_ANNOUNCER_ADDRESS;
|
2607
|
-
|
2608
|
-
console.log("Using contract address:", contractAddress);
|
2609
|
-
|
2610
|
-
const contract = new ethers.Contract(
|
2611
|
-
contractAddress,
|
2612
|
-
STEALTH_ANNOUNCER_ABI,
|
2613
|
-
signer
|
2614
|
-
);
|
2615
|
-
|
2616
|
-
// Get dev fee from contract
|
2617
|
-
const devFee = await contract.devFee();
|
2618
|
-
console.log("Dev fee:", devFee.toString());
|
2619
|
-
|
2620
|
-
// Call contract
|
2621
|
-
const tx = await contract.announcePayment(
|
2622
|
-
senderPublicKey,
|
2623
|
-
spendingPublicKey,
|
2624
|
-
stealthAddress,
|
2625
|
-
{ value: devFee }
|
2626
|
-
);
|
2627
|
-
|
2628
|
-
console.log("Transaction sent:", tx.hash);
|
2629
|
-
const receipt = await tx.wait();
|
2630
|
-
console.log("Transaction confirmed:", receipt.hash);
|
2631
|
-
|
2632
|
-
console.log("Stealth payment announced on-chain (dev fee paid)");
|
2633
|
-
} else {
|
2634
|
-
// Off-chain announcement (GunDB)
|
2635
|
-
gun
|
2636
|
-
.get("gun-eth")
|
2637
|
-
.get("stealth-payments")
|
2638
|
-
.set({
|
2639
|
-
stealthAddress,
|
2640
|
-
senderAddress,
|
2641
|
-
senderPublicKey,
|
2642
|
-
spendingPublicKey,
|
2643
|
-
timestamp: Date.now(),
|
2644
|
-
});
|
2645
|
-
console.log("Stealth payment announced off-chain");
|
2646
|
-
}
|
2647
|
-
} catch (error) {
|
2648
|
-
console.error("Error announcing stealth payment:", error);
|
2649
|
-
console.error("Error details:", error.stack);
|
2650
|
-
throw error;
|
2651
|
-
}
|
2652
|
-
};
|
2653
|
-
|
2654
|
-
/**
|
2655
|
-
* Get all stealth payments for an address
|
2656
|
-
* @param {string} signature - The signature to authenticate the user
|
2657
|
-
* @returns {Promise<Array>} List of stealth payments
|
2658
|
-
*/
|
2659
|
-
Gun.chain.getStealthPayments = async function (signature, options = { source: 'both' }) {
|
2660
|
-
try {
|
2661
|
-
const payments = [];
|
2662
|
-
|
2663
|
-
if (options.source === 'onChain' || options.source === 'both') {
|
2664
|
-
// Get on-chain payments
|
2665
|
-
const signer = await getSigner();
|
2666
|
-
const contractAddress = process.env.NODE_ENV === 'development'
|
2667
|
-
? LOCAL_CONFIG.STEALTH_ANNOUNCER_ADDRESS
|
2668
|
-
: STEALTH_ANNOUNCER_ADDRESS;
|
2669
|
-
|
2670
|
-
const contract = new ethers.Contract(
|
2671
|
-
contractAddress,
|
2672
|
-
STEALTH_ANNOUNCER_ABI,
|
2673
|
-
signer
|
2674
|
-
);
|
2675
|
-
|
2676
|
-
try {
|
2677
|
-
// Get total number of announcements
|
2678
|
-
const totalAnnouncements = await contract.getAnnouncementsCount();
|
2679
|
-
const totalCount = Number(totalAnnouncements.toString());
|
2680
|
-
console.log("Total on-chain announcements:", totalCount);
|
2681
|
-
|
2682
|
-
if (totalCount > 0) {
|
2683
|
-
// Get announcements in batches of 100
|
2684
|
-
const batchSize = 100;
|
2685
|
-
const lastIndex = totalCount - 1;
|
2686
|
-
|
2687
|
-
for(let i = 0; i <= lastIndex; i += batchSize) {
|
2688
|
-
const toIndex = Math.min(i + batchSize - 1, lastIndex);
|
2689
|
-
const batch = await contract.getAnnouncementsInRange(i, toIndex);
|
2690
|
-
|
2691
|
-
// For each announcement, try to decrypt
|
2692
|
-
for(const announcement of batch) {
|
2693
|
-
try {
|
2694
|
-
// Verify announcement is valid
|
2695
|
-
if (!announcement || !announcement.stealthAddress ||
|
2696
|
-
!announcement.senderPublicKey || !announcement.spendingPublicKey) {
|
2697
|
-
console.log("Invalid announcement:", announcement);
|
2698
|
-
continue;
|
2699
|
-
}
|
2700
|
-
|
2701
|
-
// Try to recover funds to verify if announcement is for us
|
2702
|
-
const recoveredWallet = await this.recoverStealthFunds(
|
2703
|
-
announcement.stealthAddress,
|
2704
|
-
announcement.senderPublicKey,
|
2705
|
-
signature,
|
2706
|
-
announcement.spendingPublicKey
|
2707
|
-
);
|
2708
|
-
|
2709
|
-
// If no errors thrown, announcement is for us
|
2710
|
-
payments.push({
|
2711
|
-
stealthAddress: announcement.stealthAddress,
|
2712
|
-
senderPublicKey: announcement.senderPublicKey,
|
2713
|
-
spendingPublicKey: announcement.spendingPublicKey,
|
2714
|
-
timestamp: Number(announcement.timestamp),
|
2715
|
-
source: 'onChain',
|
2716
|
-
wallet: recoveredWallet
|
2717
|
-
});
|
2718
|
-
|
2719
|
-
} catch (e) {
|
2720
|
-
// Not for us, continue
|
2721
|
-
console.log(`Announcement not for us: ${announcement.stealthAddress}`);
|
2722
|
-
continue;
|
2723
|
-
}
|
2724
|
-
}
|
2725
|
-
}
|
2726
|
-
}
|
2727
|
-
} catch (error) {
|
2728
|
-
console.error("Error retrieving on-chain announcements:", error);
|
2729
|
-
}
|
2730
|
-
}
|
2731
|
-
|
2732
|
-
if (options.source === 'offChain' || options.source === 'both') {
|
2733
|
-
// Get off-chain payments
|
2734
|
-
const gun = this;
|
2735
|
-
const offChainPayments = await new Promise((resolve) => {
|
2736
|
-
const p = [];
|
2737
|
-
gun
|
2738
|
-
.get("gun-eth")
|
2739
|
-
.get("stealth-payments")
|
2740
|
-
.get(recipientAddress)
|
2741
|
-
.map()
|
2742
|
-
.once((payment, id) => {
|
2743
|
-
if (payment?.stealthAddress) {
|
2744
|
-
p.push({ ...payment, id, source: 'offChain' });
|
2745
|
-
}
|
2746
|
-
});
|
2747
|
-
setTimeout(() => resolve(p), 2000);
|
2748
|
-
});
|
2749
|
-
|
2750
|
-
payments.push(...offChainPayments);
|
2751
|
-
}
|
2752
|
-
|
2753
|
-
console.log(`Found ${payments.length} stealth payments`);
|
2754
|
-
return payments;
|
2755
|
-
} catch (error) {
|
2756
|
-
console.error("Error retrieving stealth payments:", error);
|
2757
|
-
throw error;
|
2758
|
-
}
|
2759
|
-
};
|
2760
|
-
|
2761
|
-
/**
|
2762
|
-
* Clean up old stealth payments
|
2763
|
-
* @param {string} recipientAddress - The recipient's address
|
2764
|
-
* @returns {Promise<void>}
|
2765
|
-
*/
|
2766
|
-
Gun.chain.cleanStealthPayments = async function(recipientAddress) {
|
2767
|
-
try {
|
2768
|
-
const gun = this;
|
2769
|
-
const payments = await gun
|
2770
|
-
.get("gun-eth")
|
2771
|
-
.get("stealth-payments")
|
2772
|
-
.get(recipientAddress)
|
2773
|
-
.map()
|
2774
|
-
.once()
|
2775
|
-
.then();
|
2776
|
-
|
2777
|
-
// Remove empty or invalid nodes
|
2778
|
-
if (payments) {
|
2779
|
-
Object.keys(payments).forEach(async (key) => {
|
2780
|
-
const payment = payments[key];
|
2781
|
-
if (!payment || !payment.stealthAddress || !payment.senderPublicKey || !payment.spendingPublicKey) {
|
2782
|
-
await gun
|
2783
|
-
.get("gun-eth")
|
2784
|
-
.get("stealth-payments")
|
2785
|
-
.get(recipientAddress)
|
2786
|
-
.get(key)
|
2787
|
-
.put(null);
|
2788
|
-
}
|
2789
|
-
});
|
2790
|
-
}
|
2791
|
-
} catch (error) {
|
2792
|
-
console.error("Error cleaning stealth payments:", error);
|
2793
|
-
}
|
2794
|
-
};
|
2795
|
-
|
2796
|
-
// =============================================
|
2797
|
-
// EXPORTS
|
2798
|
-
// =============================================
|
2799
|
-
|
2800
|
-
// Crea una classe GunEth che contiene tutti i metodi e le utility
|
2801
|
-
class GunEth {
|
2802
|
-
// Static utility methods
|
2803
|
-
static generateRandomId = generateRandomId;
|
2804
|
-
static generatePassword = generatePassword;
|
2805
|
-
static gunToEthAccount = gunToEthAccount;
|
2806
|
-
static getSigner = getSigner;
|
2807
|
-
static deriveStealthAddress = deriveStealthAddress;
|
2808
|
-
|
2809
|
-
// Chain methods
|
2810
|
-
static chainMethods = {
|
2811
|
-
setSigner: Gun.chain.setSigner,
|
2812
|
-
getSigner: Gun.chain.getSigner,
|
2813
|
-
verifySignature: Gun.chain.verifySignature,
|
2814
|
-
generatePassword: Gun.chain.generatePassword,
|
2815
|
-
createSignature: Gun.chain.createSignature,
|
2816
|
-
createAndStoreEncryptedPair: Gun.chain.createAndStoreEncryptedPair,
|
2817
|
-
getAndDecryptPair: Gun.chain.getAndDecryptPair,
|
2818
|
-
proof: Gun.chain.proof,
|
2819
|
-
gunToEthAccount: Gun.chain.gunToEthAccount,
|
2820
|
-
generateStealthAddress: Gun.chain.generateStealthAddress,
|
2821
|
-
publishStealthKeys: Gun.chain.publishStealthKeys,
|
2822
|
-
recoverStealthFunds: Gun.chain.recoverStealthFunds,
|
2823
|
-
announceStealthPayment: Gun.chain.announceStealthPayment,
|
2824
|
-
getStealthPayments: Gun.chain.getStealthPayments,
|
2825
|
-
cleanStealthPayments: Gun.chain.cleanStealthPayments
|
2826
|
-
};
|
2827
|
-
|
2828
|
-
// Constants
|
2829
|
-
static MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;
|
2830
|
-
static PROOF_CONTRACT_ADDRESS = PROOF_CONTRACT_ADDRESS;
|
2831
|
-
static LOCAL_CONFIG = LOCAL_CONFIG;
|
2832
|
-
}
|
2833
|
-
|
2834
|
-
export { GunEth, MESSAGE_TO_SIGN, deriveStealthAddress, generatePassword, generateRandomId, getSigner, gunToEthAccount };
|
2835
|
-
//# sourceMappingURL=gun-eth.esm.js.map
|