-
Notifications
You must be signed in to change notification settings - Fork 2
/
gethAPI.js
617 lines (564 loc) · 26 KB
/
gethAPI.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
// ONLY SUPPORT FOR .png FILES FOR NOW.
const express = require('express')
const fs = require('fs')
const web3 = require('web3')
const ipfsApi = require('ipfs-api')
const concat = require('concat-stream')
const util = require('./utilAPI.js')
const mkdirp = require('mkdirp')
// const lwip=require('lwip')
app = express();
const appDataDir = process.env.HOME + '/.EthPhoto/'
const imageDataDir = appDataDir + 'img-store/'
const fileDataDir = appDataDir + 'file-store/'
var web3Host = 'http://localhost';
var web3Port = '8545';
var ipfsHost = 'localhost';
var ipfsAPIPort = '5001';
var ipfsWebPort = '8080';
var ipfs = ipfsApi(ipfsHost, ipfsAPIPort);
var appPort = 6969;
var lastBlockNumber = 0;
//============================
//========VARIABLES===========
//============================
var mutexForFile = {};
var mutexForCountImagesTag = {};
var countImagesForTag = {};
var indexOfHashInTagFile = {};
var getUserCountForHash = {};
var getUserImages = {};
var thumbnailHashToImageHash = {};
var address = "";
//===========================
//======END OF VARIABLES=====
//===========================
web3.setProvider(new web3.providers.HttpProvider(web3Host + ':' + web3Port));
if (web3.isConnected()) {
console.log("Ethereum - connected to RPC server");
fs.readFile(appDataDir + 'accountAddress', 'utf-8', function(error, content) {
if (error)
content = createAccount();
address = content;
});
if (!fs.existsSync(imageDataDir))
mkdirp.sync(imageDataDir);
if (!fs.existsSync(fileDataDir))
mkdirp.sync(fileDataDir);
} else {
console.error("Ethereum - no connection to RPC server from 47");
}
//===========================
//==== API to call BEGIN ====
//===========================
app.post('/uploadPhoto', function uploadPhotoFromDisk(req, res) {
addFileToIPFSAndSendTransaction(req.query.path, req.query.tag, req.query.geoLocation)
.then(() => {
res.json("Completed adding image and thumbnail.");
console.log("Completed adding image and thumbnail.");
})
});
app.post('/deletePhoto', function deletePhotoFromDisk(req, res) {
console.log("path - ", req.query.path);
console.log("tag - ", req.query.tag);
deleteFileFromIPFSSendTransaction(req.query.path, req.query.tag)
.then(() => {
res.json("Completed deleting image and thumbnail.");
console.log("Completed deleting image.")
})
});
app.post('/viewPhoto', function viewPhoto(thumbnailHash) {
var imageHash = thumbnailHashToImageHash[thumbnailHash];
getIPFSImageData(imageHash)
.then(() => {
console.log("Got image.");
})
});
//=========================
//==== API to call END ====
//=========================
//=============================
//==== start of IPFS CODE =====
//=============================
var _thumbnailHash;
function getImageThumbnailHash(path) {
return new Promise((resolve, reject) => {
// lwip.open(path,(error,image)=>{
// image.batch()
// .scale(0.3)
// .writeFile('./thumbNail.png',(err)=>{
// ipfs.util.addFromFs("./thumbNail.png",(err,res)=>{
// if(err){
// console.log("Error while adding thumbNail");
// }
// else{
// _thumbnailHash=res[0]["hash"];
// resolve();
// }
// })
// })
// })
var options = {
mode: 'text',
args: [path]
};
PythonShell.run('generateThumbNail.py', options, (err, res) => {
console.log('done');
ipfs.util.addFromFs('./_thumbnail.png', (err, res) => {
if (err) {
console.log("Error while adding thumbnail");
} else {
_thumbnailHash = res[0]["hash"];
resolve();
}
})
})
});
}
function getIPFSImageData(multihash) {
ipfs.files.cat(multihash, (error, stream) => {
if (error) {
console.log("Error while getting " + multihash, error);
throw error;
}
var writeStream = fs.createWriteStream(imageDataDir + multihash + '.png');
stream.pipe(writeStream, { end: false });
console.log('done');
});
}
function ipfsAddToDisk(hash, thumbnailHash) {
console.log("ipfsAddToDisk_BEGIN");
getIPFSImageData(hash);
getIPFSImageData(thumbnailHash);
console.log("ipfsAddToDisk_END");
}
function deleteFileFromIPFSSendTransaction(path, tag) {
return new Promise((resolve, reject) => {
ipfs.util.addFromFs(path, (error, response) => {
if (error) {
console.log("File already deleted.");
} else {
sendTransactionToDelete(address, response[0]["hash"], tag);
resolve();
}
})
})
}
function addFileToIPFSAndSendTransaction(path, tag, geolocation) {
return new Promise((resolve, reject) => {
ipfs.util.addFromFs(path, (error, response) => {
if (error) {
console.log(path, error);
console.log("Error while adding file.");
} else {
console.log("Added file to IPFS");
getImageThumbnailHash(path)
.then(() => {
console.log("thumbnailHash is: " + _thumbnailHash);
thumbnailHashToImageHash[_thumbnailHash] = response[0]["hash"];
resolve();
sendTransactionToAdd(address, response[0]["hash"], _thumbnailHash, tag, geolocation);
})
}
})
})
}
//==========================
//==== end of IPFS CODE ====
//==========================
//==================================
//=====start of fileSystem CODE=====
//==================================
var Mutex = function() {
this._busy = false;
this._queue = [];
}
Mutex.prototype.synchronize = function(task) {
this._queue.push(task);
if (!this._busy) {
this._dequeue();
}
};
Mutex.prototype._dequeue = function() {
this._busy = true;
var next = this._queue.shift();
if (next) {
this._execute(next);
} else {
this._busy = false;
}
};
Mutex.prototype._execute = function(task) {
var self = this;
task().then(function() {
self._dequeue();
}, function() {
self._dequeue();
});
};
function Photo(hash, thumbNailHash, tag, geoLocation) {
this.hash = hash;
this.thumbNailHash = thumbNailHash;
this.tag = tag;
this.geoLocation = geoLocation;
this.print = () => {
console.log(this.hash);
console.log(this.thumbNailHash);
console.log(this.tag);
console.log(this.geoLocation);
}
}
function editFile(fileName, photo) {
return new Promise(function(resolve, reject) {
fs.readFile(fileName, 'utf8', function(error, json) {
var config = { "data": [] };
try {
config = JSON.parse(json);
} catch (e) {
// console.log("empty");
}
config["data"].push(photo);
fs.writeFile(fileName, JSON.stringify(config), 'utf8', function(error) {
fs.readFile(fileName, 'utf8', function(error, json) {
resolve();
})
});
});
});
}
function addPhotoToFile(indexOfFile, currPhoto) {
var indexOfFileInInt = parseInt(parseInt(indexOfFile) / 10);
var fileName = fileDataDir + currPhoto.tag + "_" + indexOfFileInInt.toString() + "_" + (indexOfFileInInt + 1).toString() + ".txt";
var jsonPromise = new Promise(function(resolve, reject) {
if (fileName in mutexForFile) {
resolve();
} else {
console.log("====================================");
console.log(fileName + " ADDED TO MUTEX SYSTEM");
console.log("====================================");
mutexForFile[fileName] = new Mutex();
fs.writeFile(fileName, '', function(error) {
resolve();
})
}
});
jsonPromise.then(() => {
mutexForFile[fileName].synchronize(function() {
return editFile(fileName, currPhoto)
});
});
}
function incrementTag(tag, currPhoto) {
return new Promise((resolve, reject) => {
countImagesForTag[tag] = parseInt(countImagesForTag[tag]) + 1;
indexOfHashInTagFile[currPhoto.hash] = countImagesForTag[tag];
console.log(indexOfHashInTagFile[currPhoto.hash] + "__" + currPhoto.hash);
addPhotoToFile(countImagesForTag[tag], currPhoto);
resolve();
});
}
function addPhoto(tag, hash, thumbNailHash, geoLocation) {
console.log("addPhoto_BEGIN");
console.log(tag, hash, thumbNailHash, geoLocation);
var currPhoto = new Photo(hash, thumbNailHash, tag, geoLocation);
var jsonPromise = new Promise(function(resolve, reject) {
// console.log("JSON_PROMISE",hash,thumbNailHash);
ipfsAddToDisk(hash, thumbNailHash);
if (tag in countImagesForTag) {
resolve();
} else {
countImagesForTag[tag] = 0;
mutexForCountImagesTag[tag] = new Mutex();
resolve();
}
});
jsonPromise.then((error, response) => {
mutexForCountImagesTag[tag].synchronize(function() {
return incrementTag(tag, currPhoto);
})
});
console.log("addPhoto_END");
}
var _result = [];
function readDataFromFile(fileName) {
return new Promise((resolve, reject) => {
fs.readFile(fileName, 'utf8', (error, json) => {
var config = [];
try {
config = JSON.parse(json);
} catch (e) {
throw e;
}
_result.push(config);
resolve();
})
})
}
//To use this function include a callback function after
//setting a suitable timer.
//NEED TO UNDERSTAND THIS!
app.get('/searchTag', (req, res) => {
var tag = req.query.tag;
var startIndex = req.query.startIndex;
var endIndex = req.query.endIndex;
searchForTagWithRange(tag, startIndex, endIndex)
.then(() => {
console.log(_result);
res.json(_result);
})
})
function searchForTagWithRange(tag, startIndex, endIndex) {
_result = []
return new Promise((resolve, reject) => {
(function loopingOverFiles(index) {
var jsonPromise = new Promise((resolveThis, reject) => {
var fileName = fileDataDir + tag + "_" + index.toString() + "_" + (index + 1).toString() + ".txt";
index++;
try {
mutexForFile[fileName].synchronize(() => {
return readDataFromFile(fileName)
.then(() => {
resolveThis();
})
});
} catch (err) {
console.log(err);
}
});
jsonPromise.then(() => {
if (index < parseInt(endIndex)) {
loopingOverFiles(index);
} else if (index == parseInt(endIndex)) {
resolve();
}
});
})(parseInt(startIndex));
})
}
function deleteFromFileNameAfterLock(fileName, hash) {
// console.log(fileName+"__"+hash);
return new Promise((resolve, response) => {
fs.readFile(fileName, 'utf8', function(error, json) {
config = JSON.parse(json);
configNew = { "data": [] };
(function loopingOverData(index) {
var jsonPromise = new Promise((resolveThis, reject) => {
if (config["data"][index].hash != hash) {
configNew["data"].push(config["data"][index]);
}
index++;
resolveThis();
});
jsonPromise.then(() => {
if (index < config["data"].length) {
loopingOverData(index);
} else if (index == config["data"].length) {
fs.writeFile(fileName, JSON.stringify(configNew), 'utf8', function(error) {
console.log(configNew);
resolve();
})
}
})
})(0);
})
})
}
function deleteFromFileName(fileName, hash) {
mutexForFile[fileName].synchronize(function() {
return deleteFromFileNameAfterLock(fileName, hash);
})
}
function deletePhotoFromFile(tag, hash) {
return new Promise((resolve, response) => {
var indexOfHash = parseInt(parseInt(indexOfHashInTagFile[hash]) / 10);
var fileName = fileDataDir + tag + "_" + indexOfHash.toString() + "_" + (indexOfHash + 1).toString() + ".txt";
deleteFromFileName(fileName, hash);
resolve();
})
}
function deletePhoto(tag, hash) {
console.log("DELETING_PHOTO_BEGIN", tag, hash);
mutexForCountImagesTag[tag].synchronize(function() {
console.log("DELETING: " + hash);
fs.exists(imageDataDir + hash + '.png', (exists) => {
if (exists) {
console.log('File exists.');
try {
fs.unlink(imageDataDir + hash + '.png');
} catch (e) {
console.log(e);
}
} else {
console.log("FILE DOSENT EXIST");
}
})
return deletePhotoFromFile(tag, hash);
})
console.log("DELETING_PHOTO_END");
}
function sleep(time) {
return new Promise((resolve) => {
setTimeout(resolve, time);
})
}
//================================
//=====END OF fileSystem CODE=====
//================================
//===========================================
//===== backEndProcess related code BEGIN====
//===========================================
function createAccount() {
// var accountSource = util.parseRemoveLineBreaks('./userAccount.sol');
// console.log(accountSource);
// var compiledObject = web3.eth.compile.solidity(accountSource);
// console.log("compiled object" + compiledObject);
// var accountContract = web3.eth.contract(compiledObject['<stdin>:userAccount'].info.abiDefinition);
// console.log(accountContract);
var accountContract = web3.eth.contract([{ "constant": false, "inputs": [{ "name": "photoHash", "type": "string" }, { "name": "tag", "type": "string" }], "name": "deletePhoto", "outputs": [], "payable": true, "type": "function" }, { "constant": false, "inputs": [{ "name": "photoHash", "type": "string" }, { "name": "thumbnailHash", "type": "string" }, { "name": "tag", "type": "string" }, { "name": "geolocation", "type": "string" }], "name": "uploadPhoto", "outputs": [], "payable": true, "type": "function" }, { "inputs": [], "payable": false, "type": "constructor" }, { "anonymous": false, "inputs": [{ "indexed": false, "name": "message", "type": "string" }], "name": "addressLogger", "type": "event" }]);
var data = '0x6060604052341561000c57fe5b5b5b5b6107ca8061001e6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680635d960e1a14610046578063ebe7a7e5146100db575bfe5b6100d9600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919050506101f6565b005b6101f4600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190505061041f565b005b7fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a146040518080602001828103825260128152602001807f50484f544f5f44454c4554455f5354415254000000000000000000000000000081525060200191505060405180910390a17fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a148260405180806020018281038252838181518152602001915080519060200190808383600083146102cf575b8051825260208311156102cf576020820191506020810190506020830392506102ab565b505050905090810190601f1680156102fb5780820380516001836020036101000a031916815260200191505b509250505060405180910390a17fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a14816040518080602001828103825283818151815260200191508051906020019080838360008314610379575b80518252602083111561037957602082019150602081019050602083039250610355565b505050905090810190601f1680156103a55780820380516001836020036101000a031916815260200191505b509250505060405180910390a17fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a146040518080602001828103825260108152602001807f50484f544f5f44454c4554455f454e440000000000000000000000000000000081525060200191505060405180910390a15b5050565b7fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a146040518080602001828103825260128152602001807f50484f544f5f55504c4f41445f5354415254000000000000000000000000000081525060200191505060405180910390a17fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a148460405180806020018281038252838181518152602001915080519060200190808383600083146104f8575b8051825260208311156104f8576020820191506020810190506020830392506104d4565b505050905090810190601f1680156105245780820380516001836020036101000a031916815260200191505b509250505060405180910390a17fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a148360405180806020018281038252838181518152602001915080519060200190808383600083146105a2575b8051825260208311156105a25760208201915060208101905060208303925061057e565b505050905090810190601f1680156105ce5780820380516001836020036101000a031916815260200191505b509250505060405180910390a17fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a1482604051808060200182810382528381815181526020019150805190602001908083836000831461064c575b80518252602083111561064c57602082019150602081019050602083039250610628565b505050905090810190601f1680156106785780820380516001836020036101000a031916815260200191505b509250505060405180910390a17fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a148160405180806020018281038252838181518152602001915080519060200190808383600083146106f6575b8051825260208311156106f6576020820191506020810190506020830392506106d2565b505050905090810190601f1680156107225780820380516001836020036101000a031916815260200191505b509250505060405180910390a17fa6389559397379f4838732946412b33d3c7880096a9de333e06c6fd5a3ba6a146040518080602001828103825260108152602001807f50484f544f5f55504c4f41445f454e440000000000000000000000000000000081525060200191505060405180910390a15b505050505600a165627a7a7230582024d00ceb8efec111a2f8dbbfa3138ea6f3860a9cf7dd251f3bf89c9872be075d0029';
accountContract.new({ from: web3.eth.accounts[0], data: data, gas: 47000000 }, function(e, contract) {
if (!e) {
if (!contract.address) {
console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined ...");
} else {
console.log("Contract mined! Address: " + contract.address);
fs.writeFile(appDataDir + 'accountAddress', contract.address);
return contract.address;
}
} else {
console.log(e);
throw e;
}
})
}
function sendTransactionToAdd(address, photoHash, thumbnailHash, tag, geolocation) {
console.log("_sendTransactionToAdd_BEGIN");
var accountContract = web3.eth.contract([{ "constant": false, "inputs": [{ "name": "photoHash", "type": "string" }, { "name": "tag", "type": "string" }], "name": "deletePhoto", "outputs": [], "payable": true, "type": "function" }, { "constant": false, "inputs": [{ "name": "photoHash", "type": "string" }, { "name": "thumbnailHash", "type": "string" }, { "name": "tag", "type": "string" }, { "name": "geolocation", "type": "string" }], "name": "uploadPhoto", "outputs": [], "payable": true, "type": "function" }, { "inputs": [], "payable": false, "type": "constructor" }, { "anonymous": false, "inputs": [{ "indexed": false, "name": "message", "type": "string" }], "name": "addressLogger", "type": "event" }]);
var account = accountContract.at(address);
var transactionHash = account.uploadPhoto(photoHash, thumbnailHash, tag, geolocation, { from: web3.eth.accounts[0] });
console.log("_sendTransactionToAdd_FINISH " + transactionHash);
}
function sendTransactionToDelete(address, photoHash, tag) {
var accountContract = web3.eth.contract([{ "constant": false, "inputs": [{ "name": "photoHash", "type": "string" }, { "name": "tag", "type": "string" }], "name": "deletePhoto", "outputs": [], "payable": true, "type": "function" }, { "constant": false, "inputs": [{ "name": "photoHash", "type": "string" }, { "name": "thumbnailHash", "type": "string" }, { "name": "tag", "type": "string" }, { "name": "geolocation", "type": "string" }], "name": "uploadPhoto", "outputs": [], "payable": true, "type": "function" }, { "inputs": [], "payable": false, "type": "constructor" }, { "anonymous": false, "inputs": [{ "indexed": false, "name": "message", "type": "string" }], "name": "addressLogger", "type": "event" }]);
var account = accountContract.at(address);
var transactionHash = account.deletePhoto(photoHash, tag, { from: web3.eth.accounts[0] });
}
function hexToAscii(hexStr) {
var str = '';
var n = hexStr.length;
for (var i = 0; i < n; i += 2) {
var c = String.fromCharCode(parseInt(hexStr.substr(i, 2), 16));
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_')) {
str += c;
}
}
return str;
}
function init() {
if (!web3.isConnected()) {
console.log("Ethereum - no connection to RPC server");
} else {
console.log("Ethereum - connected to RPC server");
ipfs.swarm.peers(function(err, reponse) {
if (err) {
console.log(err);
} else {
console.log("IPFS - connected to " + response.Strings.length + " peers");
console.log(response);
}
})
}
}
function computeOnTransaction(transactionHash) {
console.log("computeOnTransaction_BEGIN");
web3.eth.getTransactionReceipt(transactionHash, (error, response) => {
if (!error) {
if (response["logs"].length > 0) {
var functionArgumet = hexToAscii(response["logs"][0]["data"]).toString();
console.log(functionArgumet.length);
console.log(functionArgumet == "PHOTO_UPLOAD_START");
if (response["logs"].length == 6) {
// console.log("one of these");
if (functionArgumet == "PHOTO_UPLOAD_START") {
var hash = hexToAscii(response["logs"][1]["data"]);
var thumbnailHash = hexToAscii(response["logs"][2]["data"]);
var tag = hexToAscii(response["logs"][3]["data"]);
var geolocation = hexToAscii(response["logs"][4]["data"]);
addPhoto(tag, hash, thumbnailHash, geolocation);
}
} else if (response["logs"].length == 4) {
// console.log("PHOTO_DELETE_START");
var hash = hexToAscii(response["logs"][1]["data"]);
var tag = hexToAscii(response["logs"][2]["data"]);
deletePhoto(tag, hash);
} else if (response["logs"].length == 3) {
if (functionArgumet.indexOf("AddPeer") != -1) {
console.log("AddPeer");
addPeer(response["logs"]);
}
}
}
} else {
console.log(error);
}
})
}
function getDataFromBlock(blockIndex) {
console.log(blockIndex);
web3.eth.getBlockTransactionCount(blockIndex, (error, response) => {
var numOfTransaction = JSON.parse(response);
if (numOfTransaction > 0) {
(function loopingOverBlockTransaction(index) {
var jsonPromise = new Promise((resolve, reject) => {
web3.eth.getTransactionFromBlock(blockIndex, index, (error, response) => {
if (!error) {
try {
computeOnTransaction(response["hash"]);
} catch (e) {
console.log(e);
}
index++;
resolve();
}
})
});
jsonPromise.then(() => {
if (index < numOfTransaction) {
loopingOverBlockTransaction(index);
}
})
})(0);
}
})
}
function checkForTransactions() {
console.log(lastBlockNumber);
web3.eth.getBlockNumber((error, response) => {
var blockIndex = JSON.parse(response);
var goFromBlock = lastBlockNumber;
lastBlockNumber = blockIndex;
for (var index = goFromBlock; index < blockIndex; index++) {
getDataFromBlock(index);
}
});
}
setInterval(checkForTransactions, 3000);
//=========================================
//==== backEndProcess related code END ====
//=========================================
var server = app.listen(appPort, function() {
var host = server.address().address
var port = server.address().port
console.log("EthPhoto listening at http://%s:%s", host, port)
});
// expose app
exports = module.exports = app;
//=======================
//======TEST CODE========
//=======================
sleep(20000).then(() => {
searchForTagWithRange("anime", 0, 1)
.then(() => {
console.log(_result);
})
})