forked from blockchain/unused-My-Wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sharedcoin.js
2298 lines (1743 loc) · 87.6 KB
/
sharedcoin.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var SharedCoin = new function() {
var SharedCoin = this;
var DonationPercentMin = 0.5;
var DonationPercentMax = 1.0;
var AjaxTimeout = 120000;
var AjaxRetry = 3;
var LastSignatureSubmitTime = 0;
var MinTimeBetweenSubmits = 120000;
var options = {};
var version = 6;
var URL;
var extra_private_keys = {};
var seed_prefix = 'sharedcoin-seed-v2:';
var seed_prefix_v1 = 'sharedcoin-seed:';
var ProgressCallbacksPerOffer = 7;
//Count the number of keys in an object
function nKeys(obj) {
var size = 0, key;
for (key in obj) {
size++;
}
return size;
};
//Indent a number of lines for debug printing
function indentString(str) {
var lines = str.split('\n');
var joined = '';
for (var i in lines) {
joined += ' ' + lines[i] + '\n';
}
return joined;
}
//Divide a big integer into n random parts
function splitBigInt(value, n) {
if (n == 0) throw 'Invalid N';
var values = [];
var total = BigInteger.ZERO;
for (var i = 0; i < n; ++i) {
values[i] = value.multiply(BigInteger.valueOf(Math.round(Math.random()*100)));
total = total.add(values[i]);
}
var mod = total.divide(value);
total = BigInteger.ZERO;
for (var i = 0; i < n; ++i) {
values[i] = values[i].divide(mod);
total = total.add(values[i]);
}
var randIndex = Math.ceil(Math.random()*values.length)-1;
//Add any remainder to a random index
values[randIndex] = values[randIndex].add(value.subtract(total));
return values;
}
//Count the number of digits in a big int
function getDigitCount(number) {
var factor = Math.log(2) / Math.log(10);
var digitCount = Math.ceil((factor * number.bitLength() + 1));
if (BigInteger.valueOf(10).pow(BigInteger.valueOf(digitCount - 1)).compareTo(number) > 0) {
return digitCount - 1;
}
return digitCount;
}
//Return random value between x & y
function randomLong(x, y) {
return Math.round(x + (Math.random() * (y - x)));
}
//Round one big integer and add the remainder to the second returning an array
function randomRound(val1, val2, minSignificant) {
var total = val1.add(val2);
var digitCount = getDigitCount(val1);
minSignificant = Math.min(digitCount-1, minSignificant);
var modifier = BigInteger.valueOf(Math.pow(10, randomLong(1, digitCount - 1)));
var val1Rounded = val1.divide(modifier).multiply(modifier);
var roundedRemainder = total.subtract(val1Rounded);
return [val1Rounded, roundedRemainder];
}
//Duration in milliseconds to minutes and hours (used for estimation time)
function timeToMinutesSeconds(millis) {
var oneHour = 3600 * 1000;
var oneMinute = 60 * 1000;
var hours = Math.floor(millis / oneHour);
var minutes = Math.floor((millis - (hours * oneHour)) / oneMinute);
var seconds = Math.round((millis - (hours * oneHour) - (minutes * oneMinute)) / 1000);
var str = '';
if (minutes > 0) str += minutes + ' minutes';
if (seconds > 0) str += (str.length > 0 ? ' ' : '') + seconds + ' seconds';
return str;
}
/*globals jQuery, window */
(function($) {
$.retryAjax = function (ajaxParams) {
var errorCallback;
ajaxParams.tryCount = (!ajaxParams.tryCount) ? 0 : ajaxParams.tryCount;
ajaxParams.retryLimit = (!ajaxParams.retryLimit) ? 2 : ajaxParams.retryLimit;
ajaxParams.suppressErrors = true;
if (ajaxParams.error) {
errorCallback = ajaxParams.error;
delete ajaxParams.error;
} else {
errorCallback = function () {
};
}
ajaxParams.complete = function (jqXHR, textStatus) {
if ($.inArray(textStatus, ['timeout', 'abort', 'error']) > -1) {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
// fire error handling on the last try
if (this.tryCount === this.retryLimit) {
this.error = errorCallback;
delete this.suppressErrors;
}
(function(self) {
//try again after delay
setTimeout(function() {
$.ajax(self);
}, 5000);
})(this);
return true;
}
return true;
}
};
$.ajax(ajaxParams);
};
}(jQuery));
Bitcoin.Transaction.deserialize = function (buffer)
{
function readVarInt(buff) {
var tbyte, tbytes;
tbyte = buff.splice(0, 1)[0];
if (tbyte < 0xfd) {
tbytes = [tbyte];
} else if (tbyte == 0xfd) {
tbytes = buff.splice(0, 2);
} else if (tbyte == 0xfe) {
tbytes = buff.splice(0, 4);
} else {
tbytes = buff.splice(0, 8);
}
return BigInteger.fromByteArrayUnsigned(tbytes);
}
function readUInt32(buffer) {
return new BigInteger(buffer.splice(0, 4).reverse()).intValue();
}
var tx = new Bitcoin.Transaction();
tx.version = readUInt32(buffer);
var txInCount = readVarInt(buffer).intValue();
for (var i = 0; i < txInCount; i++) {
var outPointHashBytes = buffer.splice(0,32);
var outPointHash = Crypto.util.bytesToBase64(outPointHashBytes);
var outPointIndex = readUInt32(buffer);
var scriptLength = readVarInt(buffer).intValue();
var script = new Bitcoin.Script(buffer.splice(0, scriptLength));
var sequence = readUInt32(buffer);
var input = new Bitcoin.TransactionIn({outpoint : {hash: outPointHash, index : outPointIndex}, script: script, sequence: sequence});
tx.ins.push(input);
}
var txOutCount = readVarInt(buffer).intValue();
for (var i = 0; i < txOutCount; i++) {
var valueBytes = buffer.splice(0, 8);
var scriptLength = readVarInt(buffer).intValue();
var script = new Bitcoin.Script(buffer.splice(0, scriptLength));
var out = new Bitcoin.TransactionOut({script : script, value : valueBytes})
tx.outs.push(out);
}
tx.lock_time = readUInt32(buffer);
return tx;
};
function divideUniformlyRandomly(sum, n)
{
var nums = [];
var upperbound = Math.round(sum * 1.0 / n);
var offset = Math.round(0.5 * upperbound);
var cursum = 0;
for (var i = 0; i < n; i++)
{
var rand = Math.floor((Math.random() * upperbound) + offset);
if (cursum + rand > sum || i == n - 1)
{
rand = sum - cursum;
}
cursum += rand;
nums[i] = rand;
if (cursum == sum)
{
break;
}
}
return nums;
}
var reviewModal = {
show : function (plan, success, error) {
var self = this;
self.modal = $('#sharedcoin-review-modal');
self.success = success;
self.error = error;
self.modal.modal({
keyboard: false,
backdrop: "static",
show: true
});
self.modal.find('.btn.btn-primary').unbind().click(function() {
self.success();
self.hide();
});
self.modal.find('.btn.btn-secondary').unbind().click(function() {
self.error();
self.hide();
});
self.setPlan(plan);
},
hide : function() {
if (this.modal) {
this.modal.modal('hide');
this.success = null;
this.error = null;
}
},
setPlan : function(plan) {
if (this.modal) {
this.modal.find('.estimated-time').text(timeToMinutesSeconds(plan.getEstimatedTimeLeft()));
this.modal.find('.n-repetitions').text(plan.offers.length);
this.modal.find('.network-fees').text(formatBTC(plan.offers.length * SharedCoin.getMinimumFee()));
this.modal.find('.total-fee').text(formatBTC(plan.calculateTotalFee().toString()));
var to = this.modal.find('.to');
to.empty();
for (var address in plan.to_addresses) {
var value = plan.to_addresses[address];
to.append(address + ' ('+ formatBTC(value.toString()) +')<br/>');
}
}
}
};
var progressModal = {
show : function () {
var self = this;
self.modal = $('#sharedcoin-modal');
self.modal.modal({
keyboard: false,
backdrop: "static",
show: true
});
self.modal.find('.btn.btn-secondary').unbind().click(function() {
self.hide();
});
},
setEstimatedTime : function(estimatedTime) {
if (this.modal) {
var span = this.modal.find('.estimated-time');
var subHeader = this.modal.find('h3').find('small');
if (estimatedTime <= 0) {
span.hide();
subHeader.hide();
} else {
subHeader.show();
span.show();
span.text(timeToMinutesSeconds(estimatedTime));
}
}
},
setProgressError : function() {
if (this.modal) {
var progress = this.modal.find('.progress');
progress.addClass('progress-danger');
progress.removeClass('progress-success');
progress.removeClass('progress-info');
}
},
setProgressSuccess : function() {
if (this.modal) {
var progress = this.modal.find('.progress');
progress.addClass('progress-success');
progress.removeClass('progress-danger');
progress.removeClass('progress-info');
}
},
setProgressInfo : function() {
if (this.modal) {
var progress = this.modal.find('.progress');
progress.addClass('progress-info');
progress.removeClass('progress-success');
progress.removeClass('progress-danger');
}
},
setProgress : function(stage, max_stage) {
if (this.modal) {
var width = (stage / max_stage) * 100;
var progress = this.modal.find('.progress');
if (stage >= max_stage) {
progress.removeClass('active');
} else {
progress.addClass('active');
}
progress.children().css('width', width + '%');
}
},
setAddressAndAmount : function(address, amount) {
if (this.modal) {
this.modal.find('.total_value').text(formatBTC(amount));
this.modal.find('.address').text(address);
}
},
hide : function() {
if (this.modal) {
this.modal.modal('hide');
}
},
disableCancel : function() {
if (this.modal) {
this.modal.find('.alert-warning').show();
this.modal.find('.alert-error').hide();
this.modal.find('.btn.btn-secondary').prop('disabled', true);
}
},
enableCancel : function() {
if (this.modal) {
this.modal.find('.alert-error').show();
this.modal.find('.alert-warning').hide();
this.modal.find('.btn.btn-secondary').prop('disabled', false);
}
}
};
this.newProposal = function() {
return {
_pollForCompleted : function(success, error) {
var self = this;
console.log('Offer._pollForCompleted()');
MyWallet.setLoadingText('Waiting For Other Participants To Sign');
$.retryAjax({
dataType: 'json',
type: "POST",
url: URL,
timeout: AjaxTimeout,
retryLimit: 4,
data : {method : 'poll_for_proposal_completed', format : 'json', proposal_id : self.proposal_id},
success: function (obj) {
success(obj);
},
error : function(e) {
error(e.responseText);
}
});
},
pollForCompleted : function(success, error) {
var self = this;
var handleObj = function(obj) {
if (obj.status == 'waiting') {
self._pollForCompleted(handleObj, error)
} else if (obj.status == 'not_found') {
error('Proposal ID Not Found');
} else if (obj.status == 'complete'){
success(obj.tx_hash, obj.tx)
} else {
error('Unknown status ' + obj.status)
}
}
self._pollForCompleted(handleObj, error)
}
}
};
this.newOffer = function() {
return {
offered_outpoints : [], //The outpoints we want to offer
request_outputs : [], //The outputs we want in return
offer_id : 0, //A unique ID for this offer (set by server)
fee_percent : 0, //The Offer fee percentage
wait_time : 60000,
time_submitted : 0,
toString : function() {
var self = this;
var str = '---- OFFER ----\n';
str += 'ID ' + self.offer_id + '\n';
str += 'Fee Percent ' + self.fee_percent + '\n';
str += 'Actual Fee ' + self.calculateFee() + '\n';
str += 'Wait Time ' + self.wait_time + '\n';
str += 'Inputs [\n';
for (var i in self.offered_outpoints) {
var offered_outpoint = self.offered_outpoints[i];
if (offered_outpoint.hash == null) {
var script = new Script(Crypto.util.hexToBytes(offered_outpoint.script));
var addresses = [];
script.extractAddresses(addresses);
str += ' Awaiting Connection (Address ' + addresses[0]+ ')';
} else {
str += ' Hash : ' + offered_outpoint.hash;
}
str += ' Value : ' + offered_outpoint.value;
str += '\n';
}
str += ']\n';
str += 'Outputs [\n';
for (var i in self.request_outputs) {
var request_output = self.request_outputs[i];
var script = new Script(Crypto.util.hexToBytes(request_output.script));
var addresses = [];
script.extractAddresses(addresses);
str += ' Address : ' + addresses[0] + ' Value : ' + request_output.value;
if (request_output.exclude_from_fee)
str += ' Change Output';
str += '\n';
}
str += ']\n';
str += '---- END OFFER ----';
return str;
},
submit : function(success, error, complete) {
var self = this;
self.time_submitted = new Date().getTime();
MyWallet.setLoadingText('Submitting Offer');
$.retryAjax({
dataType: 'json',
type: "POST",
url: URL,
timeout: AjaxTimeout,
retryLimit: AjaxRetry,
data : {
method : 'submit_offer',
fee_percent : self.fee_percent,
format : 'json',
token : SharedCoin.getToken(),
offer : JSON.stringify(self),
offer_max_age : self.wait_time
},
success: function (obj) {
if (obj.status == 'complete') {
complete(obj.tx_hash, obj.tx);
} else if (!obj.offer_id) {
error('Null offer_id returned');
} else {
self.offer_id = obj.offer_id;
success();
}
},
error : function(e) {
error(e.responseText);
}
});
},
_pollForProposalID : function(success, error) {
var self = this;
console.log('Offer._pollForProposalID()');
MyWallet.setLoadingText('Waiting For Outputs To Be Joined');
$.retryAjax({
dataType: 'json',
type: "POST",
url: URL,
timeout: AjaxTimeout,
retryLimit: AjaxRetry,
data : {method : 'get_offer_id', format : 'json', offer_id : self.offer_id},
success: function (obj) {
success(obj);
},
error : function(e) {
error(e.responseText);
}
});
},
calculateFee : function() {
var self = this;
var totalValueInput= BigInteger.ZERO;
for (var i in self.offered_outpoints) {
totalValueInput = totalValueInput.add(BigInteger.valueOf(self.offered_outpoints[i].value));
}
var totalValueOutput = BigInteger.ZERO;
for (var i in self.request_outputs) {
totalValueOutput = totalValueOutput.add(BigInteger.valueOf(self.request_outputs[i].value));
}
return totalValueInput.subtract(totalValueOutput);
},
pollForProposalID : function(success, error) {
var self = this;
var handleObj = function(obj) {
if (obj.status == 'waiting') {
self._pollForProposalID(handleObj, error)
} else if (obj.status == 'not_found') {
error('Offer ID Not Found');
} else if (obj.status == 'active_proposal'){
success(obj.proposal_id)
} else {
error('Unknown status ' + obj.status)
}
}
self._pollForProposalID(handleObj, error)
},
getProposal : function(proposal_id, success, error, complete) {
var self = this;
console.log('SharedCoin.getProposal()');
MyWallet.setLoadingText('Fetching Proposal');
$.retryAjax({
dataType: 'json',
type: "POST",
url: URL,
timeout: AjaxTimeout,
retryLimit: AjaxRetry,
data : {method : 'get_proposal_id', format : 'json', offer_id : self.offer_id, proposal_id : proposal_id},
success: function (obj) {
var proposal = SharedCoin.newProposal();
var clone = jQuery.extend(proposal, obj);
if (clone.status == 'not_found') {
error('Proposal or Offer ID Not Found');
} else if (clone.status == 'complete') {
complete(clone.tx_hash, clone.tx);
} else if (clone.status == 'signatures_needed') {
success(clone);
} else if (clone.status == 'waiting') {
self.getProposal(proposal_id, success, error, complete)
} else {
error('Unknown get_proposal_id status')
}
},
error : function(e) {
error(e.responseText);
}
});
},
isOutpointOneWeOffered : function (input) {
var self = this;
var base64Hash = input.outpoint.hash;
var hexHash = Crypto.util.bytesToHex(Crypto.util.base64ToBytes(base64Hash).reverse());
var index = input.outpoint.index;
for (var ii in self.offered_outpoints) {
var request_outpoint = self.offered_outpoints[ii];
if (request_outpoint.hash.toString() == hexHash.toString() && request_outpoint.index.toString() == index.toString()) {
return true;
}
}
return false;
},
isOutputOneWeRequested : function (output) {
var self = this;
var array = output.value.slice(0);
array.reverse();
var scriptHex = Crypto.util.bytesToHex(output.script.buffer);
var value = new BigInteger(array);
for (var ii in self.request_outputs) {
var request_output = self.request_outputs[ii];
if (request_output.script.toString() == scriptHex.toString() && value.toString() == request_output.value.toString()) {
return true;
}
}
return false;
},
isOutputChange : function (output) {
var self = this;
var array = output.value.slice(0);
array.reverse();
var scriptHex = Crypto.util.bytesToHex(output.script.buffer);
var value = new BigInteger(array);
for (var ii in self.request_outputs) {
var request_output = self.request_outputs[ii];
if (request_output.script.toString() == scriptHex.toString() && value.toString() == request_output.value.toString()) {
return request_output.exclude_from_fee;
}
}
return false;
},
determineOutputsToOfferNextStage : function(tx_hash, tx_hex, success, error) {
//Determine which outputs from a transaction are available for spending in the next stage
var self = this;
try {
var decodedTx = Crypto.util.hexToBytes(tx_hex);
var tx = Bitcoin.Transaction.deserialize(decodedTx);
var outpoints_to_offer_next_stage = [];
for (var i = 0; i < tx.outs.length; ++i) {
var output = tx.outs[i];
if (self.isOutputOneWeRequested(output)) {
if (!self.isOutputChange(output)) {
var array = output.value.slice(0);
array.reverse();
var value = new BigInteger(array);
outpoints_to_offer_next_stage.push({
script : Crypto.util.bytesToHex(output.script.buffer),
hash : tx_hash,
index : parseInt(i),
value : value.toString()
});
}
}
}
success(outpoints_to_offer_next_stage);
} catch (e) {
error(e);
}
},
checkProposal : function(proposal, success, error) {
console.log('Offer.checkProposal()');
var self = this;
try {
if (proposal.tx == null) {
throw 'Proposal Transaction Is Null';
}
var decodedTx = Crypto.util.hexToBytes(proposal.tx);
var tx = Bitcoin.Transaction.deserialize(decodedTx);
if (tx == null) {
throw 'Error deserializing transaction';
}
var output_matches = 0;
for (var i = 0; i < tx.outs.length; ++i) {
var output = tx.outs[i];
if (self.isOutputOneWeRequested(output)) {
++output_matches;
}
}
if (output_matches < self.request_outputs.length) {
throw 'Could not find all our requested outputs (' + output_matches + ' < ' + self.request_outputs.length + ')';
}
var input_matches = 0;
for (var i = 0; i < proposal.signature_requests.length; ++i) {
var tx_index = proposal.signature_requests[i].tx_input_index;
if (self.isOutpointOneWeOffered(tx.ins[tx_index])) {
++input_matches;
}
}
if (self.offered_outpoints.length != input_matches) {
throw 'Could not find all our offered outpoints ('+self.offered_outpoints.length + ' != ' + input_matches + ')';
}
success(tx);
} catch (e) {
error(e);
}
},
signNormal : function(tx, connected_scripts, success, error) {
console.log('Offer.signNormal()');
var index = 0;
var signatures = [];
var signOne = function() {
setTimeout(function() {
try {
var connected_script = connected_scripts[index];
if (connected_script == null) {
throw 'Null connected script';
}
var signed_script = signInput(tx, connected_script.tx_input_index, connected_script.priv_to_use, connected_script, SIGHASH_ALL);
if (signed_script) {
index++;
signatures.push({tx_input_index : connected_script.tx_input_index, input_script : Crypto.util.bytesToHex(signed_script.buffer), offer_outpoint_index : connected_script.offer_outpoint_index});
if (index == connected_scripts.length) {
success(signatures);
} else {
signOne(); //Sign The Next One
}
} else {
throw 'Unknown error signing transaction';
}
} catch (e) {
error(e);
}
}, 1);
};
signOne();
},
submitInputScripts : function(proposal, input_scripts, success, error, complete) {
console.log('Offer.submitInputScripts()');
var self = this;
MyWallet.setLoadingText('Submitting Signatures');
LastSignatureSubmitTime = new Date().getTime();
$.retryAjax({
dataType: 'json',
type: "POST",
url: URL,
timeout: AjaxTimeout,
retryLimit: AjaxRetry,
data : {method : 'submit_signatures', format : 'json', input_scripts : JSON.stringify(input_scripts), offer_id : self.offer_id, proposal_id : proposal.proposal_id},
success: function (obj) {
if (obj.status == 'not_found') {
error('Proposal Expired or Not Found');
} else if (obj.status == 'verification_failed') {
error('Signature Verification Failed');
} else if (obj.status == 'complete') {
complete(obj.tx_hash, obj.tx);
} else if (obj.status == 'signatures_accepted') {
success('Signatures Accepted');
} else {
error('Unknown status ' + obj.status);
}
},
error : function(e) {
error(e.responseText);
}
});
},
signInputs : function(proposal, tx, success, error) {
console.log('Offer.signInputs()');
var self = this;
try {
var tmp_cache = {};
var connected_scripts = [];
for (var i = 0; i < proposal.signature_requests.length; ++i) {
var request = proposal.signature_requests[i];
var connected_script = new Bitcoin.Script(Crypto.util.hexToBytes(request.connected_script));
if (connected_script == null) {
throw 'signInputs() Connected script is null';
}
connected_script.tx_input_index = request.tx_input_index;
connected_script.offer_outpoint_index = request.offer_outpoint_index;
var pubKeyHash = connected_script.simpleOutPubKeyHash();
var inputAddress = new Bitcoin.Address(pubKeyHash).toString();
//Find the matching private key
if (tmp_cache[inputAddress]) {
connected_script.priv_to_use = tmp_cache[inputAddress];
} else if (extra_private_keys[inputAddress]) {
connected_script.priv_to_use = Bitcoin.Base58.decode(extra_private_keys[inputAddress]);
} else if (MyWallet.addressExists(inputAddress) && !MyWallet.isWatchOnly(inputAddress)) {
connected_script.priv_to_use = MyWallet.decodePK(MyWallet.getPrivateKey(inputAddress));
}
if (connected_script.priv_to_use == null) {
throw 'Private key not found';
} else {
//Performance optimization
//Only Decode the key once sand save it in a temporary cache
tmp_cache[inputAddress] = connected_script.priv_to_use;
}
connected_scripts.push(connected_script);
}
self.signNormal(tx, connected_scripts, function(signatures) {
success(signatures);
}, function(e) {
error(e);
});
} catch (e) {
error(e);
}
}
};
};
this.generateAddressAndKeyFromCustomSeed = function(seed, n) {
var hash = Crypto.SHA256(seed + n, {asBytes: true});
var key = new Bitcoin.ECKey(hash);
if (seed.indexOf(seed_prefix) == 0) {
//current seed version
var address = key.getBitcoinAddressCompressed();
} else {
//Assume seed v1
if (hash[0] % 2 == 0) {
var address = key.getBitcoinAddress();
} else {
var address = key.getBitcoinAddressCompressed();
}
}
return {address: address, key: key};
}
this.generateAddressFromCustomSeed = function(seed, n) {
var key_container = this.generateAddressAndKeyFromCustomSeed(seed, n);
extra_private_keys[key_container.address.toString()] = Bitcoin.Base58.encode(key_container.key.priv);
return key_container.address;
}
this.newPlan = function() {
return {
offers : [], //Array of Offers for each stage
c_stage : 0, //The current stage
address_seed : null, //The address seed for recovery
address_seen_n : 0, //The current seed index
generated_addresses : [], //Change Addresses we have generated
fee_percent_each_repetition : [], //The fee_percent per iteration
fee_each_repetition : [], //The fee in satoshi per iteration
to_addresses : {}, //Record to addresses from form for debugging
generateAddressFromSeed : function() {
if (this.address_seed == null) {
MyWallet._seed();
var array = new Array(18);
new SecureRandom().nextBytes(array);
this.address_seed = Crypto.util.bytesToHex(array);
MyWallet.addAdditionalSeeds(seed_prefix + this.address_seed);
}
if (this.address_seen_n >= 100) {
throw 'Generating An Address Seed Greater than 100 Index. Please file an issue on Shared Coin github';
}
var address = SharedCoin.generateAddressFromCustomSeed(seed_prefix + this.address_seed, this.address_seen_n);
this.address_seen_n++;
return address;
},
sanityCheck : function(success, error) {
try {
var self = this;
if (self.offers.length == 0)
throw 'No Offers';
var networkFee = BigInteger.valueOf(SharedCoin.getMinimumFee());
var to_addresses_copy = $.extend({}, self.to_addresses);
for (var i in self.offers) {
var offer = self.offers[i];
var valueInput = BigInteger.ZERO;
var valueOutput = BigInteger.ZERO;
if (offer.offered_outpoints.length > SharedCoin.getMaximumOfferNumberOfInputs())
throw 'Number of inputs greater than maximum';
for (var ii in offer.offered_outpoints) {
var offered_outpoint = offer.offered_outpoints[ii];
if (offered_outpoint.value < SharedCoin.getMinimumInputValue())
throw 'Input value less than minimum';
if (offered_outpoint.value > SharedCoin.getMaximumInputValue())
throw 'Input value greater than maximum';