forked from dsias/blockchain.info
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sharedcoin.js
1210 lines (928 loc) · 46.4 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 options = {};
var version = 3;
var URL = MyWallet.getSharedcoinEndpoint() + '?version=' + version;
var extra_private_keys = {};
var seed_prefix = 'sharedcoin-seed:';
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 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();
});
},
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');
$.ajax({
dataType: 'json',
type: "POST",
url: URL,
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)
} 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)
submit : function(success, error) {
var self = this;
MyWallet.setLoadingText('Submitting Offer');
$.ajax({
dataType: 'json',
type: "POST",
url: URL,
data : {method : 'submit_offer', format : 'json', token : SharedCoin.getToken(), offer : JSON.stringify(self)},
success: function (obj) {
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 Other Participants');
$.ajax({
dataType: 'json',
type: "POST",
url: URL,
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) {
var self = this;
console.log('SharedCoin.getProposal()');
MyWallet.setLoadingText('Fetching Proposal');
$.ajax({
dataType: 'json',
type: "POST",
url: URL,
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 {
success(clone);
}
},
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;
},
checkProposal : function(proposal, success, error) {
console.log('Offer.checkProposal()');
var self = this;
try {
if (proposal.tx == null) {
throw 'Proposal Transaction Is Null';
}
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;
};
var decodedTx = Crypto.util.hexToBytes(proposal.tx);
var tx = Bitcoin.Transaction.deserialize(decodedTx);
if (tx == null) {
throw 'Error deserializing transaction';
}
var outpoints_to_offer_next_stage = [];
var output_matches = 0;
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({hash : null, index : parseInt(i), value : value.toString()});
}
++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, outpoints_to_offer_next_stage);
} 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];
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) {
console.log('Offer.submitInputScripts()');
var self = this;
MyWallet.setLoadingText('Submitting Signatures');
$.ajax({
dataType: 'json',
type: "POST",
url: URL,
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')
error('Transaction Already Completed');
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));
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.generateAddressFromCustomSeed = function(seed, n) {
var hash = Crypto.SHA256(seed + n, {asBytes: true});
var key = new Bitcoin.ECKey(hash);
if (hash[0] % 2 == 0) {
var address = key.getBitcoinAddress();
} else {
var address = key.getBitcoinAddressCompressed();
}
extra_private_keys[address.toString()] = Bitcoin.Base58.encode(key.priv);
return address;
}
this.newPlan = function() {
return {
offers : [], //Array of Offers for each stage
n_stages : 0, //Total number of stages
address_seed : new SecureRandom().nextBytes(16),
address_seen_n : 0,
generateAddressFromSeed : function() {
if (this.address_seed == null) {
var array = [];
array.length = 18;
new SecureRandom().nextBytes(array);
this.address_seed = Crypto.util.bytesToHex(array);
MyWallet.addAdditionalSeeds(seed_prefix + this.address_seed);
}
var address = SharedCoin.generateAddressFromCustomSeed(seed_prefix + this.address_seed, this.address_seen_n);
this.address_seen_n++;
return address;
},
executeOffer : function(offer, success, error) {
offer.submit(function() {
console.log('Successfully Submitted Offer');
offer.pollForProposalID(function(proposal_id) {
console.log('Proposal ID ' + proposal_id);
offer.getProposal(proposal_id, function(proposal) {
console.log('Got Proposal');
offer.checkProposal(proposal, function(tx, outpoints_to_offer_next_stage) {
console.log('Proposal Looks Good');
offer.signInputs(proposal, tx, function(signatures) {
console.log('Inputs Signed');
offer.submitInputScripts(proposal, signatures, function (obj) {
console.log('Submitted Input Scripts');
proposal.pollForCompleted(function(tx_hash) {
console.log('Poll For Completed Success');
//Connect the newly discovered transaction hash
for (var i in outpoints_to_offer_next_stage) {
outpoints_to_offer_next_stage[i].hash = tx_hash;
}
success(outpoints_to_offer_next_stage);
}, error);
}, error);
}, error);
}, error)
}, error);
}, error);
}, error);
},
execute : function(success, error) {
var self = this;
var execStage = function(ii) {
var offerForThisStage = self.offers[ii];
console.log('Executing Stage ' + ii);
self.executeOffer(offerForThisStage, function(outpoints_to_offer_next_stage) {
ii++;
if (ii < self.n_stages) {
//Connect the outputs created from the previous stage to the inputs to use this stage
self.offers[ii].offered_outpoints = outpoints_to_offer_next_stage;
execStage(ii);
} else if (ii == self.n_stages) {
success();
}
}, error);
};
MyWallet.backupWallet('update', function() {
console.log('Saved Wallet');
execStage(0);
}, error);
},
constructRepetitions : function(initial_offer, fee_each_repetition, success, error) {
try {
var self = this;
var totalValueInput= BigInteger.ZERO;
for (var i in initial_offer.offered_outpoints) {
totalValueInput = totalValueInput.add(BigInteger.valueOf(initial_offer.offered_outpoints[i].value));
}
var totalValueLeftToConsume = totalValueInput;
for (var ii = 0; ii < self.n_stages-1; ++ii) {
var offer = SharedCoin.newOffer();
//Copy the inputs from the last offer
if (ii == 0) {
for (var i in initial_offer.request_outputs) {
if (initial_offer.request_outputs[i].exclude_from_fee) {
var changeoutput = initial_offer.request_outputs.splice(i, 1)[0];
offer.request_outputs.push(changeoutput);
totalValueLeftToConsume = totalValueLeftToConsume.subtract(BigInteger.valueOf(changeoutput.value));
break;
}
}
offer.offered_outpoints = initial_offer.offered_outpoints.slice(0);
initial_offer.offered_outpoints = [];
}
totalValueLeftToConsume = totalValueLeftToConsume.subtract(fee_each_repetition[ii]);
var splitValues = [10,5,1,0.5,0.3,0.1];
var maxSplits = 10;
var rand = Math.random();
if (totalValueLeftToConsume.intValue() >= 0.2*satoshi) {
var minSplits = 2;
if (rand >= 0.5) {
minSplits = 3;
}
} else {
var minSplits = 1;
}
var outputsAdded = false;
for (var _i = 0; _i < 1000; ++_i) {
for (var sK in splitValues) {
var variance = (splitValues[sK] / 100) * ((Math.random()*30)-15);
var splitValue = BigInteger.valueOf(Math.round((splitValues[sK] + variance) * satoshi));
var valueAndRemainder = totalValueLeftToConsume.divideAndRemainder(splitValue);
var quotient = valueAndRemainder[0].intValue();
if (quotient >= minSplits && quotient <= maxSplits) {
if (valueAndRemainder[1].compareTo(BigInteger.ZERO) == 0 || valueAndRemainder[1].compareTo(BigInteger.valueOf(SharedCoin.getMinimumOutputValue())) >= 0) {
var remainderDivides = [];
if (valueAndRemainder[1].compareTo(BigInteger.ZERO) > 0) {
if (quotient <= 1) {
var new_address = self.generateAddressFromSeed();
offer.request_outputs.push({
value : valueAndRemainder[1].toString(),
script : Crypto.util.bytesToHex(Script.createOutputScript(new_address).buffer)
});
} else {
remainderDivides = divideUniformlyRandomly(valueAndRemainder[1].intValue(), quotient);
}
}
for (var iii = 0; iii < quotient; ++iii) {
var new_address = self.generateAddressFromSeed();
var value = splitValue;
if (remainderDivides[iii] && remainderDivides[iii] > 0) {
value = value.add(BigInteger.valueOf(remainderDivides[iii]));
}
offer.request_outputs.push({
value : value.toString(),
script : Crypto.util.bytesToHex(Script.createOutputScript(new_address).buffer)
});
}
outputsAdded = true;
break;
}
}
}
if (outputsAdded)
break;
}
if (!outputsAdded) {
console.log('Could not successfully split output');
var new_address = self.generateAddressFromSeed();
offer.request_outputs.push({
value : totalValueLeftToConsume.toString(),
script : Crypto.util.bytesToHex(Script.createOutputScript(new_address).buffer)
});
}
self.offers.push(offer);
}
self.offers.push(initial_offer);
success(self);
} catch (e) {
error(e);
}
}
};
};
this.generateNewAddress = function(success, error) {
try {
var key = MyWallet.generateNewKey();
var bitcoin_address = key.getBitcoinAddress();
MyWallet.setAddressLabel(bitcoin_address.toString(), 'SharedCoin Change');
success(bitcoin_address);
} catch (e) {
error(e);
}
}
this.getMinimumOutputValue = function() {
return options.minimum_output_value;
}
this.getToken = function() {
return options.token;
}
this.getMinimumInputValue = function() {
return options.minimum_input_value;
}
this.getMinimumSupportedVersion = function() {
return options.min_supported_version;
}
this.getIsEnabled = function() {
return options.enabled;
}
this.getMaximumOutputValue = function() {
return options.maximum_output_value;
}
this.getFee = function() {
return options.fee_percent;
}
this.getMinimumFee = function() {
return options.minimum_fee ? options.minimum_fee : 0;
}
this.constructPlan = function(el, success, error) {
try {
var repetitionsSelect = el.find('select[name="repetitions"]');
var repetitions = parseInt(repetitionsSelect.val());
if (repetitions <= 0) {
throw 'invalid number of repetitions';
}
var newTx = initNewTx();
//Get the from address, if any
var from_select = el.find('select[name="from"]');
var fromval = from_select.val();
if (fromval == null || fromval == 'any') {
newTx.from_addresses = MyWallet.getActiveAddresses();
} else if (from_select.attr('multiple') == 'multiple') {
newTx.from_addresses = fromval;
} else {
newTx.from_addresses = [fromval];
}
var recipients = el.find(".recipient");
recipients.each(function() {
try {
var child = $(this);
var value_input = child.find('input[name="send-value"]');
var send_to_input = child.find('input[name="send-to-address"]');
var value = 0;
try {
value = precisionToSatoshiBN(value_input.val());
if (value == null || value.compareTo(BigInteger.ZERO) <= 0)
throw 'You must enter a value greater than zero';
} catch (e) {
throw 'Invalid send amount';
};
//Trim and remove non-printable characters
var send_to_address = $.trim(send_to_input.val()).replace(/[\u200B-\u200D\uFEFF]/g, '');
if (send_to_address == null || send_to_address.length == 0) {
throw 'You must enter a bitcoin address for each recipient';
}
var address = resolveAddress(send_to_address);
if (address == null || address.length == 0) {
throw 'You must enter a bitcoin address for each recipient';
}
newTx.to_addresses.push({address: new Bitcoin.Address(address), value : value});
} catch (e) {
error(e);
}
});
//Check that we have resolved all to addresses
if (newTx.to_addresses.length == 0 || newTx.to_addresses.length < recipients.length) {
return;
}
var to_values_before_fees = [];
var fee_each_repetition = [];
for (var i in newTx.to_addresses) {
var to_address = newTx.to_addresses[i];
to_values_before_fees.push(to_address.value);
for (var ii = repetitions-1; ii >= 0; --ii) {
var feeThisOutput = SharedCoin.calculateFeeForValue(to_address.value);
to_address.value = to_address.value.add(feeThisOutput);
var existing = fee_each_repetition[ii];
if (existing) {
fee_each_repetition[ii] = existing.add(feeThisOutput);
} else {
fee_each_repetition[ii] = feeThisOutput;
}
}
}
//Build the last offer
SharedCoin.generateNewAddress(function(change_address) {
newTx.min_input_confirmations = 1;
newTx.allow_adjust = false;
newTx.change_address = change_address;
newTx.base_fee = BigInteger.ZERO;
newTx.min_input_size = BigInteger.valueOf(SharedCoin.getMinimumInputValue());
newTx.min_free_output_size = BigInteger.valueOf(SharedCoin.getMinimumOutputValue());
newTx.fee = BigInteger.ZERO
newTx.ask_for_fee = function(yes, no) {
no();
};
var offer = SharedCoin.newOffer();
newTx.signInputs = function() {
try {
var self = this;
for (var i = 0; i < self.tx.ins.length; ++i) {
var input = self.tx.ins[i];
var base64Hash = input.outpoint.hash;
var hexHash = Crypto.util.bytesToHex(Crypto.util.base64ToBytes(base64Hash).reverse());
offer.offered_outpoints.push({hash : hexHash, index : input.outpoint.index, value : input.outpoint.value.toString()});
}
for (var i = 0; i < self.tx.outs.length; ++i) {
var output = self.tx.outs[i];
var array = output.value.slice(0);
array.reverse();
var value = new BigInteger(array);
var pubKeyHash = new Bitcoin.Script(output.script).simpleOutPubKeyHash();
var outputAddress = new Bitcoin.Address(pubKeyHash).toString();
if (outputAddress.toString() == change_address.toString()) {
offer.request_outputs.push({value : value.toString(), script : Crypto.util.bytesToHex(output.script.buffer), exclude_from_fee : true});
} else {
offer.request_outputs.push({value : to_values_before_fees[i].toString(), script : Crypto.util.bytesToHex(output.script.buffer)});
}
}
var plan = SharedCoin.newPlan();
plan.n_stages = repetitions;
plan.c_stage = 0;
plan.constructRepetitions(offer, fee_each_repetition, success, function(e) {
error(e);
});
} catch (e) {
error(e);
}
};
newTx.addListener({
on_error : function(e) {
error();
}
});
newTx.start();
}, function(e) {
error(e);
});
} catch (e) {
MyWallet.makeNotice('error', 'misc-error', e);
}
}
this.calculateFeeForValue = function(input_value) {
var minFee = BigInteger.valueOf(SharedCoin.getMinimumFee());
if (input_value.compareTo(BigInteger.ZERO) > 0 && SharedCoin.getFee() > 0) {
var mod = Math.ceil(100 / SharedCoin.getFee());
var fee = input_value.divide(BigInteger.valueOf(mod));
if (minFee.compareTo(fee) > 0) {
return minFee;
} else {
return fee;
}
} else {
return minFee;
}
}
this.init = function(el) {
$('#sharedcoin-recover').unbind().click(function() {
var self = $(this);
MyWallet.getSecondPassword(function() {
self.prop('disabled', true);
var original_text = self.text();
self.text('Working. Please Wait...');