-
Notifications
You must be signed in to change notification settings - Fork 33
/
sendform.js
632 lines (478 loc) · 18.1 KB
/
sendform.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
var initialAmount = 0;
function AcceptOfferController($scope, $http) {
$scope.transactionInformation;
$scope.footer = "FOOTER";
$scope.title = "TITLE";
$scope.step = 0.1;
$scope.amount;
$scope.fee = 0.0005;
$scope.key = "";
$scope.currency = "";
$scope.toAddress = "";
$scope.toAddrReadOnly = true;
$scope.keyChange = function () {
if ($scope.key != "") {
$('#reSign').attr('disabled', false);
}
else {
$('#reSign').attr('disabled', true);
}
};
$scope.getSellofferData = function () {
// parse tx from url parameters
var myURLParams = BTCUtils.getQueryStringArgs();
//var file = 'tx/' + myURLParams['tx'] + '.json';
$scope.currency = myURLParams['currency'];
$scope.toAddress = myURLParams['addr'];
$scope.toAddrReadOnly = ($scope.toAddress && $scope.toAddress.length > 0);
if (myURLParams['fee'])
$scope.fee = parseFloat(myURLParams['fee']);
if (myURLParams['amount'])
$scope.amount = parseFloat(myURLParams['amount']);
}
$scope.comboBoxValueChange = function () {
console.log($scope.transactionInformation);
}
$scope.AmountChanged = function () {
$('#amountWarning').hide();
}
$('.invalidKey').hide();
}
//class for Context
BTNClientContext = new function () {
};
//class for Signing
BTNClientContext.Signing = new function () {
};
BTNClientContext.Signing.Transaction = "";
BTNClientContext.Signing.ConvertRaw = function (jsonTransaction) {
//var str = BTNClientContext.Signing.Transaction;
var str = jsonTransaction;
str = str.replace(/[^0-9a-fA-f]/g, '');
var bytes = Crypto.util.hexToBytes(str);
var sendTx = BTNClientContext.Signing.deserialize(bytes);
var text = BTNClientContext.toBBE(sendTx);
return text;
}
BTNClientContext.Signing.ConvertJSON = function (signedTransaction) {
try {
$('.invalidTransaction').hide();
var sendTx = BTNClientContext.fromBBE(signedTransaction);
}
catch (e) {
$('.invalidTransaction').show();
}
var rawTx = Crypto.util.bytesToHex(sendTx.serialize());
return rawTx;
};
BTNClientContext.Signing.Verify = function () {
console.log("verify function");
var from_addr = $("input.select.optional.form-control.form-control30px.combobox").val();
var dataToSend = { addr: from_addr };
var ok = true;
$.post('/wallet/validateaddr/', dataToSend, function (data) {
console.log('success');
console.log(data);
if (data.status == 'OK') {
ok = true;
$('#verifyMessage').addClass('greenText');
$('#verifyMessage').text('OK');
$('#verifyMessage').show();
BTNClientContext.Resize();
return ok;
}
else {
$('#verifyMessage').addClass('greenText');
ok = false;
if (data.error == 'invalid pubkey') {
$('#verifyMessage').text('invalid pubkey');
} else {
if (data.error == 'missing pubkey') {
$('#verifyMessage').text('no pubkey on blockchain. use wallet or supply Public Key from brainwallet.org');
} else {
$('#verifyMessage').addClass('redText');
if (data.error == 'invalid address') {
$('#verifyMessage').text('invalid address');
} else {
$('#verifyMessage').text('invalid');
}
}
}
}
$('#verifyMessage').show();
BTNClientContext.Resize();
return ok;
}).fail(function () {
console.log('fail');
$('#verifyMessage').text('ping?');
$('#verifyMessage').addClass('redText');
ok = false;
$('#verifyMessage').show();
BTNClientContext.Resize();
return ok;
});
};
BTNClientContext.Signing.SingSource = function () {
var hashType = 1;
//Source Script for signing
var sourceScript = [];
var sourceScriptString = $('#sourceScript').val().split(';');
$.each(sourceScriptString, function (i, val) {
sourceScript[i] = new BTNClientContext.parseScript(val);
console.log(val);
console.log($.toJSON(sourceScript[i]));
console.log(BTNClientContext.dumpScript(sourceScript[i]));
});
//create transaction object from BBE JSON
// var transactionBBE = $('#transactionBBE').val();
var transactionBBE = BTNClientContext.Signing.ConvertRaw(BTNClientContext.Signing.Transaction);
try {
$('.invalidTransaction').hide();
var sendTx = BTNClientContext.fromBBE(transactionBBE);
}
catch (e) {
$('.invalidTransaction').show();
return;
}
//signature section
var eckey = BTNClientContext.GetEckey($('#privateKey').val()); //ECDSA
console.log($('#privateKey').val());
console.log(Crypto.util.bytesToHex(eckey.getPubKeyHash()));
for (var i = 0; i < sendTx.ins.length; i++) { //for each input in the transaction -- sign it with the Key
//console.log($.toJSON(sendTx));
//console.log($.toJSON(sourceScript[i]));
var hash = sendTx.hashTransactionForSignature(sourceScript[i], i, hashType); //Get hash of the transaction applying the soure script
console.log(Crypto.util.bytesToHex(hash));
var signature = eckey.sign(hash); //<---SIGN HERE
signature.push(parseInt(hashType, 10)); //add white space
var pubKey = eckey.getPub(); //public key
//creating new in sript signature
var script = new Bitcoin.Script();
script.writeBytes(signature);
script.writeBytes(pubKey);
//write sript signature
sendTx.ins[i].script = script;
}
return BTNClientContext.toBBE(sendTx);
};
//Should re sign transaction -- need to call all BC functions
BTNClientContext.Signing.ReSignTransaction = function () {
var reSigned = BTNClientContext.Signing.SingSource();
BTNClientContext.Signing.TransactionBBE = reSigned;
//show re-signed transaction
$('#signedTransactionBBE').val(reSigned);
BTNClientContext.Signing.RawChecked = false;
BTNClientContext.ToRawSigned();
$('#RawRadioBtnSigned').addClass('active');
$('#JsonRadioBtnSigned').removeClass('active');
//show hidden
$('#reSignClickedForm').show();
};
BTNClientContext.Signing.SendTransaction = function () {
var signedTransaction = $('#signedTransactionBBE').val();
//Maybe I need to convert to object from json string???
var sendTx = BTNClientContext.fromBBE(signedTransaction);
var rawTx = Crypto.util.bytesToHex(sendTx.serialize());
var dataToSend = { signedTransaction: rawTx };
console.log(dataToSend);
// Ajax call to /wallet/pushtx/
$.post('/wallet/pushtx/', dataToSend, function (data) {
console.log('success');
console.log(data);
}).fail(function () {
// TODO This should be changed - Currently always fail as there is no server
});
};
BTNClientContext.Signing.GetRawTransaction = function () {
$('#statusMessage').removeClass('redText');
$('#statusMessage').addClass('greenTextColor');
$('#statusMessage').text('');
$('#createRawResponseForm').hide();
var myURLParams = BTCUtils.getQueryStringArgs();
var marker = myURLParams['marker'];
var to_address = $("#recipient").val();
var from_address = $("input.select.optional.form-control.form-control30px.combobox").val();
var amount = $('#amount').val();
var currency = $('#currency').val();
var fee = $('#fee').val();
var dataToSend = { from_address: from_address, to_address: to_address, amount: amount, currency: currency, fee: fee, marker: marker };
console.log(dataToSend);
// Ajax call to /wallet/send/
$.post('/wallet/send/', dataToSend, function (data) {
console.log('success');
console.log(data);
BTNClientContext.Signing.GetRawTransactionResponse(data);
}).fail(function () {
console.log('fail');
var testResponse = {
'status': 'ping?',
'sourceScript': 'ERROR',
'transaction': ''
};
BTNClientContext.Signing.GetRawTransactionResponse(testResponse);
});
};
BTNClientContext.Signing.GetRawTransactionResponse = function (data) {
var status = data.status;
if (!status)
status = data.error;
if (status && status != "OK" && status != "Ok" && status != "ok") {
if (status.length > 120) {
//take first 117 and add ...
status = status.substr(0, 117);
status += "...";
}
$('#statusMessage').removeClass('greenTextColor');
$('#statusMessage').addClass('redText');
$('#statusMessage').text(status);
$('#createRawResponseForm').hide();
return;
}
BTNClientContext.Signing.Transaction = data.transaction;
//Init fields values
//data should have fields sourceScript and transaction
$('#sourceScript').val(data.sourceScript);
$('#transactionBBE').val(data.transaction);
//Showing the fields
$('#createRawResponseForm').show();
};
// HISTORY of Buyer address or public key
BTNClientContext.Signing.supportsStorage = function () {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
};
BTNClientContext.Signing.initHistoryCombobox = function () {
var myURLParams = BTCUtils.getQueryStringArgs();
var useAddress = myURLParams['from'];
var showValuesInCombobox = Wallet.GetAddressesOfFirstWallet();
if (useAddress) {
if (showValuesInCombobox.indexOf(useAddress) == -1) {
showValuesInCombobox.splice(0, 0, useAddress);
}
}
$.each(showValuesInCombobox, function (key, value) {
console.log(key);
console.log(value);
$('#fromAddressOrPublicKey')
.append($("<option></option>")
.attr("value", value)
.text(value));
//.attr("value", value.address)
// .text(value.address));
});
if (useAddress) {
$("#fromAddressOrPublicKey").val(useAddress);
}
$("#fromAddressOrPublicKey").combobox();
};
BTNClientContext.Signing.addAddressToHistory = function () {
if (BTNClientContext.Signing.supportsStorage()) {
var address = $("input.select.optional.form-control.form-control30px.combobox").val();
var history;
if (localStorage["Addresses"]) {
history = JSON.parse(localStorage["Addresses"]);
if (history.length > 9) {
history.shift();
}
var addr = { 'address': address };
// Check if the addr is in the array already and if it is delete it
// var index = history.indexOf(addr);
var index = history.indexOf(address);
if (index > -1) {
history.splice(index, 1);
}
//add new address to array
// history.push(addr);
history.push(address);
localStorage["Addresses"] = JSON.stringify(history);
}
else { // If the localStorage["Addresses"] doesn't exists
// var addr = { 'address': address };
var que = [];
// que.push(addr);
que.push(address);
localStorage["Addresses"] = JSON.stringify(que);
}
// console.log(localStorage["Addresses"]);
}
};
$(document).ready(function myfunction() {
$('#sendLoader').addClass('hideLoader');
//Combbox init
BTNClientContext.Signing.initHistoryCombobox();
BTNClientContext.Resize();
var navHeight = $('.navbar').height();
$('.page-container').css('paddingTop', navHeight + 20);
//disable btn at the beggining, because it needs to have a value in a privateKey
$('#reSign').attr('disabled', true);
$('#createRawTransaction').click(function () {
$('#createRawTransactionLoader').show();
BTNClientContext.Signing.GetRawTransaction();
//Add address to history
BTNClientContext.Signing.addAddressToHistory();
$('#createRawTransactionLoader').hide();
});
$('#reSign').click(function () {
$('.invalidKey').hide();
$('.invalidTransaction').hide();
$('#reSignLoader').show();
try {
BTNClientContext.Signing.ReSignTransaction();
}
catch (e) {
console.log(e);
$('.invalidKey').show();
$('.invalidTransaction').show();
//If the key is invalid the resigned transaction form is hidden again
$('#reSignClickedForm').hide();
}
$('#reSignLoader').hide();
});
$('#send').click(function () {
$('#sendLoader').addClass('showUntilAjax');
$('#sendLoader').addClass('show3sec');
var sendLoaderInterval = setInterval(function () {
$('#sendLoader').removeClass('show3sec');
clearInterval(sendLoaderInterval);
}, 3000);
//BTNClientContext.Signing.SendTransaction();
BTNClientContext.txSend();
});
$('#verifyButton').click(function () {
$('#verifyMessage').hide();
$('#verifyLoader').show();
//If returned ok then add address to history
if (BTNClientContext.Signing.Verify()) {
BTNClientContext.Signing.addAddressToHistory();
console.log('added to history');
}
else {
console.log('not verified and not ok');
}
$('#verifyLoader').hide();
});
//$("#rawJsonRadio").click(function () {
// console.log(BTNClientContext.Signing.Transaction);
// var converted = "";
// if ($('#RawRadioBtn').hasClass('active')) { //It raw has class active it means that the json state is selected now
// converted = BTNClientContext.Signing.ConvertRaw();
// }
// else { //the raw state is selected now
// converted = BTNClientContext.Signing.Transaction;
// }
// $('#transactionBBE').val(converted);
//});
$('#JsonRadioBtn').click(function () {
var converted = BTNClientContext.Signing.ConvertRaw(BTNClientContext.Signing.Transaction);
$('#transactionBBE').val(converted);
});
$('#RawRadioBtn').click(function () {
var converted = BTNClientContext.Signing.Transaction;
$('#transactionBBE').val(converted);
});
$('#JsonRadioBtnSigned').click(function () {
if (BTNClientContext.Signing.RawChecked == true) {
var rawTransaction = $('#signedTransactionBBE').val();
var converted = BTNClientContext.Signing.ConvertRaw(rawTransaction);
$('#signedTransactionBBE').val(converted);
$('#signedTransactionBBE').attr('readonly', false);
BTNClientContext.Signing.RawChecked = false;
}
});
BTNClientContext.Signing.RawChecked = true;
$('#RawRadioBtnSigned').click(function () {
BTNClientContext.ToRawSigned();
if ($('.invalidTransaction').is(":visible")) {
console.log('Json is invalid');
$('#RawRadioBtnSigned').removeClass('active');
$('#JsonRadioBtnSigned').addClass('active');
}
});
});
BTNClientContext.ToRawSigned = function() {
if (BTNClientContext.Signing.RawChecked == false) {
var converted = "";
try {
var signedTransaction = $('#signedTransactionBBE').val();
converted = BTNClientContext.Signing.ConvertJSON(signedTransaction);
$('#signedTransactionBBE').attr('readonly', false);
BTNClientContext.Signing.RawChecked = true;
}
catch (e) {
converted = $('#signedTransactionBBE').val();
$('#RawRadioBtnSigned').removeClass('active');
$('#JsonRadioBtnSigned').addClass('active');
}
$('#signedTransactionBBE').val(converted);
}
}
BTNClientContext.Resize = function () {
// console.log($('#amount').width());
var width = $('#amount').width() - 25;
var left = $('#verifyButton').offset().left + 70;
// console.log(left);
$('#verifyMessage').width(width);
$('#verifyMessage').offset({ left: left });
};
$(window).resize(function () {
BTNClientContext.Resize();
});
function txSent(text) {
alert(text ? text : 'No response!');
}
BTNClientContext.txSend = function() {
$('#sendHyperlink').hide();
$('#sendMessage').hide();
BTNClientContext.ToRawSigned();
$('#RawRadioBtnSigned').addClass('active');
$('#JsonRadioBtnSigned').removeClass('active');
var rawTx = $('#signedTransactionBBE').val();
//var sendTx = BTNClientContext.fromBBE(signedTransaction);
//var rawTx = Crypto.util.bytesToHex(sendTx.serialize());
//url = 'http://bitsend.rowit.co.uk/?transaction=' + tx;
url = 'http://blockchain.info/pushtx';
postdata = 'tx=' + rawTx;
if (url != null && url != "") {
BTNClientContext.tx_fetch(url, txSent, txSent, postdata);
}
return false;
}
// Some cross-domain magic (to bypass Access-Control-Allow-Origin)
BTNClientContext.tx_fetch = function(url, onSuccess, onError, postdata) {
var useYQL = true;
if (useYQL) {
var q = 'select * from html where url="'+url+'"';
if (postdata) {
q = 'use "https://dev.masterchain.info/js/htmlpost.xml" as htmlpost; ';
q += 'select * from htmlpost where url="' + url + '" ';
q += 'and postdata="' + postdata + '" and xpath="//p"';
}
url = 'https://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(q);
}
$.ajax({
url: url,
success: function(res) {
$('#sendLoader').removeClass('showUntilAjax');
$('#sendMessage').text('Transaction sent');
$('#sendMessage').addClass('greenTextColor');
$('#sendMessage').show();
//Get transaction hash code
var link = "https://blockchain.info/tx/";
//signed transaction code
var code = JSON.parse(BTNClientContext.Signing.TransactionBBE).hash;
link += code;
$('#sendLink').attr('href', link);
$('#sendLink').text(link);
$('#sendHyperlink').show();
},
error:function (xhr, opt, err) {
$('#sendMessage').text('Transaction send error');
$('#sendMessage').addClass('redText');
$('#sendMessage').show();
$('#sendLoader').removeClass('showUntilAjax');
}
});
}