Repository navigation
Expand file tree
/
Copy pathapi.js
More file actions
1342 lines (1268 loc) · 45.7 KB
/
Copy pathapi.js
File metadata and controls
1342 lines (1268 loc) · 45.7 KB
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
//////////////////////////////////////////////////////////////
// Load configuration file //
//
var fs = require('fs');
JSON.minify = JSON.minify || require('node-json-minify');
if (!fs.existsSync('./config.json')){
console.log('config.json file does not exist. Read the installation/setup instructions.');
return;
}
var CONFIG = JSON.parse(JSON.minify(fs.readFileSync('./config.json', {encoding: 'utf8'})));
console.log('config load from api');
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// inter-proccess comunication
// a way to send some info to api proccess
//
var bestIndex = 0;
var ipc=require('node-ipc');
ipc.config.id = 'sandonodeapi';
ipc.config.retry= 1500;
ipc.config.silent = true;
function connectIPC() {
ipc.connectTo('sandonodesync', function() {
ipc.of.sandonodesync.on('height', function(data,socket) {
bestIndex = data;
console.log('got height ', bestIndex);
});
});
}
connectIPC();
//////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
// shared functions from utils.js
//
var utils = require('./lib/utils');
var convHash = utils.convHash;
var outputAddress = utils.outputAddress;
var inputAddress = utils.inputAddress;
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// a simple database interface //
//
var database = require('./lib/database');
var dbBlocks = CONFIG.dbBlocks;
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// an initial database query on block height
//
database.searchCount(dbBlocks, {}, function(result) {
bestIndex = (result-1);
});
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// web interface
//
var apiPort = CONFIG.apiPort;
var http = require('http');
console.log('Web server started...'); // a debug message, can be deleted
http.createServer(function (req, res) {
console.log('URL request: ' + req.url); // a debug message, can be deleted
var url = req.url;
var commands = url.replace(/\/\s*$/,'').split('/');
commands.shift();
if (commands[0] === 'api') {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'X-Powered-By': 'sando'
});
commands.shift();
responseAPIrequest(res, commands);
}
else {
responseExplorer(res, commands);
}
}).listen(apiPort);
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// data structures for blocks and transactions //
//
var bitcore = require('bitcore-lib');
var Block = bitcore.Block;
var SAT = 100000000;
var COINBASE = CONFIG.blockchain.nullHash;
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// *** utility functions *** //
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Remove unsafe characters from an input string to prevent
// script/database injection attack
//
function safeString(s) {
return s.replace(/\W/g, '');
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Converet a part of string from URL request to a 4-char string
// without any special symbols, with 'main' as a default.
//
function safeCommand(s) {
var cl = s.length;
var command = (cl == 0) ? 'main' : s[0].substring(0,4).replace(/\W/g, '');
return command;
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Convert a part of a string from URL request to a parameter
// without any special symbols. Param will contain coin address,
// transaction id, block hash or block index.
//
function safeParam(s) {
var cl = s.length;
var param = (cl == 0) ? '' : s[0].substring(7, s[0].length).replace(/\W/g, '');
return param;
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Calculate a difference between now and a past timestamp in minutes.
//
function calcAge(time) {
var dif = Math.round((Math.floor(Date.now())/1000 - time)/6)/10;
return dif;
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Convert a timestamp to a human readable date/time.
//
function timeToISO(time) {
var newDate = new Date();
newDate.setTime(time*1000);
var dstr = newDate.toISOString().replace('T', ' ').substring(0, 19);
return dstr;
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Add an item into the list (array) to be contained only once.
//
function condPush(list, item) {
var isIn = false;
for (var i=0; i<list.length; i++) {
if (list[i] === item) {
isIn = true;
break;
}
}
if (!isIn)
list.push(item);
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Indexing of address usage in the database by 'oid' parameter
// 'char_number1_number2'. This function split it back to 3
// components
//
function DEOID(oid) {
var arr = oid.split('_');
return {typ: arr[0], ti: Number(arr[1]), oi: Number(arr[2])};
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// *** API-call functions *** //
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API web interface command recognization
//
function responseAPIrequest(res, commands) {
var nParams = commands.length;
var command = (nParams == 0) ? 'help' : safeString(commands[0]);
var param = (nParams > 1) ? safeString(commands[1]) : '';
var pfrom = (nParams > 2) ? safeString(commands[2]) : '';
var pto = (nParams > 3) ? safeString(commands[3]) : '';
console.log(command, param);
switch(command) {
case 'help':
showHelp(res);
break;
case 'getheight':
case 'height':
case 'getblockcount':
showHeight(res);
break;
case 'getblock':
case 'block':
showBlock(res, param);
break;
case 'txinfo':
case 'tx':
showTxInfo(res, param);
break;
case 'addressfirstseen':
showAddressFirst(res, param);
break;
case 'addressinfo':
showAddrInfo(res, param);
break;
case 'getbalance':
case 'balance':
showBalance(res, param);
break;
case 'utxo':
case 'unspent':
showUnspent(res, param);
break;
case 'txbyaddr':
showTxByAddr(res, param, pfrom, pto);
break;
case 'getdifficulty':
case 'difficulty':
showDifficulty(res);
break;
case 'getblockhash':
case 'blockhash':
showBlockHash(res, param);
break;
case 'getblockheight':
case 'getblockindex':
case 'blockheight':
case 'blockindex':
showBlockHeight(res, param);
break;
case 'getrawblock':
case 'rawblock':
showRawBlock(res, param);
break;
case 'getrawtransaction':
case 'rawtransaction':
case 'rawtx':
showRawTx(res, param);
break;
default:
res.end('{"error": "unknown request"}');
}
}
//////////////////////////////////////////////////////////////
// A default API command, it will show list of avaiable API
// commands and a short description.
function showHelp(res) {
var rts = {
avaiable_commands: {
help: "show this help on avaiable API commands",
getheight: "return current block height",
height: "the same as getheight",
getblock: "return a block, takes block hash or block heigth as PARAM: http://url:port/api/getblock/PARAM",
block: "the same as getblock",
txinfo: "return details of transactions TX: http://url:port/txinfo/TX",
tx: "the same as txinfo",
addressfirstseen: "return the time when ADDRESS appeared in the blockchain: http://url:port/api/addressfirstseen/ADDRESS",
getbalance: "return balance of ADDRESS: http://url:port/api/getbalance/ADDRESS",
addressinfo: "return a short summary of the address balance and transactions",
balance: "the same as getbalance",
utxo: "return unspent transaction outputs of ADDRESS: http://url:port/api/utxo/ADDRESS",
unspent: "the same as utxo",
txbyaddr: "return a list of all transactions on ADDRESS: http://url:port/api/txbyaddress/ADDRESS or optionally with paging: http://url:port/api/txbyaddress/ADDRESS/START_INDEX/END_INDEX"
}
};
res.end(JSON.stringify(rts));
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show a raw block data
//
function showRawBlock(res, param) {
if (param === '')
param = bestIndex;
var index = Number(param);
var query = ((!(isNaN(param))) && Number.isInteger(index)) ? {i: index} : {_id: param};
database.search(dbBlocks, query, function(rts) {
if (rts)
res.end(JSON.stringify(rts.d.buffer.toString('hex')));
else
res.end(JSON.stringify({error: 'not found'}));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show a raw block data
//
function showRawTx(res, param) {
if (param === '') {
res.end(JSON.stringify({error: 'not found'}));
return;
}
var query = {t: param};
database.search(dbBlocks, query, function(rts) {
if (rts) {
block = Block.fromBuffer(rts.d.buffer);
var i=0;
while (block.transactions[i].hash != param)
i++;
res.end(JSON.stringify(block.transactions[i].toString('hex')));
}
else
res.end(JSON.stringify({error: 'not found'}));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show the current minning difficulty
//
function showDifficulty(res) {
var param = bestIndex;
getBlock(param, function(response) {
if (response.hasOwnProperty('difficulty'))
res.end(JSON.stringify(response.difficulty));
else
res.end(JSON.stringify(response));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show a block hash
//
function showBlockHash(res, param) {
if (param === '')
param = bestIndex;
getBlock(param, function(response) {
if (response.hasOwnProperty('hash'))
res.end(JSON.stringify(response.hash));
else
res.end(JSON.stringify(response));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show a block height
//
function showBlockHeight(res, param) {
if (param === '')
param = bestIndex;
getBlock(param, function(response) {
if (response.hasOwnProperty('height'))
res.end(JSON.stringify(response.height));
else
res.end(JSON.stringify(response));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show the current height of the blockchain
//
function showHeight(res) {
var rts = JSON.stringify({height: bestIndex});
res.end(rts);
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show a block details. If no param given,
// it will show the latest block.
//
function showBlock(res, param) {
if (param == '')
param = bestIndex;
getBlock(param, function(response) {
res.end(JSON.stringify(response));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// A function to read a block from the database. Autodetect if
// the param is block index or block hash, extract the data
// of the block found and return the as a JSON structure.
// When finished, the callBack function is called because
// database operations are asynchronous so the value can
// not be simply returned by the return command.
//
function getBlock(param, callBack) {
var index = Number(param);
var query = ((!(isNaN(param))) && Number.isInteger(index)) ? {i: index} : {_id: param};
database.search(dbBlocks, query, function(rts) {
if (!rts) {
console.log('API asked invalid block '); // a debug message, can be deleted
callBack({error: "unknown block requested"});
return;
}
var response;
if (!(rts.d)) {
console.log('API asked non-indexed block '); // a debug message, can be deleted
response = {hash: rts.h, indexed: false}; // theoretically should never happen ?
callBack(response);
return;
}
var block = Block.fromBuffer(rts.d.buffer);
var size = rts.d.buffer.length;
var header = block.header;
var transactions = block.transactions;
var txs = [];
var totalOutput = 0;
transactions.forEach(function(tx) {
txs.push(tx.hash);
tx.outputs.forEach( function(output) {
totalOutput += output.satoshis;
});
});
var created = transactions[0].outputs[0].satoshis;
response = {
hash: header.hash,
confirmations: (bestIndex - rts.i),
size: size,
height: rts.i,
version: header.version,
merkleroot: convHash(header.merkleRoot),
tx: txs,
valueout: totalOutput,
created: created,
time: header.time,
nonce: header.nonce,
bits: header.bits.toString(16),
difficulty: header.getDifficulty(),
previousblockhash: convHash(header.prevHash)
};
callBack(response);
return;
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show a transaction details. If no param given,
// an error message is shown.
//
function showTxInfo(res, param) {
if (param == '') {
res.end('{"error": "unknown transaction requested"}');
return;
}
var query = { t: param };
database.search(dbBlocks, query, function(rts) {
if (!rts) {
res.end('{"error": "unknown transaction requested"}');
return;
}
var response = getTxInfo(rts, param);
res.end(JSON.stringify(response));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Extranct the particular transaction from block database record
// passed in rts and return info on the transaction in JSON format.
//
function getTxInfo(rts, param) {
if (rts.i > 0) {
var block = Block.fromBuffer(rts.d.buffer);
var txs = block.transactions;
var txIndex = 0;
while (txIndex < txs.length) {
if (txs[txIndex].hash === param) {
var tx = txs[txIndex];
var response = {
txid: tx.hash,
version: tx.version,
locktime: tx.nLockTime,
block: rts.i,
index: txIndex,
timestamp: block.header.time,
confirmations: (bestIndex+1-rts.i),
inputs: [],
outputs: []
};
if ( (tx.version == 2) && (tx.txComment) ) {
var txComposedComment = getSplitTxComment(tx.txComment.toString());
if (txComposedComment.txComment.length > 0)
response.txComment = txComposedComment.txComment;
if (txComposedComment.IPFS_ID.length > 0)
response.IPFS_ID = txComposedComment.IPFS_ID;
}
var inputs = tx.inputs;
var item;
inputs.forEach(function(input) {
var prevTxId = input.prevTxId.toString('hex');
if (prevTxId == COINBASE) {
item = {received_from: 'coinbase'};
response.inputs.push(item);
}
else {
var address = inputAddress(input);
var txPrevId = input.prevTxId.toString('hex');
var n = input.outputIndex;
item = {addr: address, received_from: {tx: txPrevId, n: n}};
response.inputs.push(item);
}
});
var outputs = tx.outputs;
outputs.forEach(function(output) {
var address = outputAddress(output);
var amount = (output.satoshis)/SAT;
var script = output.script.toBuffer().toString('hex');
var item = {addr: address, amount: amount, script: script};
response.outputs.push(item);
});
return response;
}
txIndex++;
}
}
return {error: "unknown"}; // The code never should got here, but for a safety.
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show the firts occurency of the address
// (passed as param) in the blockchain.
//
function showAddressFirst(res, param) {
if (param == '') {
res.end('{"error": "unknown address requested"}');
return;
}
var query = { a: param };
database.search(dbBlocks, query, function(rts) { // no need for a sort-search, blocks have been sorted in the database
if (!rts) {
res.end('{"error": "unknown address requested"}');
return;
}
var block = Block.fromBuffer(rts.d.buffer);
res.end(JSON.stringify(timeToISO(block.header.time)));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show the avaiable balance on an address.
// Calculation for a large address (e.g. used for mining) take place
// up to 30 seconds.
//
function showBalance(res, param) {
if (param == '') {
res.end('{"error": "unknown address requested"}');
return;
}
var query = { a: param };
database.searchMore(dbBlocks, query, function(rts) {
if (rts.length === 0) {
res.end('{"error": "unknown address requested"}');
return;
}
var jsonRts = exBalance(param, rts);
var balance = jsonRts.balance;
res.end(JSON.stringify(balance));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show the a short summary of an address.
// Calculation for a large address (e.g. used for mining) take place
// up to 30 seconds.
//
function showAddrInfo(res, param) {
if (param == '') {
res.end('{"error": "unknown address requested"}');
return;
}
var query = { a: param };
database.searchMore(dbBlocks, query, function(rts) {
if (rts.length === 0) {
res.end('{"error": "unknown address requested"}');
return;
}
var jsonRts = exBalance(param, rts);
res.end(JSON.stringify(jsonRts));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API command to show the unspent outputs of an address.
// Returns the informations needed to construct a spent transaction.
// Similarly the getbalance API command, limit on transaction count
// is applied due to the algorithm complexity.
//
function showUnspent(res, param) {
if (param == '') {
res.end('{"error": "unknown address requested"}');
return;
}
var query = { a: param };
database.searchMore(dbBlocks, query, function(rts) {
if (!rts) {
res.end('{"error": "unknown address requested"}');
return;
}
if (rts.length > CONFIG.dbLimit) {
res.end('{"error": "to many transactions -> wallet is protected "}');
return;
}
var unspent = findUnspent(rts, param);
res.end(JSON.stringify(unspent));
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Analyze the block records found in the database to identify
// the unspent transactions of an address passed in param.
// Dev note: calculation could be moved to the client side
// and server would only do the database search?
//
function findUnspent(blocks, param) {
var txo = {};
var unspent = [];
blocks.forEach( function(blockRecord) {
var block = Block.fromBuffer(blockRecord.d.buffer);
var txs = block.transactions;
var i=0;
while (blockRecord.a[i] != param)
i++;
var b = blockRecord.b[i];
Object.keys(b).forEach( function(c) {
var doid = DEOID(c);
var tx = txs[doid.ti];
if (doid.typ == 'o') {
var id = tx.hash + '_' + doid.oi;
txo[id] = {
tx_hash: tx.hash,
tx_output_n: doid.oi,
value: b[c],
confirmations: bestIndex - blockRecord.i,
script: tx.outputs[doid.oi].script.toBuffer().toString('hex')
};
}
else {
var input = tx.inputs[doid.oi];
var prevTxId = input.prevTxId.toString('hex');
var outIndex = input.outputIndex;
var idSpent = prevTxId + '_' + outIndex;
txo[idSpent] = false;
}
});
});
Object.values(txo).forEach( function(item) {
if (item != false) {
unspent.push(item);
}
});
return unspent;
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// API call for detailed list of input and output transactions
// on an address.
//
function showTxByAddr(res, param, pf, pt) {
if (param == '') {
res.end('{"error": "unknown address requested"}');
return;
}
var query = { a: param };
console.log('jsem tu a hledam v databazi...');
database.searchMore(dbBlocks, query, function(rts) {
if (!rts) {
res.end('{"error": "unknown address requested"}');
return;
}
if (rts.length > CONFIG.dbLimit) {
res.end('{"error": "to many transactions -> wallet is protected "}');
return;
}
findAllTx(rts, param, function(response) {
var n = response.length;
var last = parseInt(pt);
if (Number.isNaN(last) || last>=n)
last = n-1;
var first = parseInt(pf);
if (Number.isNaN(first) || first<0)
first = 0;
// console.log('pocet', n, ' dolni: ', first, 'horni:', last);
var filtered = [];
var i = first;
while ( i <= last) {
var revmap = n-i-1;
i++;
// console.log('pushing:', revmap);
filtered.push(response[revmap]);
}
res.end(JSON.stringify(filtered));
});
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Prepare an array of all raw transactions in a list of blocks
//
function findRawTx(blocks) {
var rawtxs = [];
blocks.forEach( function(blockRecord) {
var block = Block.fromBuffer(blockRecord.d.buffer);
var txs = block.transactions;
txs.forEach( function(tx) {
var outputs = [];
tx.outputs.forEach( function(output) {
output = {
address: outputAddress(output),
satoshis: output.satoshis,
script: output.script.toBuffer().toString('hex')
};
outputs.push(output);
});
var inputs = [];
tx.inputs.forEach( function(input) {
input = {
address: inputAddress(input),
};
inputs.push(input);
});
var wtx = {
inputs: inputs,
outputs: outputs
};
rawtxs[tx.hash]=wtx;
});
});
return rawtxs;
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Extract txComment and IPFS_ID from composedComment
//
function getSplitTxComment(txRawComment) {
var nlen = txRawComment.length;
var npos = txRawComment.indexOf("\n");
var txComment = '';
var IPFS_ID = '';
if (npos == -1)
txComment = txRawComment;
else {
IPFS_ID = txRawComment.substring(0, npos);
if ((npos+1) < nlen)
npos++;
txComment = (npos<nlen) ? txRawComment.substring(npos, nlen) : "";
}
var rts = {};
rts['txComment'] = txComment;
rts['IPFS_ID'] = IPFS_ID;
return rts;
}
//////////////////////////////////////////////////////////////
// Prepare a list (in the JSON format) of transactions on an
// address for the API function txbyaddr.
// Dev note: Here the call-back style for return values was
// needless - replace with a single return?
//
function findAllTx(blocks, param, callBack) {
var rawtxs = findRawTx(blocks);
var txo = {};
blocks.forEach( function(blockRecord) {
var block = Block.fromBuffer(blockRecord.d.buffer);
var txs = block.transactions;
var i=0;
while (blockRecord.a[i] != param)
i++;
var b = blockRecord.b[i];
Object.keys(b).forEach( function(c) {
var doid = DEOID(c);
var tx = txs[doid.ti];
var blockInfo = {
block_hash: blockRecord._id,
block_height: blockRecord.i,
block_time: block.header.time
};
var txInfo;
if (doid.typ == 'o') {
var id = tx.hash + '_' + doid.oi;
txInfo = {
tx_hash: tx.hash,
tx_index: doid.ti,
tx_output_index: doid.oi,
confirmations: bestIndex - blockRecord.i,
inputs: rawtxs[tx.hash].inputs,
outputs: rawtxs[tx.hash].outputs
};
if (tx.hasOwnProperty('txComment'))
txInfo['txComment'] = tx.txComment.toString();
var fromInfo = {
block: blockInfo,
transaction: txInfo
};
txo[id] = {
value: b[c],
script: tx.outputs[doid.oi].script.toBuffer().toString('hex'),
spent: false,
received: fromInfo
};
}
else {
var input = tx.inputs[doid.oi];
var prevTxId = input.prevTxId.toString('hex');
var outIndex = input.outputIndex;
var idSpent = prevTxId + '_' + outIndex;
txInfo = {
tx_hash: tx.hash,
tx_index: doid.ti,
tx_input_index: doid.oi,
confirmations: bestIndex - blockRecord.i,
inputs: rawtxs[tx.hash].inputs,
outputs: rawtxs[tx.hash].outputs,
};
if (tx.hasOwnProperty('txComment')) {
var txComposedComment = getSplitTxComment(tx.txComment.toString());
if (txComposedComment.txComment.length > 0)
txInfo['txComment'] = txComposedComment.txComment;
if (txComposedComment.IPFS_ID.length > 0)
txInfo['IPFS_ID'] = txComposedComment.IPFS_ID;
}
var spentInTx = {
block: blockInfo,
transaction: txInfo
};
txo[idSpent].spent = true;
txo[idSpent].sent = spentInTx;
}
});
});
callBack(Object.values(txo));
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// *** Block Explorer functions *** //
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Web interface of the Block Explorer code.
// It translates the URL to commands
// and calls the appropriate internal functions.
// TODO: The current implementation does not allow graphic
// resources (icons, images, etc.). Is there a simple way for it?
//
function responseExplorer(res, commands) {
var command = safeCommand(commands);
var param = safeParam(commands);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<!DOCTYPE html><html><head><meta charset="utf-8"><title>'+CONFIG.coinName+' ('+CONFIG.ticker+') Block Explorer</title>');
res.write('<style>a:link, a:visited {text-decoration: none; color: blue}</style>');
res.write('</head><body>');
switch(command) {
case 'help':
exHelp(res);
break;
case 'find':
exFind(res, param);
break;
default:
exMain(res);
}
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// A shorcut function for creation the common top part of
// the Block Explorer web page.
//
function exHeader(res) {
var title = '<h1><p align="center"><a href="main">Block Explorer for '+CONFIG.coinName+'</a></p></h1>';
var searchBar = '<div align="center"> <form action="find" method="get">';
searchBar+= '<input name="q" type="text" size="80" placeholder="block hash, index, transaction or address" />';
searchBar+= '<input type="submit" value="Search" /></form></div><hr>';
var navBar = '<table width="100%"><tr><td width="20%"><B>Block height '+bestIndex+'</b></td>';
navBar+= '<td width="60%"> </td>';
navBar+= '<td width="20%"><a href="/help">API documentation</a>    ';
navBar+= '<a href="/api"> API link</a></td></tr></table>';
res.write(title);
res.write(navBar);
res.write(searchBar);
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// A shorcut function for creation the common bottom part of
// the Block Explorer web page and finishing the http response.
//
function exFooter(res) {
var footer = '<hr><p align="center">Powered by <A href="https://github.com/Sandokaaan/EarthCoin-API">Sando-explorer</A> Ⓒ 2018</P></body></html>';
res.write(footer);
res.end();
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Block Explorer default page - tha last 50 blocks sumary
//
function exMain(res) {
last50Blocks( function(blockList) {
exHeader(res);
res.write(lbInfo(blockList));
exFooter(res);
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Search the database for the last 50 blocks and pass them to
// the call-back function. Call-back is used due to the database
// requests are asynchronous.
//
function last50Blocks(callBack) {
var query = {i: {$gt: (bestIndex-50)}};
database.searchMore(dbBlocks, query, function(rts) {
callBack(rts);
});
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Extranct block infromations from database block records
// passed in and return them in the HTML format.
//
function lbInfo(blockList) {
var response = '<H3>Last Blocks </H1><HR><table width="100%" border="1">';
response+= '<tr><td width="16%" align="center">Block Height</td><td width="16%" align="center">Age (min)</td>';
response+= '<td width="16%" align="center">Transactions</td><td width="16%" align="center">Value Out (' + CONFIG.ticker + ')</td>';
response+= '<td width="16%" align="center">Difficulty</td><td width="20%" align="center">Extracted by</td></tr>';
for (var i=(blockList.length-1); i>0; i--) {
var block = Block.fromBuffer(blockList[i].d.buffer);
response+= '<tr><td align="center"><a href="/find?q=' + blockList[i].i + '">' + blockList[i].i + '</a></td>';
var time = block.header.time;
response+= '<td align="center">'+ calcAge(time) + '</td>';
response+= '<td align="center">'+ block.transactions.length;
response+= '<font color="gray"> (';
response+= parseInt(Math.round(blockList[i].d.buffer.length/102.4))/10 + ' kB)</font></td>';
var valOut = 0;
block.transactions.forEach( function(tx) {
tx.outputs.forEach( function(output) {
valOut += output.satoshis;
});
});
response+= '<td align="center">'+ valOut/SAT + '</td>';
response+= '<td align="center">'+ block.header.getDifficulty() + '</td>';
var miner = outputAddress(block.transactions[0].outputs[0]);
if (miner == "unknown")
var miner = outputAddress(block.transactions[0].outputs[1]);
response+= '<td align="center"><font size="2">'+ miner + '</font></td>';
response+= '</tr>';
}
response+= '</table>';
return response;
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// Search the database for string passed in param and try
// to interpret is as a block index/hash, transaction id
// or address. Result is translatet into the HTLM code
// by daughter functions and passed to the call-back function.