-
Notifications
You must be signed in to change notification settings - Fork 11
/
p2p.py
250 lines (211 loc) · 9.58 KB
/
p2p.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
#-*- coding: utf-8 -*-
import sys, json, requests, django ,os ,base64, collections,hashlib, math, schedule, time
from django.utils.encoding import smart_str
from ecdsa import SigningKey, SECP256k1, NIST384p, BadSignatureError, VerifyingKey
from twisted.internet import reactor
from twisted.python import log
from twisted.web.server import Site
from twisted.web.static import File
import netifaces as ni
from cloudbank.wsgi import application as wsgi_handler
import threading
import queue as Queue
django.setup()
from core.models import transaction
from cloudbank.utils import instantwallet, generate_wallet_from_pkey, generate_pubkey_from_prikey, checkreward
from autobahn.twisted.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
from autobahn.twisted.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
def addnewnode(host):
ws = "ws://{}:9000".format(host)
#factory = WebSocketClientFactory(u"ws://127.0.0.1:9000")
factory = WebSocketClientFactory(ws)
factory.protocol = MyClientProtocol
reactor.connectTCP(host, 9000, factory)
#Yeni bir kullanıcı servara bağlandığı zaman bu kısım çalışır.
class BroadcastServerProtocol(WebSocketServerProtocol):
def onOpen(self):
self.factory.register(self)
def onMessage(self, payload, isBinary):
print(type(payload))
print(payload)
print(isBinary)
if not isBinary:
print(type(payload))
#omg getting from server and thats already binary...
myjson = json.loads(payload.decode('utf8'))
if myjson["server"]:
print("that message came from server")
addnewnode(myjson["host"])
else:
print(myjson["message"])
myjson["host"] = ip
mybinarydata = json.dumps(myjson)
self.factory.broadcast(mybinarydata.encode('utf8'))
else:
myjson = json.loads(payload)
if myjson["server"]:
print("that message came from server")
addnewnode(myjson["host"])
else:
print(myjson["message"])
myjson["host"] = ip
myjson = json.dumps(myjson)
self.factory.broadcast(myjson)
def connectionLost(self, reason):
WebSocketServerProtocol.connectionLost(self, reason)
self.factory.unregister(self)
#Kendi içindeki clientlere yayın yapar.
clients = []
class BroadcastServerFactory(WebSocketServerFactory):
#self.broadcast serverda yayn yapar..
def __init__(self, url):
WebSocketServerFactory.__init__(self, url)
def register(self, client):
if client not in clients:
if client not in clients:
print("registered client {}".format(client.peer))
print(clients)
tcp, host, port = client.peer.split(":")
print(host)
clients.append(client)
def unregister(self, client):
if client in clients:
print("unregistered client {}".format(client.peer))
clients.remove(client)
@classmethod
def broadcast(self, msg):
for c in clients:
print(type(msg))
print(type(msg))
c.sendMessage(msg)
print("messaj disaridan aldim {}".format(c.peer))
class MyClientProtocol(WebSocketClientProtocol):
def onConnect(self, response):
print("33 'den servera connected': {0}".format(response.peer))
def onOpen(self):
print("WebSocket connection open.")
#kullanıcı servera ilk bağlandığı zaman bu mesaj gönderilir.
def hello():
#self.sendMessage(u"Hello, from 138.68.94.33 !".encode('utf8'))
data = {}
data["server"] = True
data["host"] = ip
mybinarydata = json.dumps(data)
self.sendMessage(mybinarydata.encode('utf8'))
hello()
def onMessage(self, payload, isBinary):
data = {}
print("onmessage")
allify = {}
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
payloaded = json.loads(payload.decode('utf-8'))
print(payloaded["host"])
if str(payloaded["host"]) == str(ip):
print("bu zaten sensin")
else:
payloaded = json.loads(payload.decode('utf-8'))
if 'sender' in payloaded:
data['sender'] = str(payloaded["sender"]) #1
data['receiver'] = str(payloaded["receiver"]) #2
data['previous_hash'] = str(transaction.objects.all().last().blockhash) #3
data['amount'] = str(payloaded["amount"]) #4
data['timestamp'] = str(payloaded["timestamp"]) #5
data["nonce"] = str(payloaded["nonce"])
data = collections.OrderedDict(sorted(data.items()))
datashash = hashlib.sha256(json.dumps(data).encode('utf-8')).hexdigest()
sig = json.loads(payloaded["P2PKH"])
print("datahashhere", datashash.encode('utf-8'))
print("sigbyte is here", sig)
print("sende weas here", payloaded["sender"])
wllt = generate_wallet_from_pkey(payloaded["sender"])
if(sig == "reward"):
newtrans = transaction(sender=payloaded["sender"],
senderwallet=wllt,
receiver=payloaded["receiver"],
prevblockhash=transaction.objects.all().last().blockhash,
blockhash=payloaded["blockhash"],
amount=payloaded["amount"],
nonce=payloaded["nonce"],
first_timestamp=payloaded["timestamp"],
P2PKH=payloaded["P2PKH"],
verification=True
).save()
else:
try:
sigbyte = bytes.fromhex(sig)
vk = VerifyingKey.from_string(bytes.fromhex(payloaded["sender"]), curve=SECP256k1)
tt = vk.verify(sigbyte, datashash.encode('utf-8')) # True
except BadSignatureError:
print("unbelieveable")
data["response"] = "unbelieveable"
newtrans = transaction(sender=payloaded["sender"],
senderwallet=wllt,
receiver=payloaded["receiver"],
prevblockhash=transaction.objects.all().last().blockhash,
blockhash=payloaded["blockhash"],
amount=payloaded["amount"],
nonce=payloaded["nonce"],
first_timestamp=payloaded["timestamp"],
P2PKH=payloaded["P2PKH"],
verification=False
).save()
print("badsignature")
newtrans = transaction(sender=payloaded["sender"],
senderwallet=wllt,
receiver=payloaded["receiver"],
prevblockhash=transaction.objects.all().last().blockhash,
blockhash=payloaded["blockhash"],
amount=payloaded["amount"],
nonce=payloaded["nonce"],
first_timestamp=payloaded["timestamp"],
P2PKH=payloaded["P2PKH"],
verification=True
).save()
else:
print("other message")
BroadcastServerFactory.broadcast(payload)
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
def byebye():
self.sendMessage(u"Good byee, from 138.68.94.33 !".encode('utf8'))
byebye()
def syncfirst():
r = requests.get('http://159.89.197.53/api/v1/alltransactions/')
alltrans = r.json()
for x in alltrans["alltestsarecomplated"]:
try:
mytransactions = transaction.objects.get(blockhash=x["blockhash"])
except transaction.DoesNotExist:
newtrans = transaction(sender=x["sender"],
senderwallet=x["senderwallet"],
receiver=x["receiver"],
prevblockhash=x["prevblockhash"],
blockhash=x["blockhash"],
amount=x["amount"],
nonce=x["nonce"],
first_timestamp=x["first_timestamp"],
P2PKH=x["P2PKH"],
verification=x["verification"])
newtrans.save()
print("everyting is up-da-te")
if __name__ == '__main__':
#log.startLogging(sys.stdout)
syncfirst()
ServerFactory = BroadcastServerFactory
factory = ServerFactory(u"ws://127.0.0.1:9000")
factory.protocol = BroadcastServerProtocol
reactor.listenTCP(9000, factory)
factory = WebSocketClientFactory(u"ws://159.89.197.53:9000")
factory.protocol = MyClientProtocol
reactor.connectTCP(u"159.89.197.53", 9000, factory)
reactor.run()