-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmyAttackNode.py
725 lines (546 loc) · 23.7 KB
/
myAttackNode.py
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
from aioconsole import ainput
from myBlockChain import BlockChain
from myRPC import *;
from myRoutingTable import KadTable;
import logging # 引入logging模块
import os.path
#from watchdog.events import *
import time
from myleger import Leger;
class AttackNode(myRPCProtocol):
def __init__(self, ID=None):
super(AttackNode, self).__init__()
if ID is None:
ID = random_id();
self.ID = ID;
self.routingTable = KadTable(self.ID);
self.recallFunctions = self.recordFunctions();
self.BroadCasts = [];
# self.leger = Leger(self.ID);
self.blockchain = None
self.local_addr = None
self.wallet = 0
self.pos = 0
self.hackers=[]
def setLocalAddr(self,local_addr):
self.local_addr = local_addr;
self.initFileCMD()
self.logger = self.init_logger()
self.recordbaseInfo()
def sethackers(self,attack_num):
for i in range(1,attack_num+1):
self.hackers.append("10.0.0.%d" % i)
print(self.hackers)
def recordFunctions(self):
funcs = []
funcs.extend(myRPCProtocol.__dict__.values())
funcs.extend(AttackNode.__dict__.values())
return {
func.funcName: func.recall_function
for func in funcs if hasattr(func, 'funcName')
}
@convert2RPC
def ping(self,peer,peerID):
print(self.ID, "handling ping", peer, peerID)
return (self.ID, peerID)
@convert2RPC
def findNodes(self, peer, peerID):
self.routingTable.add(peerID,peer);
return self.routingTable.getKpeers(peerID);
@convert2RPC
def testBoradCast(self, peer, peerId, args):
print("Recived boardCast message!!!!", peer, peerId, args)
@convert2RPC
def recordTX(self, peer, peerId, transaction):
print("Recived new transaction!!!!", peer, peerId, transaction)
if transaction['id'] not in [x['id'] for x in self.blockchain.current_transactions]:
logging.info("Recived new transaction")
self.blockchain.current_transactions.append(transaction);
logging.info(self.blockchain.current_transactions)
self.recordTXInfo()
@convert2RPC
def recordNewBlock(self, peer, peerId, newBlock):
print("Recived new Block!!!!", peer, peerId, newBlock)
logging.info("Recived new Block")
self.blockchain.stop = True;
self.pos = 0
#TODO 判断新块是否有冲突, 有冲突从其他人拉去区块,否则直接更新
tmp_chain = [x for x in self.blockchain.chain]
tmp_chain.append(newBlock)
if self.blockchain.check_chain(tmp_chain):
self.blockchain.chain.append(newBlock);
else:
print("run resolve_conflicts()!!!")
# loop = asyncio.get_event_loop();
# loop.run_until_complete(self.resolve_conflicts())
asyncio.ensure_future(self.resolve_conflicts())
# self.resolve_conflicts()
IDlist = self.blockchain.getAllTX()
self.blockchain.removeSomeTX(IDlist)
logging.info(self.blockchain.chain)
self.recordBlockInfo()
self.recordTXInfo()
@convert2RPC
def download_peer_blockchain(self, peer, peerID):
# print(self.ID, "downloading blockchain from", peer, peerID)
return self.blockchain
@convert2RPC
def getpos(self, peer, peerID):
# print(self.ID, "downloading blockchain from", peer, peerID)
return self.pos
@convert2RPC
def getwallet(self, peer, peerID):
# print(self.ID, "downloading blockchain from", peer, peerID)
return self.wallet
@asyncio.coroutine
def updateRoutingTable(self, peer):
# self.routingTable.add(self.ID,self)
peers = yield from self.findNodes(peer, self.ID)
for peerID in peers.keys():
self.routingTable.add(peerID, peers[peerID])
# self.routingTable.printTable();
@asyncio.coroutine
def BGPjoin(self):
# print(self.ID, "Pinging ", peer)
print("myIP: ", self.local_addr, " myID: ", self.ID)
try:
yield from self.download_blockchain_all();
except socket.timeout:
print("Could not download blockchain", "BGPNode")
return
try:
tx_id = self.create_transaction(self.blockchain, self.ID, self.ID,
0)
self.logger.info('init get transactinon from miner = ')
self.logger.info(self.blockchain.current_transactions)
self.recordTXInfo()
yield from self.postBoardcast(random_id(), 'recordTX', self.ID,
self.blockchain.current_transactions[-1]);
except socket.timeout:
print("Could not get money from node0", "BGPNode")
return
@asyncio.coroutine
def join(self, peer):
# print(self.ID, "Pinging ", peer)
print("myIP: ",self.local_addr," myID: ",self.ID)
try:
yield from self.ping(peer, self.ID)
except socket.timeout:
print("Could not ping %r", peer)
return
try:
yield from self.updateRoutingTable(peer);
# print("======================print my routing table============================")
# self.routingTable.printTable();
except socket.timeout:
print("Could not updateRoutingTable", peer)
return
try:
yield from self.download_blockchain_all();
except socket.timeout:
print("Could not download blockchain", peer)
return
# 默认启动后找第一个人要钱
# try:
# tx_id = self.create_transaction(self.blockchain, self.routingTable.getPeerIDByIP(peer[0]), self.ID, random.randint(1,10))
# self.logger.info('init get transactinon from miner = ')
# self.logger.info(self.blockchain.current_transactions)
# self.recordTXInfo()
# yield from self.postBoardcast(random_id(), 'recordTX', self.ID, self.blockchain.current_transactions[-1]);
# except socket.timeout:
# print("Could not get money from node0", peer)
# return
@asyncio.coroutine
def getAllPOS(self):
peers = self.routingTable.getNeighborhoods()
all_pos = []
for peerID, peer in peers.items():
try:
pos = yield from self.getpos(peers[peerID], self.ID)
if pos != None:
all_pos.append(pos)
except socket.timeout:
print("Could not download_peer_blockchain", peers[peerID])
return all_pos
@asyncio.coroutine
def download_blockchain_all(self):
peers = self.routingTable.getNeighborhoods()
if len(peers) == 0:
# genesis block
self.blockchain = BlockChain(self.ID)
# self.blockchain.set_logger(self.logger)
self.blockchain.create_genesis_block()
else:
for peerID, peer in peers.items():
try:
receive_blockchain = yield from self.download_peer_blockchain(peers[peerID], self.ID)
self.logger.info('receive blockchain.chain = ')
self.logger.info(receive_blockchain.chain)
if self.blockchain == None:
self.blockchain = receive_blockchain
self.blockchain.set_node_id(self.ID)
# self.blockchain.set_logger(self.logger)
elif len(receive_blockchain.chain) > len(self.blockchain.chain):
self.blockchain = receive_blockchain
self.blockchain.set_node_id(self.ID)
# self.blockchain.set_logger(self.logger)
except socket.timeout:
print("Could not download_peer_blockchain", peers[peerID])
print('current blockchain = ', self.blockchain.chain)
self.logger.info('blockchain.node_id = ' + str(self.blockchain.node_id))
self.logger.info(self.blockchain.chain)
self.recordBlockInfo()
@asyncio.coroutine
def resolve_conflicts(self):
logging.info("In resolve conflicts!")
print("In resolve conflicts!")
peers = self.routingTable.getNeighborhoods()
new_chain = None
# We're only looking for chains longer than ours
self_length = len(self.blockchain.chain)
# Grab and verify the chains from all the nodes in our network
for peerID, peer in peers.items():
try:
receive_blockchain = yield from self.download_peer_blockchain(peers[peerID], self.ID)
chain = receive_blockchain.chain
length = len(chain)
# Check if the length is longer and the chain is valid
# if the blockchain length is 2 block head current blockchain
# TODO test receive blockchain length
print(length," !!!!!! " ,self_length, " ",self.blockchain.check_chain(chain))
if length - 1 > self_length and self.blockchain.check_chain(chain):
self_length = length
new_chain = chain
except socket.timeout:
print("Could not download_peer_blockchain in resolve_conflicts", peers[peerID])
# Replace our chain if we discovered a new, valid chain longer than ours
if new_chain:
self.blockchain.chain = new_chain
self.blockchain.set_node_id(self.ID)
self.logger.info('blockchain.node_id = ' + str(self.blockchain.node_id))
self.logger.info(self.blockchain.chain)
self.recordBlockInfo()
IDlist = self.blockchain.getAllTX()
self.blockchain.removeSomeTX(IDlist)
self.recordTXInfo()
return True
return False
@asyncio.coroutine
def mine(self):
# We run the proof of work algorithm to get the next proof...
last_block = self.blockchain.last_block
last_proof = last_block['proof']
# use proof of work
proof = yield from self.blockchain.proof_of_work(last_proof)
if self.blockchain.stop == True:
return None;
# 给工作量证明的节点提供奖励.
# 发送者为 "0" 表明是新挖出的币
self.blockchain.new_transaction(
sender="0",
recipient=self.ID,
amount=random.randint(1,10),
)
node_id = self.ID
amount = self.wallet
if self.hackers[0] != self.local_addr[0]:
node_id = self.routingTable.getPeerIDByIP(self.hackers[0])
peer = self.routingTable.getPeerByIP(self.hackers[0])
amount = yield from self.getwallet(peer,self.ID)
hackblock = self.blockchain.new_hackblock(proof,node_id,amount)
# Forge the new Block by adding it to the chain
self.blockchain.new_block(proof)
return hackblock
@asyncio.coroutine
def startPOW(self):
while True:
block = yield from self.mine()
if block!=None:
print(self.ID, ' has mined new block ')
self.logger.info('after mining, blockchain = ')
self.logger.info(self.blockchain.chain)
# broadcast new Blcokchain
self.recordBlockInfo()
self.recordTXInfo()
peers = self.routingTable.getNeighborhoods();
for peer_id in peers.keys():
try:
if peers[peer_id][0] in self.hackers:
yield from self.recordNewBlock(peers[peer_id],self.ID,self.blockchain.chain[-1])
else:
yield from self.recordNewBlock(peers[peer_id], self.ID, block)
except socket.timeout:
print("send newblock timeout %r", peers[peer_id])
# yield from self.postBoardcast(random_id(), 'recordNewBlock', self.ID, block, self.blockchain.chain[-1]);
else:
print('This new block has been mined by others')
self.logger.info('This blockchain has been mined by others')
#每当挖完矿或者别人挖到矿时,等待一段时间,等所有消息处理完毕
yield from asyncio.sleep(30)
self.blockchain.stop=False;
def mine_quick(self):
last_block = self.blockchain.last_block
last_proof = last_block['proof']
# use pos (very quick)
proof = self.blockchain.pos(last_proof)
# 给pos的节点提供奖励.
# 发送者为 "0" 表明是新挖出的币
self.blockchain.new_transaction(
sender="0",
recipient=self.ID,
amount=random.randint(1, 10),
)
# Forge the new Block by adding it to the chain
self.blockchain.new_block(proof)
@asyncio.coroutine
def startPOS(self):
print("POS start !!!")
while True:
#没两分钟进行一次pos协议
period = 120
yield from asyncio.sleep(period)
# TODO 暂时简化
self.pos = random.randint(0,self.wallet)
# 等待其他人计算pos值
yield from asyncio.sleep(30)
all_pos = yield from self.getAllPOS()
leader = True
for pos in all_pos:
print(pos," ",self.pos)
if pos>=self.pos:
leader=False
if leader == True:
print(self.ID, ' has mined new block ')
self.mine_quick()
self.logger.info('after mining, blockchain = ')
self.logger.info(self.blockchain.chain)
# broadcast new Blcokchain
self.recordBlockInfo()
self.recordTXInfo()
yield from self.postBoardcast(random_id(), 'recordNewBlock', self.ID, self.blockchain.chain[-1]);
else:
print('This new block has been mined by others')
self.logger.info('This blockchain has been mined by others')
#每当挖完矿或者别人挖到矿时,等待一段时间,等所有消息处理完毕
yield from asyncio.sleep(30)
def create_transaction(self, blockchain, sender, recipient, amount):
# Create a new Transaction
# tx_index = blockchain.new_transaction(sender, recipient, amount)
# return tx_index
if sender != self.ID:
tx_index = blockchain.new_transaction(sender, recipient, amount)
return tx_index
elif sender == self.ID and self.wallet - amount >= 0:
tx_index = blockchain.new_transaction(sender, recipient, amount)
return tx_index
else:
return -1
def init_logger(self):
# 第一步,创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log等级总开关
# 第二步,创建一个handler,用于写入日志文件
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
log_path = os.path.join(cur_path,'Logs',str(self.local_addr[0]))
if not os.path.exists(log_path):
os.mkdir(log_path)
log_name = os.path.join(log_path, str(self.ID) + ".log")
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关
# 第三步,定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
# 第四步,将logger添加到handler里面
logger.addHandler(fh)
return logger
def recordbaseInfo(self):
log_path = os.path.join(cur_path, 'Logs', str(self.local_addr[0]))
if not os.path.exists(log_path):
os.mkdir(log_path)
baseInfo = os.path.join(log_path, "baseInfo")
with open(baseInfo,'w') as f:
f.write(str(self.ID)+"\n")
f.write(str(self.local_addr)+"\n")
def recordTXInfo(self):
log_path = os.path.join(cur_path, 'Logs', str(self.local_addr[0]))
if not os.path.exists(log_path):
os.mkdir(log_path)
TXInfo = os.path.join(log_path, "TXInfo")
save_data(self.blockchain.current_transactions,TXInfo)
def update_wallet(self):
# update wallet value
txs = self.blockchain.get_all_tx()
self.logger.info('txs = ')
self.logger.info(txs)
self.wallet = 0
for tx in txs:
if tx['sender'] ==self.ID:
self.wallet -= tx['amount']
if tx['recipient'] == self.ID:
self.wallet += tx['amount']
# serialize block and wallet
def recordBlockInfo(self):
log_path = os.path.join(cur_path, 'Logs', str(self.local_addr[0]))
if not os.path.exists(log_path):
os.mkdir(log_path)
BlockInfo = os.path.join(log_path, "BlockInfo")
save_data(self.blockchain.chain,BlockInfo)
self.update_wallet()
wallet_info = os.path.join(log_path, "wallet")
save_data(self.wallet,wallet_info)
def initFileCMD(self):
path = os.path.join(cur_path,'CMD')
with open(os.path.join(path,str(self.local_addr[0])), 'w') as f:
f.close();
@asyncio.coroutine
def pingAll(self, peer, peerID):
peers = self.routingTable.getNeighborhoods();
for peerID, peer in peers.keys():
try:
yield from self.ping(peers[peerID], self.ID);
except socket.timeout:
print("pingAll timeout %r", peer)
@asyncio.coroutine
def postBoardcast(self, messageID, funcName, *args):
if messageID not in self.BroadCasts:
self.BroadCasts.append(messageID);
obj = ('broadcast', messageID, funcName, *args)
message = pickle.dumps(obj, protocol=0)
peers = self.routingTable.getNeighborhoods();
for peer in peers.values():
try:
self.transport.sendto(message, peer)
except socket.timeout:
print("transport sendto timeout %r", peer)
#收到的所有请求,更新路由表
# 处理请求
def handleRequest(self, peer, messageID, funcName, args, kwargs):
peerID = args[0];
self.routingTable.add(peerID,peer);
super(AttackNode, self).handleRequest(peer, messageID, funcName, args, kwargs);
# 处理回复
def handleReply(self, peer, messageID, response):
peerID, response = response;
self.routingTable.add(peerID,peer);
super(AttackNode, self).handleReply(peer, messageID, response);
# 处理广播
def handleBroadcast(self, peer, messageID, funcName, *args):
peerID = args[0];
self.routingTable.add(peerID, peer);
if messageID not in self.BroadCasts:
self.BroadCasts.append(messageID);
self.postBoardcast(messageID, funcName, args);
super(AttackNode,self).handleBroadcast(peer, messageID, funcName, *args);
# 处理超时
def handletimeout(self, messageID, peer, args, kwargs):
if messageID in self.requests:
reply = self.requests.pop(messageID);
reply.set_exception(socket.timeout);
peerID = self.routingTable.getPeerIDByIP(peer[0]);
print('remove peerID ',peerID)
self.routingTable.remove(peerID);
# super(AttackNode, self).handletimeout( messageID,peer, args, kwargs);
#=================监听命令行=====================#
async def nodeCommand(self):
while True:
line = await ainput(">>> ")
line = line.strip()
if not line:
continue;
await self.dealCMD(line)
# =================监听文件命令行=====================#
async def fileCommand(self):
while True:
line = self.readFromFile()
if line != None:
line = line.strip()
if len(line) > 0:
await self.dealCMD(line)
self.clearFileCMD()
await asyncio.sleep(2)
def printHelpList(self):
print("==========this is a help list!==========")
def printLog(self):
path = os.path.join(cur_path,'Logs')
with open(os.path.join(path, str(self.ID)+".log"), 'r') as f:
lines = f.readlines()
for line in lines:
print(line)
def clearFileCMD(self):
path = os.path.join(cur_path,'CMD')
with open(os.path.join(path, str(self.local_addr[0])), 'w') as f:
f.close()
def readFromFile(self):
path = os.path.join(cur_path,'CMD')
with open(os.path.join(path,str(self.local_addr[0])),'r') as f:
lines = f.readlines();
if len(lines)>0:
return lines[0].strip();
else:
return None;
async def dealCMD(self,line):
line = line.split();
cmd = line[0];
args = line[1:];
if cmd in ["?", "help"]:
self.printHelpList();
elif cmd in ["id"]:
print("NodeId : ", self.ID);
elif cmd in ["ip"]:
print("<ip,port> ",self.local_addr)
elif cmd in ["showHashTable"]:
self.routingTable.printTable();
elif cmd in ["showlog"]:
self.printLog();
elif cmd in ["ping"]:
IP = args[0];
peer = self.routingTable.getPeerByIP(IP)
if peer != None:
try:
await self.ping(peer, self.ID);
except socket.timeout:
print("Could not ping %r", peer)
return
else:
print("peerIP : ", IP, " not exist!");
elif cmd in ["testBoardCast"]:
try:
await self.postBoardcast(random_id(), 'testBoradCast', self.ID, "Testargs");
except socket.timeout:
print(self.ID, ": could not postBoardcast")
return
elif cmd in ["join"]:
try:
await self.join(("10.0.0.1",9000))
except socket.timeout:
print(self.ID, ": could not join 10.0.0.1")
return
elif cmd in ["mine"]:
self.mine_quick()
# IDlist = [x.id for x in self.blockchain.chain[-1]['transactions']]
# self.blockchain.removeSomeTX(IDlist)
self.logger.info('after mining, blockchain = ')
self.logger.info(self.blockchain.chain)
# broadcast new Blcokchain
self.recordBlockInfo()
self.recordTXInfo()
await self.postBoardcast(random_id(), 'recordNewBlock', self.ID, self.blockchain.chain[-1]);
elif cmd in ["createTx"]:
IP = args[0];
amount = int(args[1])
peerID = self.routingTable.getPeerIDByIP(IP)
if peerID != None:
# check for enough money
tx_id = self.create_transaction(self.blockchain, self.ID, peerID, amount)
if tx_id != -1:
self.logger.info('current transactinon = ')
self.logger.info(self.blockchain.current_transactions)
self.recordTXInfo()
await self.postBoardcast(random_id(), 'recordTX', self.ID, self.blockchain.current_transactions[-1]);
else:
self.logger.info('could not create transaction, wallet < amount')
log_str=str(self.wallet)+' < '+str(amount)
self.logger.info(log_str)
else:
print("no such reciever! peerIP: ", IP)