forked from 0xs34n/blockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
108 lines (98 loc) · 2.33 KB
/
cli.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
const P2p = require("./P2p.js");
const Blockchain = require("./Blockchain.js");
const blockchain = new Blockchain();
const p2p = new P2p(blockchain);
function cli(vorpal) {
vorpal
.use(welcome)
.use(connectCommand)
.use(discoverCommand)
.use(blockchainCommand)
.use(peersCommand)
.use(mineCommand)
.use(openCommand)
.delimiter('blockchain →')
.show()
}
module.exports = cli;
// COMMANDS
function welcome(vorpal) {
vorpal.log("Welcome to Blockchain CLI!");
vorpal.exec("help");
}
function connectCommand(vorpal) {
vorpal
.command('connect <host> <port>', "Connect to a new peer. Eg: connect localhost 2727")
.alias('c')
.action(function(args, callback) {
if(args.host && args.port) {
try {
p2p.connectToPeer(args.host, args.port);
} catch(err) {
this.log(err);
}
}
callback();
})
}
function discoverCommand(vorpal) {
vorpal
.command('discover', 'Discover new peers from your connected peers.')
.alias('d')
.action(function(args, callback) {
try {
p2p.discoverPeers();
} catch(err) {
this.log(err);
}
callback();
})
}
function blockchainCommand(vorpal) {
vorpal
.command('blockchain', 'See the current state of the blockchain.')
.alias('bc')
.action(function(args, callback) {
this.log(blockchain)
callback();
})
}
function peersCommand(vorpal) {
vorpal
.command('peers', 'Get the list of connected peers.')
.alias('p')
.action(function(args, callback) {
p2p.peers.forEach(peer => {
this.log(`${peer.pxpPeer.socket._host} \n`)
}, this)
callback();
})
}
function mineCommand(vorpal) {
vorpal
.command('mine <data>', 'Mine a new block. Eg: mine hello!')
.alias('m')
.action(function(args, callback) {
if (args.data) {
blockchain.mine(args.data);
p2p.broadcastLatest();
}
callback();
})
}
function openCommand(vorpal) {
vorpal
.command('open <port>', 'Open port to accept incoming connections. Eg: open 2727')
.alias('o')
.action(function(args, callback) {
if (args.port) {
if(typeof args.port === 'number') {
p2p.startServer(args.port);
this.log(`Listening to peers on ${args.port}`);
} else {
this.log(`Invalid port!`);
}
}
callback();
})
}