forked from byteball/ocore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wallet_defined_by_addresses.js
491 lines (455 loc) · 20.6 KB
/
wallet_defined_by_addresses.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*jslint node: true */
"use strict";
var async = require('async');
var db = require('./db.js');
var constants = require('./constants.js');
var conf = require('./conf.js');
var composer = require('./composer.js');
var objectHash = require('./object_hash.js');
var _ = require('lodash');
var network = require('./network.js');
var device = require('./device.js');
var walletGeneral = require('./wallet_general.js');
var eventBus = require('./event_bus.js');
var Definition = require("./definition.js");
var ValidationUtils = require("./validation_utils.js");
var indivisibleAsset = require('./indivisible_asset.js');
var divisibleAsset = require('./divisible_asset.js');
var MAX_INT32 = Math.pow(2, 31) - 1;
// unused
function sendOfferToCreateNewSharedAddress(device_address, arrAddressDefinitionTemplate){
device.sendMessageToDevice(device_address, "create_new_shared_address", {address_definition_template: arrAddressDefinitionTemplate});
}
// called from UI (unused)
function sendApprovalOfNewSharedAddress(device_address, address_definition_template_chash, address, assocDeviceAddressesByRelativeSigningPaths){
device.sendMessageToDevice(device_address, "approve_new_shared_address", {
address_definition_template_chash: address_definition_template_chash,
address: address,
device_addresses_by_relative_signing_paths: assocDeviceAddressesByRelativeSigningPaths
});
}
// called from UI (unused)
function sendRejectionOfNewSharedAddress(device_address, address_definition_template_chash){
device.sendMessageToDevice(device_address, "reject_new_shared_address", {
address_definition_template_chash: address_definition_template_chash
});
}
function sendNewSharedAddress(device_address, address, arrDefinition, assocSignersByPath, bForwarded){
device.sendMessageToDevice(device_address, "new_shared_address", {
address: address, definition: arrDefinition, signers: assocSignersByPath, forwarded: bForwarded
});
}
// called from UI (unused)
// my address is not filled explicitly, it is specified as variable in the template like external addresses
// assocMyDeviceAddressesByRelativeSigningPaths points to my device addresses that hold the actual signing keys
function createNewSharedAddressByTemplate(arrAddressDefinitionTemplate, my_address, assocMyDeviceAddressesByRelativeSigningPaths){
validateAddressDefinitionTemplate(arrAddressDefinitionTemplate, device.getMyDeviceAddress(), function(err, assocMemberDeviceAddressesBySigningPaths){
if(err) {
throw Error(err);
}
// assocMemberDeviceAddressesBySigningPaths are keyed by paths from root to member addresses (not all the way to signing keys)
var arrMemberSigningPaths = Object.keys(assocMemberDeviceAddressesBySigningPaths);
var address_definition_template_chash = objectHash.getChash160(arrAddressDefinitionTemplate);
db.query(
"INSERT INTO pending_shared_addresses (definition_template_chash, definition_template) VALUES(?,?)",
[address_definition_template_chash, JSON.stringify(arrAddressDefinitionTemplate)],
function(){
async.eachSeries(
arrMemberSigningPaths,
function(signing_path, cb){
var device_address = assocMemberDeviceAddressesBySigningPaths[signing_path];
var fields = "definition_template_chash, device_address, signing_path";
var values = "?,?,?";
var arrParams = [address_definition_template_chash, device_address, signing_path];
if (device_address === device.getMyDeviceAddress()){
fields += ", address, device_addresses_by_relative_signing_paths, approval_date";
values += ",?,?,"+db.getNow();
arrParams.push(my_address, JSON.stringify(assocMyDeviceAddressesByRelativeSigningPaths));
}
db.query("INSERT INTO pending_shared_address_signing_paths ("+fields+") VALUES("+values+")", arrParams, function(){
cb();
});
},
function(){
var arrMemberDeviceAddresses = _.uniq(_.values(assocMemberDeviceAddressesBySigningPaths));
arrMemberDeviceAddresses.forEach(function(device_address){
if (device_address !== device.getMyDeviceAddress())
sendOfferToCreateNewSharedAddress(device_address, arrAddressDefinitionTemplate);
})
}
);
}
);
});
}
// unused
// received approval from co-signer address
function approvePendingSharedAddress(address_definition_template_chash, from_address, address, assocDeviceAddressesByRelativeSigningPaths){
db.query( // may update several rows if the device is referenced multiple times from the definition template
"UPDATE pending_shared_address_signing_paths SET address=?, device_addresses_by_relative_signing_paths=?, approval_date="+db.getNow()+" \n\
WHERE definition_template_chash=? AND device_address=?",
[address, JSON.stringify(assocDeviceAddressesByRelativeSigningPaths), address_definition_template_chash, from_address],
function(){
// check if this is the last required approval
db.query(
"SELECT device_address, signing_path, address, device_addresses_by_relative_signing_paths \n\
FROM pending_shared_address_signing_paths \n\
WHERE definition_template_chash=?",
[address_definition_template_chash],
function(rows){
if (rows.length === 0) // another device rejected the address at the same time
return;
if (rows.some(function(row){ return !row.address; })) // some devices haven't approved yet
return;
// all approvals received
var params = {};
rows.forEach(function(row){ // the same device_address can be mentioned in several rows
params['address@'+row.device_address] = row.address;
});
db.query(
"SELECT definition_template FROM pending_shared_addresses WHERE definition_template_chash=?",
[address_definition_template_chash],
function(templ_rows){
if (templ_rows.length !== 1)
throw Error("template not found");
var arrAddressDefinitionTemplate = JSON.parse(templ_rows[0].definition_template);
var arrDefinition = Definition.replaceInTemplate(arrAddressDefinitionTemplate, params);
var shared_address = objectHash.getChash160(arrDefinition);
db.query(
"INSERT INTO shared_addresses (shared_address, definition) VALUES (?,?)",
[shared_address, JSON.stringify(arrDefinition)],
function(){
var arrQueries = [];
var assocSignersByPath = {};
rows.forEach(function(row){
var assocDeviceAddressesByRelativeSigningPaths = JSON.parse(row.device_addresses_by_relative_signing_paths);
for (var member_signing_path in assocDeviceAddressesByRelativeSigningPaths){
var signing_device_address = assocDeviceAddressesByRelativeSigningPaths[member_signing_path];
// this is full signing path, from root of shared address (not from root of member address)
var full_signing_path = row.signing_path + member_signing_path.substring(1);
// note that we are inserting row.device_address (the device we requested approval from), not signing_device_address
// (the actual signer), because signing_device_address might not be our correspondent. When we need to sign, we'll
// send unsigned unit to row.device_address and it'll forward the request to signing_device_address (subject to
// row.device_address being online)
db.addQuery(arrQueries,
"INSERT INTO shared_address_signing_paths \n\
(shared_address, address, signing_path, member_signing_path, device_address) VALUES(?,?,?,?,?)",
[shared_address, row.address, full_signing_path, member_signing_path, row.device_address]);
assocSignersByPath[full_signing_path] = {
device_address: row.device_address,
address: row.address,
member_signing_path: member_signing_path
};
}
});
async.series(arrQueries, function(){
deletePendingSharedAddress(address_definition_template_chash);
// notify all other member-devices about the new shared address they are a part of
rows.forEach(function(row){
if (row.device_address !== device.getMyDeviceAddress())
sendNewSharedAddress(row.device_address, shared_address, arrDefinition, assocSignersByPath);
});
forwardNewSharedAddressToCosignersOfMyMemberAddresses(shared_address, arrDefinition, assocSignersByPath);
if (conf.bLight)
network.addLightWatchedAddress(shared_address);
});
}
);
}
);
}
);
}
);
}
// unused
function deletePendingSharedAddress(address_definition_template_chash){
db.query("DELETE FROM pending_shared_address_signing_paths WHERE definition_template_chash=?", [address_definition_template_chash], function(){
db.query("DELETE FROM pending_shared_addresses WHERE definition_template_chash=?", [address_definition_template_chash], function(){});
});
}
// called from network after the initiator collects approvals from all members of the address and then sends the completed address to all members
// member_signing_path is now deprecated and unused
// shared_address_signing_paths.signing_path is now path to member-address, not full path to a signing key
function addNewSharedAddress(address, arrDefinition, assocSignersByPath, bForwarded, onDone){
// network.addWatchedAddress(address);
db.query(
"INSERT "+db.getIgnore()+" INTO shared_addresses (shared_address, definition) VALUES (?,?)",
[address, JSON.stringify(arrDefinition)],
function(){
var arrQueries = [];
for (var signing_path in assocSignersByPath){
var signerInfo = assocSignersByPath[signing_path];
db.addQuery(arrQueries,
"INSERT "+db.getIgnore()+" INTO shared_address_signing_paths \n\
(shared_address, address, signing_path, member_signing_path, device_address) VALUES (?,?,?,?,?)",
[address, signerInfo.address, signing_path, signerInfo.member_signing_path, signerInfo.device_address]);
}
async.series(arrQueries, function(){
console.log('added new shared address '+address);
eventBus.emit("new_address-"+address);
if (conf.bLight)
network.addLightWatchedAddress(address);
if (!bForwarded)
forwardNewSharedAddressToCosignersOfMyMemberAddresses(address, arrDefinition, assocSignersByPath);
if (onDone)
onDone();
});
}
);
}
function includesMyDeviceAddress(assocSignersByPath){
for (var signing_path in assocSignersByPath){
var signerInfo = assocSignersByPath[signing_path];
if (signerInfo.device_address === device.getMyDeviceAddress())
return true;
}
return false;
}
// Checks if any of my payment addresses is mentioned.
// It is possible that my device address is not mentioned in the definition if I'm a member of multisig address, one of my cosigners is mentioned instead
function determineIfIncludesMe(assocSignersByPath, handleResult){
var assocMemberAddresses = {};
for (var signing_path in assocSignersByPath){
var signerInfo = assocSignersByPath[signing_path];
// if (signerInfo.device_address === device.getMyDeviceAddress())
if (signerInfo.address)
assocMemberAddresses[signerInfo.address] = true;
}
var arrMemberAddresses = Object.keys(assocMemberAddresses);
if (arrMemberAddresses.length === 0)
return handleResult("no member addresses?");
db.query(
"SELECT address FROM my_addresses WHERE address IN(?) UNION SELECT shared_address AS address FROM shared_addresses WHERE shared_address IN(?)",
[arrMemberAddresses, arrMemberAddresses],
function(rows){
// handleResult(rows.length === arrMyMemberAddresses.length ? null : "Some of my member addresses not found");
handleResult(rows.length > 0 ? null : "I am not a member of this shared address");
}
);
}
function forwardNewSharedAddressToCosignersOfMyMemberAddresses(address, arrDefinition, assocSignersByPath){
var assocMyMemberAddresses = {};
for (var signing_path in assocSignersByPath){
var signerInfo = assocSignersByPath[signing_path];
if (signerInfo.device_address === device.getMyDeviceAddress() && signerInfo.address)
assocMyMemberAddresses[signerInfo.address] = true;
}
var arrMyMemberAddresses = Object.keys(assocMyMemberAddresses);
if (arrMyMemberAddresses.length === 0)
throw Error("my member addresses not found");
db.query(
"SELECT DISTINCT device_address FROM my_addresses JOIN wallet_signing_paths USING(wallet) WHERE address IN(?) AND device_address!=?",
[arrMyMemberAddresses, device.getMyDeviceAddress()],
function(rows){
rows.forEach(function(row){
sendNewSharedAddress(row.device_address, address, arrDefinition, assocSignersByPath, true);
});
}
);
}
// {address: "BASE32", definition: [...], signers: {...}}
function handleNewSharedAddress(body, callbacks){
if (!ValidationUtils.isArrayOfLength(body.definition, 2))
return callbacks.ifError("invalid definition");
if (typeof body.signers !== "object" || Object.keys(body.signers).length === 0)
return callbacks.ifError("invalid signers");
if (body.address !== objectHash.getChash160(body.definition))
return callbacks.ifError("definition doesn't match its c-hash");
for (var signing_path in body.signers){
var signerInfo = body.signers[signing_path];
if (signerInfo.address && !ValidationUtils.isValidAddress(signerInfo.address))
return callbacks.ifError("invalid member address: "+signerInfo.address);
}
determineIfIncludesMe(body.signers, function(err){
if (err)
return callbacks.ifError(err);
validateAddressDefinition(body.definition, function(err){
if (err)
return callbacks.ifError(err);
addNewSharedAddress(body.address, body.definition, body.signers, body.forwarded, callbacks.ifOk);
});
});
}
function createNewSharedAddress(arrDefinition, assocSignersByPath, callbacks){
if (!includesMyDeviceAddress(assocSignersByPath))
return callbacks.ifError("my device address not mentioned");
var address = objectHash.getChash160(arrDefinition);
handleNewSharedAddress({address: address, definition: arrDefinition, signers: assocSignersByPath}, {
ifError: callbacks.ifError,
ifOk: function(){
// share the new address with all cosigners
var arrDeviceAddresses = [];
for (var signing_path in assocSignersByPath){
var signerInfo = assocSignersByPath[signing_path];
if (signerInfo.device_address !== device.getMyDeviceAddress() && arrDeviceAddresses.indexOf(signerInfo.device_address) === -1)
arrDeviceAddresses.push(signerInfo.device_address);
}
arrDeviceAddresses.forEach(function(device_address){
sendNewSharedAddress(device_address, address, arrDefinition, assocSignersByPath);
});
callbacks.ifOk(address);
}
});
}
function getMemberDeviceAddressesBySigningPaths(arrAddressDefinitionTemplate){
function evaluate(arr, path){
var op = arr[0];
var args = arr[1];
if (!args)
return;
switch (op){
case 'or':
case 'and':
for (var i=0; i<args.length; i++)
evaluate(args[i], path + '.' + i);
break;
case 'r of set':
if (!ValidationUtils.isNonemptyArray(args.set))
return;
for (var i=0; i<args.set.length; i++)
evaluate(args.set[i], path + '.' + i);
break;
case 'weighted and':
if (!ValidationUtils.isNonemptyArray(args.set))
return;
for (var i=0; i<args.set.length; i++)
evaluate(args.set[i].value, path + '.' + i);
break;
case 'address':
var address = args;
var prefix = '$address@';
if (!ValidationUtils.isNonemptyString(address) || address.substr(0, prefix.length) !== prefix)
return;
var device_address = address.substr(prefix.length);
assocMemberDeviceAddressesBySigningPaths[path] = device_address;
break;
case 'definition template':
throw Error(op+" not supported yet");
// all other ops cannot reference device address
}
}
var assocMemberDeviceAddressesBySigningPaths = {};
evaluate(arrAddressDefinitionTemplate, 'r');
return assocMemberDeviceAddressesBySigningPaths;
}
function validateAddressDefinitionTemplate(arrDefinitionTemplate, from_address, handleResult){
var assocMemberDeviceAddressesBySigningPaths = getMemberDeviceAddressesBySigningPaths(arrDefinitionTemplate);
var arrDeviceAddresses = _.uniq(_.values(assocMemberDeviceAddressesBySigningPaths));
if (arrDeviceAddresses.length < 2)
return handleResult("less than 2 member devices");
if (arrDeviceAddresses.indexOf(device.getMyDeviceAddress()) === - 1)
return handleResult("my device address not mentioned in the definition");
if (arrDeviceAddresses.indexOf(from_address) === - 1)
return handleResult("sender device address not mentioned in the definition");
var params = {};
// to fill the template for validation, assign my device address (without leading 0) to all member devices
// (we need just any valid address with a definition)
var fake_address = device.getMyDeviceAddress().substr(1);
arrDeviceAddresses.forEach(function(device_address){
params['address@'+device_address] = fake_address;
});
try{
var arrFakeDefinition = Definition.replaceInTemplate(arrDefinitionTemplate, params);
}
catch(e){
return handleResult(e.toString());
}
var objFakeUnit = {authors: [{address: fake_address, definition: ["sig", {pubkey: device.getMyDevicePubKey()}]}]};
var objFakeValidationState = {last_ball_mci: MAX_INT32};
Definition.validateDefinition(db, arrFakeDefinition, objFakeUnit, objFakeValidationState, false, function(err){
if (err)
return handleResult(err);
handleResult(null, assocMemberDeviceAddressesBySigningPaths);
});
}
// fix:
// 1. check that my address is referenced in the definition
function validateAddressDefinition(arrDefinition, handleResult){
var objFakeUnit = {authors: []};
var objFakeValidationState = {last_ball_mci: MAX_INT32, bAllowUnresolvedInnerDefinitions: true};
Definition.validateDefinition(db, arrDefinition, objFakeUnit, objFakeValidationState, false, function(err){
if (err)
return handleResult(err);
handleResult();
});
}
function forwardPrivateChainsToOtherMembersOfAddresses(arrChains, arrAddresses, conn, onSaved){
conn = conn || db;
conn.query(
"SELECT device_address FROM shared_address_signing_paths WHERE shared_address IN(?) AND device_address!=?",
[arrAddresses, device.getMyDeviceAddress()],
function(rows){
console.log("shared address devices: "+rows.length);
async.eachSeries(
rows,
function(row, cb){
console.log("forwarding to device "+row.device_address);
walletGeneral.sendPrivatePayments(row.device_address, arrChains, true, conn, cb);
},
function(){
if (onSaved)
onSaved();
}
);
}
);
}
/*
function readRequiredCosigners(shared_address, arrSigningDeviceAddresses, handleCosigners){
db.query(
"SELECT shared_address_signing_paths.address \n\
FROM shared_address_signing_paths \n\
LEFT JOIN unit_authors USING(address) \n\
WHERE shared_address=? AND device_address IN(?) AND unit_authors.address IS NULL",
[shared_address, arrSigningDeviceAddresses],
function(rows){
handleCosigners(rows.map(function(row){ return row.address; }));
}
);
}*/
function readSharedAddressDefinition(shared_address, handleDefinition){
db.query(
"SELECT definition, "+db.getUnixTimestamp("creation_date")+" AS creation_ts FROM shared_addresses WHERE shared_address=?",
[shared_address],
function(rows){
if (rows.length !== 1)
throw Error('shared definition not found '+shared_address);
var arrDefinition = JSON.parse(rows[0].definition);
handleDefinition(arrDefinition, rows[0].creation_ts);
}
);
}
function readSharedAddressCosigners(shared_address, handleCosigners){
db.query(
"SELECT DISTINCT device_address, name, "+db.getUnixTimestamp("shared_addresses.creation_date")+" AS creation_ts \n\
FROM shared_address_signing_paths \n\
JOIN correspondent_devices USING(device_address) \n\
JOIN shared_addresses USING(shared_address) \n\
WHERE shared_address=? AND device_address!=?",
[shared_address, device.getMyDeviceAddress()],
function(rows){
handleCosigners(rows);
}
);
}
function determineIfHasMerkle(shared_address, handleResult){
db.query(
"SELECT 1 FROM shared_address_signing_paths WHERE shared_address=? AND device_address=? AND address=''",
[shared_address, device.getMyDeviceAddress()],
function(rows){
handleResult(rows.length > 0);
}
);
}
exports.validateAddressDefinitionTemplate = validateAddressDefinitionTemplate;
exports.approvePendingSharedAddress = approvePendingSharedAddress;
exports.deletePendingSharedAddress = deletePendingSharedAddress;
exports.validateAddressDefinition = validateAddressDefinition;
exports.handleNewSharedAddress = handleNewSharedAddress;
exports.forwardPrivateChainsToOtherMembersOfAddresses = forwardPrivateChainsToOtherMembersOfAddresses;
exports.readSharedAddressCosigners = readSharedAddressCosigners;
exports.readSharedAddressDefinition = readSharedAddressDefinition;
exports.determineIfHasMerkle = determineIfHasMerkle;
exports.createNewSharedAddress = createNewSharedAddress;
exports.createNewSharedAddressByTemplate = createNewSharedAddressByTemplate;