Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·814 lines (715 loc) · 29.5 KB
/
Copy pathindex.js
File metadata and controls
executable file
·814 lines (715 loc) · 29.5 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
#!/usr/bin/env node
const program = require("commander");
//const contractFIle = "contracts/SimpleStorage.json"
//const contractAddress = "0x14a0a8f85f7041c1bed7a372479821f0caf09b63";
//var contractJsonInterface = JSON.parse(fs.readFileSync(contractFIle).toString());
//var contract = new web3.eth.Contract(contractJsonInterface, contractAddress);
let cost = 1000000000;
let gas = 10000000;
let configFileName = "./.conf.json"
let hashesBase = "./.HashBases.json"
let owners = "./.owners.txt"
let SUPPORTED_FORMATS = [
'.docx',
'.txt',
'.doc',
'.md',
'.html',
'.xml',
'.org',
''
]
var source;
var compiled;
var bin;
var abi;
var contract;
var bin2;
var abi2;
var contract2;
var bin3;
var abi3;
var contract3;
var bin4;
var abi4;
var contract4;
var address, address2, address3, address4;
var account;
program
.version("1.0")
.description("odh command-line interface of managing distributed files-")
.option('--add <file>', "File Inclusion to ODH")
.option('--setup', "Setting up the network [contract compiling & deployement]")
.option('--add-remote <link>', "File Inclusion to ODH")
.option('--from-ipfs-hash <hash>', 'Include files from an IPFS Hash')
.option('--sync', 'Synchronize the new node with the current state of the network')
.option('--o-check <file>', 'Check wether a file is an open document')
.option('--owning <file>', 'Registering an ownership claim')
.option('--claim-of-ownership <hash>', 'Checking wether a claim of ownership is valid')
.option('--webui', 'Lauching the web user interface')
.option('--vote-for-deletion <hash>', 'Vote of the deletion a file in the network.' )
.option('--deletion-req <hash>', 'Supply a request for the deletion of a file in the network.' )
.option('--full-node-req', 'Lauching the process of becoming a full node')
.option('--light-node-req <hash List File>', 'Launching the hosting of a set of files')
.option('--exist <hash | name | regexp>', "verifying if a file is in the network")
.option('--stats', "Display some statistics about files in the network")
.option('--peers', "Display the set of peer connected to the network")
.option('--convert <hash> <file.ext>', "Convert a hosted file to different format according to .ext")
.option('--revoque-current-req', "Suppend the deletion request")
.option('--fetch <hash | name>', "Write in the current directory the file hashed <hash>")
.option('--id', "Getting the identity of the node")
.option('--garbage-collect', "Remove unlinked or unpinned IPFS files")
.option('--reset', "Remove configuration files")
.option('--list-files', 'List pinned files')
.option('--author', 'The author')
.parse(process.argv)
const Web3 = require("web3");
const IPFS = require('ipfs-api');
const co = require("co");
const prompt = require("co-prompt");
const chalk = require("chalk")
const fs = require("fs");
const ipfs = new IPFS({ host: 'localhost', port: 5001, protocol: 'http' });
const provider = new Web3.providers.HttpProvider("http://localhost:8545");
const web3 = new Web3(provider);
const bs58 = require("base58")
function getBytes32FromIpfsHash(ipfsListing) {
var v = "0x"+bs58.decode(ipfsListing)
return v.slice(2).toString('hex')
}
function getIpfsHashFromBytes32(bytes32Hex) {
const hashHex = "1220" + bytes32Hex.slice(2)
const hashBytes = Buffer.from(hashHex, 'hex');
const hashStr = bs58.encode(hashBytes)
return hashStr
}
const ipfsHashtoBN = (hash) => {
try {
const bn = web3.utils.toBN(web3.utils.toHex(hash))
return bn;
} catch (err) {
console.log("----------------------------------------------------------------")
console.log("=> ERROR: ", err)
console.log("----------------------------------------------------------------")
}
}
const bnto2uint = (bn) => {
try {
var k = 23;
gn = bn.toBuffer()
gn1 = gn.slice(0, k).toString()
gn2 = gn.slice(k, k*2).toString()
return [ ipfsHashtoBN(gn1), ipfsHashtoBN(gn2)]
} catch (err) {
console.log("----------------------------------------------------------------")
console.log("=> BN: ", bn)
console.log("----------------------------------------------------------------")
console.log(err)
}
}
const fromBNtoIpfs = (bn) => {
return bn.toBuffer().toString()
}
const lightNodeReq = () => {
console.log("Light Node Sync:")
const fileHashName = program.lightNodeReq;
const hashes = fs.readFileSync(fileHashName).split("\n");
for (var i in hashes) {
ipfs.get(hashes[i]).then(inf => {
const out = inf[0].hash;
console.log("file %s added successfully", out)
})
}
}
const extractType = (hash) => {
let type;
ipfs.get(hash).then(inf => {
let content = inf[0].content;
// some format detection stuff here.
})
return type;
}
const convertFile = (hash, to) => {
var nodePandoc = require('node-pandoc');
var src, args, callback;
// if the file is supported and destination formart are supported then
// extract file type
extractType(hash);
src = './word.docx';
// Or in an array of strings -- careful no spaces are present:
args = ['-f','docx','-t','markdown','-o','markdown.md'];
// Set your callback function
const execute_if_error = (err, result) => {
if (err) {
console.error('An error occured: ',err);
}
// For output to files, the 'result' will be a boolean 'true'.
// Otherwise, the converted value will be returned.
console.log(result);
return result;
};
// Call pandoc
nodePandoc(src, args, callback);
}
fromIpfsHash = () => {
hash = program.fromIpfsHash;
ipfs.get(hash).then(retObj => {
console.log("File Added successfully")
var hash = retObj[0]["hash"];
var bn = ipfsHashtoBN(hash)
var bn_ = bnto2uint(bn)
var bn1 = bn_[0]
var bn2 = bn_[1]
console.log(chalk.bold.green("adding " + hash + " to ODH."))
addHashToHashBase(hash)
ipfs.add(fs.readFileSync(hashesBase)).then(retObj => {
var hash2 = retObj[0]["hash"];
var bn = ipfsHashtoBN(hash2)
var bn_ = bnto2uint(bn)
var bn1 = bn_[0]
var bn2 = bn_[1]
return contract.methods.set(bn1, bn2).send({from:account, value:cost})
})
})
}
const deletionRequest = (hash) => {
var config = loadConfig();
bin = config.code4;
abi = config.abi4;
account = config.account;
contract = new web3.eth.Contract(abi);
contract.options.address = config.address4;
var bn = ipfsHashtoBN(hash)
var bn_ = bnto2uint(bn)
var bn1 = bn_[0]
var bn2 = bn_[1]
web3.eth.getAccounts().then(accounts => {
contract.methods.isPending().call().then(pending => {
console.log(pending)
if (!pending)
contract.methods.setRequest(bn1, bn2)
.send({from:account, value:cost})
.on('receipt', inf => {
console.log(chalk.bold.blue('[ ! ]'), "Request successfully registered.");
})
else {
console.log(chalk.bold.red('[ ! ]'),"Sorry there is already one pending request");
}
})
})
}
// It basicaly remove uneeded configuration files from
// the conf directory.
// That happens often while you have deployed multiple
// instance of a collection of smart contracts.
const reset = () => {
console.log(chalk.bold.green("[ ! ]"), "Configuration reseted successfully.")
console.log(chalk.bold.green("[ ! ]"), "You may need to setup the network before further developement")
const os = require("os");
const fs = require("fs");
const configFile = "~/.config/odh/bc";
try {
fs.rmdirSync(configFile);
} catch (err) {
console.log(chalk.bold.red("[ ! ]"), "An error occured from the data.")
console.log(err)
}
console.log(chalk.bold.green("[ ! ]"), "Configuration reseted successfully.")
}
const revokeReq = (hash) => {
var config = loadConfig();
bin = config.code4;
abi = config.abi4;
account = config.account;
contract = new web3.eth.Contract(abi);
contract.options.address = config.address4;
web3.eth.getAccounts().then(accounts => {
contract.methods.isPending().call().then(value => {
if (value) {
contract.methods.stopReq()
.send({from:account, value:cost})
.on('receipt', inf => {
console.log(inf)
})
} else {
console.log("[ * ] There is no registered request.")
}
})
})
}
const votingForDeletion = () => {
const config = loadConfig();
account = config.account;
const deletionReqContract = new web3.eth.Contract(config.abi4);
deletionReqContract.options.address = config.address4;
const votingContract = new web3.eth.Contract(config.abi3);
votingContract.options.address = config.address3;
let deletionHash;
// stop if the request is not pending
// extract deletion hash from the blockchain
//const deletionHash;
web3.eth.getAccounts().then(accounts => {
deletionReqContract.methods.getHash().call().then(res => {
console.log(res)
})
})
return;
// console.log("Do you really want to remove the file from the network? ")
// console.log("You can still inspect the file before voting")
// console.log("File Hash: ", chalk.bold.green(deletionHash))
// co(function *() {
// const vote = yield prompt("Your choice [Yes or No]: ");
// do {
// console.log("Please answer yes or no")
// } while (vote.toLowerCase() != "yes" || vote.toLowerCase() != "no");
// const choice = vote.toLowerCase() == "yes";
// if (choice) {
// console.log("You choose to delete the file")
// votingContract.methods.vote(choice);
// } else {
// console.log("You choose to keep the file")
// votingContract.methods.vote(choice);
// console.log("Done!")
//
// })
}
const setup = () => {
if (fs.existsSync(configFileName)) {
var content = fs.readFileSync(configFileName);
if (content.toString()) {
console.log("Contracts already deployed");
console.log("Remove .conf.json if yout want to restart the deployement");
}
return;
}
const solc = require('solc');
console.log(chalk.bold.yellow('[ * ]'),"Compiling the contract");
source = fs.readFileSync('./contracts/SimpleStorage.sol', 'UTF-8');
compiled = solc.compile(source);
bin = compiled.contracts[':SyncContract'].bytecode;
contracts = compiled.contracts;
abi = JSON.parse(compiled.contracts[':SyncContract'].interface);
contract = new web3.eth.Contract(abi);
bin2 = compiled.contracts[':Ownership'].bytecode;
abi2 = JSON.parse(compiled.contracts[':Ownership'].interface);
contract2 = new web3.eth.Contract(abi2);
bin3 = compiled.contracts[':Voting'].bytecode;
abi3 = JSON.parse(compiled.contracts[':Voting'].interface);
contract3 = new web3.eth.Contract(abi3);
bin4 = compiled.contracts[':DeletionRequest'].bytecode;
abi4 = JSON.parse(compiled.contracts[':DeletionRequest'].interface);
contract4 = new web3.eth.Contract(abi4);
console.log(chalk.bold.yellow('[ * ]'),"Compilation finished");
web3.eth.getAccounts().then(accounts => {
console.log(chalk.bold.blue('[ * ]'),'Accounts list: ');
console.log(accounts)
web3.eth.coinbase = accounts[0];
account = accounts[0];
console.log(account)
return web3.eth.getBalance(account);
}).then(balance => {
console.log(balance)
co(function *() {
var password = yield prompt.password("ethereum account password: ")
web3.eth.personal.unlockAccount(account, password)
.then(result => {
console.log(chalk.bold.blue('[ * ]'), '+> Ready to deploy SyncContract contract');
contract.deploy({
data: '0x'+bin,
arguments: []
})
.send({
from: account,
gas: gas
})
.on('receipt', receipt => {
console.log(chalk.bold.yellow('[ ! ]'),"+> Contract sucessfully deployed at: ", chalk.bold.green(`${receipt.contractAddress}`));
address = receipt.contractAddress;
web3.eth.personal.unlockAccount(account, password)
.then(result => {
console.log(chalk.bold.blue('[ * ]'), '+> Ready to deploy the Ownership contract');
contract2.deploy({
data: '0x'+bin2,
arguments: []
})
.send({
from: account,
gas: gas
})
.on('receipt', receipt => {
console.log(chalk.bold.yellow('[ ! ]'),"+> Contract sucessfully deployed at: ", chalk.bold.green(`${receipt.contractAddress}`));
address2 = receipt.contractAddress;
web3.eth.personal.unlockAccount(account, password)
.then(result => {
console.log(chalk.bold.blue('[ * ]'), '+> Ready to deploy the Voting contract');
contract3.deploy({
data: '0x'+bin3,
arguments: []
})
.send({
from: account,
gas: gas
})
.on('receipt', receipt => {
console.log(chalk.bold.yellow('[ ! ]'),"+> Contract sucessfully deployed at: ", chalk.bold.green(`${receipt.contractAddress}`));
address3 = receipt.contractAddress;
web3.eth.personal.unlockAccount(account, password)
.then(result => {
console.log(chalk.bold.blue('[ * ]'), '+> Ready to deploy the DeletionRequest contract');
contract4.deploy({
data: '0x'+bin4,
arguments: []
})
.send({
from: account,
gas: gas
})
.on('receipt', receipt => {
console.log(chalk.bold.yellow('[ ! ]'),"+> Contract sucessfully deployed at: ", chalk.bold.green(`${receipt.contractAddress}`));
configOptions = {
code: bin,
abi: abi,
address: address,
code2: bin2,
abi2: abi2,
address2: address2,
code3: bin3,
abi3: abi3,
address3: address3,
code4: bin4,
abi4: abi4,
address4: receipt.contractAddress,
account:account,
}
var conf = fs.openSync(configFileName, "w");
fs.writeFileSync(conf, JSON.stringify(configOptions));
fs.closeSync(conf);
console.log(chalk.bold.yellow('[ ! ]'), "Network setup terminated finished.");
});
}, error => {
console.log(chalk.bold.red('[ ? ]'),`***** contractApi - account unlock error - ${error}`);
});
});
}, error => {
console.log(chalk.bold.red('[ ? ]'),`***** contractApi - account unlock error - ${error}`);
});
})
});
}, error => {
console.log(chalk.bold.red('[ ? ]'),`***** contractApi - account unlock error - ${error}`);
});
});
}, error => {
console.log(chalk.bold.red('[ ? ]'),`***** contractApi - account unlock error - ${error}`);
});
})
}
loadConfig = () => JSON.parse(fs.readFileSync(configFileName));
/*
This ownership stuff is the source of many lawsuite cases in the scientific
reasearch realm. It's even an issue for publishing and authorship related activities
like books publishers and so on.
But what if an idea with all of its mutations aretracked in a kinda zero-knowledge way.
An individual will be able to proof under certain assumptions that he is the author of
of sequences of bytes through this breakthrough way of managing distributed data base through
timestamp-based and proof-of-{work, stake} consensus mechanism.
The set of assumption used to achieve such a thing is pretty narrow, they are namely:
- The data submited to the networks are inserted into block and chained together with
the hash of the previous block execept of course the first block (genesis node); in
that case the rule is that to be considered as the member of the network you *must*
use the same genesis block with other nodes of the network.
- When a block is chained with others it's impossible to change it without changing
the hash of that block and the hash of the merkle root.
- blocks are timestamped so if a block is chained at a certain time it is a proof that,
it hash been the data inside it had been inserted at that time prior to the argument
that the blockchain is immutable.
Therefore we simply need to insert the file itself but this solution is useless
because the hash of the file is sufficient for our proof and also that hashes are fit
perfectly with our zero-knowledge context. We will also need to insert the hash of certain
informations about the author like (name, birthday, city, research field)
*/
const ownershipRegistering = () => {
var config = loadConfig();
bin = config.code2;
abi = config.abi2;
account = config.account;
contract = new web3.eth.Contract(abi);
contract.options.address = config.address2;
try {
const fileName = program.owning;
const buffer = fs.readFileSync(fileName);
// co(function *() {
// var name = yield prompt("Your Name: ")
// var birthday = yield prompt("birthday: ")
ipfs.add(buffer).then(retObj => {
var hash = retObj[0]["hash"];
var bn_ = bnto2uint(ipfsHashtoBN(hash))
var bn1 = bn_[0]
var bn2 = bn_[1]
ipfs.pin.add(hash).then(inf => {
console.log(hash)
contract.methods.setOwnership(bn1, bn2)
.send({from:account, value:cost})
.on('receipt', arg => {
console.log(arg)
console.log("Ownership claim registered successfully.")
console.log("File hash: ", inf[0].hash, "Date ", new Date())
return;
});
return;
}).catch(err => {
console.log(err)
console.log("Unable to register the file")
return;
})
}).catch(err => {
console.log("The ipfs daemon in not running");
return;
})
// });
} catch (error) {
console.log(chalk.bold.red("[ ! ]"), "Unable to open the " + program.owning);
}
}
/*
To check an ownership we will need all the data previously inserted
(in the ownership registering function), extracting them and then
comparing them.
Later we will make the probalistic nature of the proof less elusive.
The probalistic nature
*/
const fetch = () => {
ipfs.get(program.fetch).then(inf => {
var buffer = inf[0].content;
console.log(buffer)
console.log("Writing ", program.fetch, "to the current directory...");
var file = fs.openSync(program.fetch, "w");
fs.writeFileSync(file, buffer);
console.log("done..")
})
}
const lauchWebui = () => {
const express = require('express')
const app = express()
app.use(express.static(__dirname + '/webui/'));
app.get('/', (req, res) => res.render('index.html'))
app.listen(3000, () => console.log('Server listening on port 3000!'))
}
const ownershipClaim = (fileName) => {
var config = loadConfig();
bin = config.code2;
abi = config.abi2;
account = config.account;
contract = new web3.eth.Contract(abi);
contract.options.address = config.address2;
const buffer = fs.readFileSync(fileName);
ipfs.add(buffer).then(retObj => {
var submitedHash = retObj[0]["hash"];
console.log("SUBMITED HASH ", submitedHash)
contract.methods.getOwnersList().call().then(t => {
console.log(t);
var fst = web3.utils.toBN(t["h"]);
var snd = web3.utils.toBN(t["h_"]);
var registeredHash = fromBNtoIpfs(fst) + fromBNtoIpfs(snd);
console.log("REGISTERED HASH: ", registeredHash)
if (submitedHash == registeredHash) {
console.log(chalk.bold.green("[ ! ] YOU ARE THE OWNER OF THE FILE"))
} else {
console.log(chalk.bold.red("[ ! ] YOU ARE **NOT** THE OWNER OF THE FILE"))
}
})
})
}
loadHashesBase = () => {
if (!fs.existsSync(hashesBase)) {
return ''
}
return fs.readFileSync(hashesBase).toString().split('\n')
}
addHashToHashBase = (hash) => {
hashes = loadHashesBase();
if (!hashes)
hashes = []
hashes.push(hash);
var theFile = fs.openSync(hashesBase, "w");
fs.writeFileSync(theFile, hashes.join("\n"))
fs.closeSync(theFile)
}
removeHashFromHashBase = (hash) => {
hashes = loadHashesBase();
hashes.remove(hash);
var theFile = fs.openSync(hashesBase, "w");
fs.writeFileSync(theFile,hashes.join("\n"))
fs.closeSync(theFile)
}
/*
The synchronization algorithm is pretty straightforward.
The sync multihash is stored in the ODH blockchain and managed by a smart contract.
The algorithm starts by extracting that hash from the blockchain.
Perform the ipfs-get operation from that hash then extract a set of new hashes:
then map ipfs-get to all of them.
*/
syncWithPeers = () => {
var config = loadConfig();
bin = config.code;
abi = config.abi;
account = config.account;
contract = new web3.eth.Contract(abi);
contract.options.address = config.address;
console.log("Synchronization with peers is starting:")
web3.eth.getAccounts().then(accounts => {
contract.methods.get().call().then(t => {
var fst = web3.utils.toBN(t["0"]);
var snd = web3.utils.toBN(t["1"]);
var hash = fromBNtoIpfs(fst) + fromBNtoIpfs(snd);
console.log(hash)
ipfs.get(hash).then((obj) => {
hashes = obj[0].content.toString().split('\n');
for(var j in hashes) {
ipfs.get(hashes[j]).then(z => {
var s = z[0].path;
console.log(chalk.bold.blue("[ ! ]"),s, "downloaded successfully.")
})
}
})
});
})
}
fileInsertion = () => {
console.log("Before the file insertion, we need first to Synchronize with peers")
showPeers()
//syncWithPeers()
var config = loadConfig();
bin = config.code;
abi = config.abi;
account = config.account;
contract = new web3.eth.Contract(abi);
contract.options.address = config.address;
const isLink = program.add.match(/^http|^ftp/)
console.log("adding ", program.add);
const buffer = fs.readFileSync(program.add);
ipfs.add(buffer).then(retObj => {
var hash = retObj[0].hash;
console.log(chalk.bold.green("adding " + hash + " to ODH."))
addHashToHashBase(hash)
ipfs.add(fs.readFileSync(hashesBase)).then(retObj => {
var hash2 = retObj[0]["hash"];
var bn = ipfsHashtoBN(hash2)
var bn_ = bnto2uint(bn)
var bn1 = bn_[0]
var bn2 = bn_[1]
console.log(bn1, bn2)
return contract.methods.set(bn1, bn2).send({from:account, value:cost}).catch(err => {
console.log(err)
})
})
}).catch(err => {
console.log(chalk.bold.red("[ ? ]"), " File insertion failed");
console.log(chalk.bold.red("[ ? ]"), " The IPFS daemon is not running");
console.log(err);
});
}
listFiles = () => {
console.log(loadHashesBase())
}
remoteAddFromLink = () => {
var link = program.addRemote;
ipfs.util.addFromURL(link).then(v => {
var hash = v[0].hash
var bn = ipfsHashtoBN(hash)
var bn_ = bnto2uint(bn)
var bn1 = bn_[0]
var bn2 = bn_[1]
// h1 = hash.slice(0, hash.length/2)
// h2 = hash.slice(hash.length/2, hash.length)
console.log(chalk.bold.green("adding " + hash + " to ODH."))
// h1_x = web3.utils.fromAscii(h1)
// h2_x = web3.utils.fromAscii(h2)
// console.log("h1 = (%s, %s) et h2 = (%s, %s)", h1_x, web3.utils.toUtf8(h1_x), h2_x, web3.utils.toUtf8(h2_x))
// contract.methods.set(h1_x, h2_x).call({from:account});
addHashToHashBase(hash)
ipfs.add(fs.readFileSync(hashesBase)).then(retObj => {
var hash2 = retObj[0]["hash"];
var bn = ipfsHashtoBN(hash2)
var bn_ = bnto2uint(bn)
var bn1 = bn_[0]
var bn2 = bn_[1]
return contract.methods.set(bn1, bn2).send({from:account, value:cost})
});
console.log(chalk.bold.blue('[ ! ] ', link, "Added successfully: ", hash))
})
}
const showPeers = () => {
ipfs.swarm.peers().then(peersList => {
for(var j in peersList) {
console.log(chalk.bold.yellow(peersList[j].addr.toString()))
}
}).catch(err => {
console.log(chalk.bold.red('[ ! ]'), "The IPFS daemon is not running");
})
}
if (program.listFiles) {
listFiles()
// ipfs.pin.ls().then(files => {
// for(var idx in files) {
// //console.log(files[idx]["hash"])
// }
// });
}
if (program.add) {
fileInsertion();
}
if (program.fromIpfsHash) {
fileInsertion();
}
if (program.setup) {
setup();
}
if (program.sync) {
syncWithPeers()
}
if (program.fromIpfsHash) {
fromIpfsHash();
}
if (program.peers) {
showPeers()
}
if (program.id) {
console.log(chalk.bold.blue('[ ! ]'), "USER INFORMATIONS")
ipfs.id().then(inf => {
console.log("USER ID:", inf.id)
console.log("Protocol Version:", inf.protocolVersion)
console.log("Public key: ", inf.publicKey, "\n")
console.log("Addresses Attached to ", inf.id, "\n")
for(var k in inf.addresses)
console.log(inf.addresses[k])
})
}
if (program.fetch) {
fetch()
}
if (program.author) {
console.log("(c) MOKTAR ALHASAPI BAVA <moktaralhasapi@gmail.com>");
}
if (program.webui) {
lauchWebui()
}
if (program.owning) {
ownershipRegistering()
}
if(program.claimOfOwnership) {
ownershipClaim(program.claimOfOwnership);
}
if (program.deletionReq) {
deletionRequest(program.deletionReq)
}
if (program.revoqueCurrentReq) {
var currentHash = program.revoqueCurrentReq;
revokeReq(currentHash)
}
if (program.voteForDeletion) {
votingForDeletion()
}
if (program.reset) {
reset();
}