forked from LiuBoyu/blockchain
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rpc.py
91 lines (72 loc) · 2.49 KB
/
rpc.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
# coding:utf-8
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.client import ServerProxy
from node import get_nodes, add_node
from database import BlockChainDB, UnTransactionDB, TransactionDB
from lib.common import cprint
server = None
PORT = 8301
class RpcServer():
def __init__(self,server):
self.server = server
def ping(self):
return True
def get_blockchain(self):
bcdb = BlockChainDB()
return bcdb.find_all()
def new_block(self,block):
cprint(__name__, block)
BlockChainDB().insert(block)
UnTransactionDB().clear()
cprint('INFO',"Receive new block.")
return True
def get_transactions(self):
tdb = TransactionDB()
return tdb.find_all()
def new_untransaction(self,untx):
cprint(__name__,untx)
UnTransactionDB().insert(untx)
cprint('INFO',"Receive new unchecked transaction.")
return True
def blocked_transactions(self,txs):
TransactionDB().write(txs)
cprint('INFO',"Receive new blocked transactions.")
return True
def add_node(self, address):
add_node(address)
return True
class RpcClient():
ALLOW_METHOD = ['get_transactions', 'get_blockchain', 'new_block', 'new_untransaction', 'blocked_transactions', 'ping', 'add_node']
def __init__(self, node):
self.node = node
self.client = ServerProxy(node)
def __getattr__(self, name):
def noname(*args, **kw):
if name in self.ALLOW_METHOD:
return getattr(self.client, name)(*args, **kw)
return noname
class BroadCast():
def __getattr__(self, name):
def noname(*args, **kw):
cs = get_clients()
rs = []
for c in cs:
try:
rs.append(getattr(c,name)(*args, **kw))
except ConnectionRefusedError:
cprint('WARN', 'Contact with node %s failed when calling method %s , please check the node.' % (c.node,name))
else:
cprint('INFO', 'Contact with node %s successful calling method %s .' % (c.node,name))
return rs
return noname
def start_server(ip, port=8301):
server = SimpleXMLRPCServer((ip, port))
rpc = RpcServer(server)
server.register_instance(rpc)
server.serve_forever()
def get_clients():
clients = []
nodes = get_nodes()
for node in nodes:
clients.append(RpcClient(node))
return clients