-
Notifications
You must be signed in to change notification settings - Fork 0
/
nbc
executable file
·236 lines (182 loc) · 6.36 KB
/
nbc
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
#!/usr/bin/env python
import sys
import os
import subprocess
import requests
import time
PIDS_FILE = 'logs/running.pids.log'
BTS = 'http://localhost:5000'
def run(cmd, logfile):
'''
Run the cmd and output to the logfile, returns the ret_code, pid
'''
logfile = open(logfile, 'w')
err = open(os.devnull, 'w')
proc = subprocess.Popen(cmd.split(),
universal_newlines=True,
stdout=logfile,
stderr=err)
return proc.pid
def start():
if len(sys.argv) != 3:
print('Usage: ./nbc start <n>')
return
nodes = sys.argv[2]
pids = open(PIDS_FILE, 'w')
# Start the bootstrapper
cmd = 'python rest.py -p 5000 -b -n ' + nodes
pid = run(cmd, 'logs/n0.log')
print('---------------------- Setting up the Nodes ----------------------')
print('Started Bootstrapper | PID: ' + str(pid))
pids.write('bootstrapper: ' + str(pid) + '\n')
# Make sure the bootstrap has been successfully started
time.sleep(2)
# All the nodes must register themselves at the Bootstrap Node
for node in range(int(nodes))[1:]:
port = str(5000 + node)
pid = run('python rest.py -p ' + port, 'logs/n' + str(node) + '.log')
# Log
print('\nStarted Miner | pid: ' + str(pid))
pids.write('node' + str(node) + ': ' + str(pid) + '\n')
# Wait for the node to register
time.sleep(1.5)
# Then the boostrap node must inform everyone about the networks structure
resp = requests.get(BTS + '/broadcast-ring').json()
print(resp)
print()
print('------------------------------------------------------------------')
print('------------------ Sending Initial Transactions ------------------')
time.sleep(1)
# The bootstrapper creates the first n initial transactions
for n in range(int(nodes))[1:]:
print('\nBroadcasting initial Transaction for Node ' + str(n))
requests.post(BTS + '/create-transaction', json={
'id': n,
'value': 100,
})
print()
print('-------------- Bootstrapping Completed Succesfully! --------------')
def stop():
'''
Delete all the processes that start from the 'start' step
'''
pids_f = open(PIDS_FILE, 'r')
pids = [pid.split(": ")[-1] for pid in pids_f.read().split('\n')]
for pid in pids:
if pid != '':
run("kill -KILL " + pid, 'stop.log')
def transaction():
'''
Create a new transaction from A to B with Value NBCs
'''
if len(sys.argv) != 5:
print('Usage: ./nbc t <id-from> <id-to> <coins>')
return
src = int(sys.argv[2])
src_addr = 'http://localhost:' + str(5000 + src) + '/create-transaction'
dst = int(sys.argv[3])
dst_id = 'localhost:' + str(5000 + dst)
value = int(sys.argv[4])
# POST the data to the Server's route
requests.post(src_addr, json={'id': dst, 'value': value})
print('Send: {} NBCs from [{}] -> [{}]'.
format(value, 'localhost:' + str(5000 + src), dst_id))
def transaction_file():
'''
Create a new transaction from A to B with Value NBCs
'''
if len(sys.argv) != 4:
print('Usage: ./nbc tf <id> <file>')
return
src = int(sys.argv[2])
src_id = 'localhost:' + str(5000 + src)
ts_file = open(sys.argv[3], 'r')
ts = [t for t in ts_file.read().split('\n')]
# Send each transaction
for t in ts:
if t == '':
return
dst = int(t.split()[0].split('id')[-1])
dst_id = 'localhost:' + str(5000 + dst)
val = int(t.split()[-1])
print('\nSend: {} NBCs from [{}] -> [{}]'.
format(val, src_id, dst_id))
requests.post('http://' + src_id + '/create-transaction', json={'id': dst, 'value': val})
time.sleep(1)
def balance():
'''
Check how many NBCs this user has
'''
if len(sys.argv) != 3:
print('Usage: ./nbc b <n>')
return
src = int(sys.argv[2])
src_id = 'localhost:' + str(5000 + src)
val = requests.get('http://' + src_id + '/balance').json()
print('User: ' + src_id)
print('Balance: ' + str(val['balance']))
def balances():
'''
Check how many NBCs every user has
'''
if len(sys.argv) != 3:
print('Usage: ./nbc bs <n>')
return
nodes = int(sys.argv[2])
total = 0
for n in range(nodes):
src_id = 'localhost:' + str(5000 + n)
val = requests.get('http://' + src_id + '/balance').json()
print('User: ' + src_id)
print('Balance: ' + str(val['balance']))
print()
total += val['balance']
print()
print('Total: {} NBCs in the BlockChain'.format(total))
def last_transactions():
'''
Get the transactions in the last block
'''
if len(sys.argv) != 3:
print('Usage: ./nbc ts <n>')
return
src = int(sys.argv[2])
ts = requests.get('http://localhost:' + str(5000 + src) + '/last-transactions').json()
for t in ts['transactions']:
print('Node {} -> Node {}: {} NBCs'.format(t['src'], t['dst'], t['val']))
def help():
print('-------------------- Welcome to NoobCoin CLI! --------------------')
print()
print('Available commands:')
print(' start <n> Starts n Clients (Bootstrap included)')
print(' stop Stops all started Clients')
print(' t <idA> <idB> <val> Create a Transaction from A -> B with val')
print(' tf <id> <file> Apply transactions file from Node <id>')
print(' b <id> Get Node\'s balance')
print(' bs <n> Get the balance from all Nodes')
print(' ts <id> Get the Transactions in the last block from Node <id>')
print()
if __name__ == "__main__":
if len(sys.argv) == 1:
print('Available commands: \n' +
' start <n>: Start the Chain with <n> nodes')
exit()
cmd = sys.argv[1]
if cmd == 'start':
start()
elif cmd == 'stop':
stop()
elif cmd == 't':
transaction()
elif cmd == 'tf':
transaction_file()
elif cmd == 'b' or cmd == 'balance':
balance()
elif cmd == 'bs' or cmd == 'balances':
balances()
elif cmd == 'ts' or cmd == 'transactions':
last_transactions()
elif cmd == 'h' or cmd == 'help':
help()
else:
print('Command not supported.')