separated client and server handling into factories. incoming and outgoing connection...
[p2pool.git] / p2pool / p2p.py
1 from __future__ import division
2
3 import random
4 import time
5
6 from twisted.internet import defer, protocol, reactor
7 from twisted.python import log
8
9 import p2pool
10 from p2pool import data as p2pool_data
11 from p2pool.bitcoin import p2p as bitcoin_p2p
12 from p2pool.bitcoin import data as bitcoin_data
13 from p2pool.util import deferral
14
15 class Protocol(bitcoin_p2p.BaseProtocol):
16     version = 2
17     sub_version = p2pool.__version__
18     
19     def __init__(self, node):
20         self.node = node
21         
22         self._prefix = self.node.net.PREFIX
23     
24     max_payload_length = 1000000
25     use_checksum = True
26     
27     other_version = None
28     connected2 = False
29     
30     def connectionMade(self):
31         bitcoin_p2p.BaseProtocol.connectionMade(self)
32         
33         self.factory.proto_made_connection(self)
34         
35         self.addr = self.transport.getPeer().host, self.transport.getPeer().port
36         
37         self.send_version(
38             version=self.version,
39             services=0,
40             addr_to=dict(
41                 services=0,
42                 address=self.transport.getPeer().host,
43                 port=self.transport.getPeer().port,
44             ),
45             addr_from=dict(
46                 services=0,
47                 address=self.transport.getHost().host,
48                 port=self.transport.getHost().port,
49             ),
50             nonce=self.node.nonce,
51             sub_version=self.sub_version,
52             mode=1,
53             best_share_hash=self.node.best_share_hash_func(),
54         )
55         
56         reactor.callLater(10, self._connect_timeout)
57         self.timeout_delayed = reactor.callLater(100, self._timeout)
58     
59     def _connect_timeout(self):
60         if not self.connected2 and self.transport.connected:
61             print 'Handshake timed out, disconnecting from %s:%i' % self.addr
62             self.transport.loseConnection()
63     
64     def gotPacket(self):
65         if not self.timeout_delayed.called:
66             self.timeout_delayed.cancel()
67             self.timeout_delayed = reactor.callLater(100, self._timeout)
68     
69     def _timeout(self):
70         if self.transport.connected:
71             print 'Connection timed out, disconnecting from %s:%i' % self.addr
72             self.transport.loseConnection()
73     
74     @defer.inlineCallbacks
75     def _think(self):
76         while self.connected2:
77             self.send_ping()
78             yield deferral.sleep(random.expovariate(1/100))
79     
80     @defer.inlineCallbacks
81     def _think2(self):
82         while self.connected2:
83             self.send_addrme(port=self.node.port)
84             #print 'sending addrme'
85             yield deferral.sleep(random.expovariate(1/(100*len(self.node.peers) + 1)))
86     
87     message_version = bitcoin_data.ComposedType([
88         ('version', bitcoin_data.StructType('<I')),
89         ('services', bitcoin_data.StructType('<Q')),
90         ('addr_to', bitcoin_data.address_type),
91         ('addr_from', bitcoin_data.address_type),
92         ('nonce', bitcoin_data.StructType('<Q')),
93         ('sub_version', bitcoin_data.VarStrType()),
94         ('mode', bitcoin_data.StructType('<I')), # always 1 for legacy compatibility
95         ('best_share_hash', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
96     ])
97     def handle_version(self, version, services, addr_to, addr_from, nonce, sub_version, mode, best_share_hash):
98         if self.other_version is not None or version < 2:
99             self.transport.loseConnection()
100             return
101         
102         self.other_version = version
103         self.other_sub_version = sub_version[:512]
104         self.other_services = services
105         
106         if nonce == self.node.nonce:
107             #print 'Detected connection to self, disconnecting from %s:%i' % self.addr
108             self.transport.loseConnection()
109             return
110         if nonce in self.node.peers:
111             #print 'Detected duplicate connection, disconnecting from %s:%i' % self.addr
112             self.transport.loseConnection()
113             return
114         
115         self.nonce = nonce
116         self.connected2 = True
117         self.factory.proto_connected(self)
118         
119         self._think()
120         self._think2()
121         
122         if best_share_hash is not None:
123             self.node.handle_share_hashes([best_share_hash], self)
124     
125     message_ping = bitcoin_data.ComposedType([])
126     def handle_ping(self):
127         if not self.connected2:
128             self.transport.loseConnection()
129             return
130     
131     message_addrme = bitcoin_data.ComposedType([
132         ('port', bitcoin_data.StructType('<H')),
133     ])
134     def handle_addrme(self, port):
135         if not self.connected2:
136             self.transport.loseConnection()
137             return
138         host = self.transport.getPeer().host
139         #print 'addrme from', host, port
140         if host == '127.0.0.1':
141             if random.random() < .8 and self.node.peers:
142                 random.choice(self.node.peers.values()).send_addrme(port=port) # services...
143         else:
144             self.node.got_addr((self.transport.getPeer().host, port), self.other_services, int(time.time()))
145             if random.random() < .8 and self.node.peers:
146                 random.choice(self.node.peers.values()).send_addrs(addrs=[
147                     dict(
148                         address=dict(
149                             services=self.other_services,
150                             address=host,
151                             port=port,
152                         ),
153                         timestamp=int(time.time()),
154                     ),
155                 ])
156     
157     message_addrs = bitcoin_data.ComposedType([
158         ('addrs', bitcoin_data.ListType(bitcoin_data.ComposedType([
159             ('timestamp', bitcoin_data.StructType('<Q')),
160             ('address', bitcoin_data.address_type),
161         ]))),
162     ])
163     def handle_addrs(self, addrs):
164         if not self.connected2:
165             self.transport.loseConnection()
166             return
167         for addr_record in addrs:
168             self.node.got_addr((addr_record['address']['address'], addr_record['address']['port']), addr_record['address']['services'], min(int(time.time()), addr_record['timestamp']))
169             if random.random() < .8 and self.node.peers:
170                 random.choice(self.node.peers.values()).send_addrs(addrs=[addr_record])
171     
172     message_getaddrs = bitcoin_data.ComposedType([
173         ('count', bitcoin_data.StructType('<I')),
174     ])
175     def handle_getaddrs(self, count):
176         if not self.connected2:
177             self.transport.loseConnection()
178             return
179         if count > 100:
180             count = 100
181         self.send_addrs(addrs=[
182             dict(
183                 timestamp=self.node.addr_store[host, port][2],
184                 address=dict(
185                     services=self.node.addr_store[host, port][0],
186                     address=host,
187                     port=port,
188                 ),
189             ) for host, port in
190             self.node.get_good_peers(count)
191         ])
192     
193     message_getshares = bitcoin_data.ComposedType([
194         ('hashes', bitcoin_data.ListType(bitcoin_data.HashType())),
195         ('parents', bitcoin_data.VarIntType()),
196         ('stops', bitcoin_data.ListType(bitcoin_data.HashType())),
197     ])
198     def handle_getshares(self, hashes, parents, stops):
199         if not self.connected2:
200             self.transport.loseConnection()
201             return
202         self.node.handle_get_shares(hashes, parents, stops, self)
203     
204     message_shares = bitcoin_data.ComposedType([
205         ('shares', bitcoin_data.ListType(p2pool_data.share_type)),
206     ])
207     def handle_shares(self, shares):
208         if not self.connected2:
209             self.transport.loseConnection()
210             return
211         res = []
212         for share in shares:
213             share_obj = p2pool_data.Share.from_share(share, self.node.net)
214             share_obj.peer = self
215             res.append(share_obj)
216         self.node.handle_shares(res)
217     
218     def sendShares(self, shares, full=False):
219         def att(f, **kwargs):
220             try:
221                 f(**kwargs)
222             except bitcoin_p2p.TooLong:
223                 att(f, **dict((k, v[:len(v)//2]) for k, v in kwargs.iteritems()))
224                 att(f, **dict((k, v[len(v)//2:]) for k, v in kwargs.iteritems()))
225         if shares:
226             att(self.send_shares, shares=[share.as_share() for share in shares])
227     
228     def connectionLost(self, reason):
229         if self.connected2:
230             self.factory.proto_disconnected(self)
231             self.connected2 = False
232         self.factory.proto_lost_connection(self)
233
234 class ServerFactory(protocol.ServerFactory):
235     def __init__(self, node, max_conns):
236         self.node = node
237         self.max_conns = max_conns
238         
239         self.conns = set()
240         self.running = False
241     
242     def buildProtocol(self, addr):
243         if len(self.conns) >= self.max_conns:
244             return None
245         p = Protocol(self.node)
246         p.factory = self
247         return p
248     
249     def proto_made_connection(self, proto):
250         self.conns.add(proto)
251     def proto_lost_connection(self, proto):
252         self.conns.remove(proto)
253     
254     def proto_connected(self, proto):
255         self.node.got_conn(proto)
256     def proto_disconnected(self, proto):
257         self.node.lost_conn(proto)
258     
259     def start(self):
260         assert not self.running
261         self.running = True
262         
263         self.listen_port = reactor.listenTCP(self.node.port, self)
264     def stop(self):
265         assert self.running
266         self.running = False
267         
268         self.listen_port.stopListening()
269
270 class ClientFactory(protocol.ClientFactory):
271     def __init__(self, node, desired_conns, max_attempts, preferred_addrs):
272         self.node = node
273         self.desired_conns = desired_conns
274         self.max_attempts = max_attempts
275         self.preferred_addrs = preferred_addrs
276         
277         self.attempts = {}
278         self.conns = set()
279         self.running = False
280     
281     def buildProtocol(self, addr):
282         p = Protocol(self.node)
283         p.factory = self
284         return p
285     
286     def startedConnecting(self, connector):
287         host, port = connector.getDestination().host, connector.getDestination().port
288         if (host, port) in self.attempts:
289             raise ValueError('already have attempt')
290         self.attempts[host, port] = connector
291     
292     def clientConnectionFailed(self, connector, reason):
293         self.clientConnectionLost(connector, reason)
294     
295     def clientConnectionLost(self, connector, reason):
296         host, port = connector.getDestination().host, connector.getDestination().port
297         if (host, port) not in self.attempts:
298             raise ValueError('''don't have attempt''')
299         if connector is not self.attempts[host, port]:
300             raise ValueError('wrong connector')
301         del self.attempts[host, port]
302     
303     def proto_made_connection(self, proto):
304         pass
305     def proto_lost_connection(self, proto):
306         pass
307     
308     def proto_connected(self, proto):
309         self.conns.add(proto)
310         self.node.got_conn(proto)
311     def proto_disconnected(self, proto):
312         self.conns.remove(proto)
313         self.node.lost_conn(proto)
314     
315     def start(self):
316         assert not self.running
317         self.running = True
318         self._think()
319     def stop(self):
320         assert self.running
321         self.running = False
322     
323     @defer.inlineCallbacks
324     def _think(self):
325         while self.running:
326             try:
327                 if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and (len(self.preferred_addrs) or len(self.node.addr_store)):
328                     if (random.randrange(2) and len(self.preferred_addrs)) or not len(self.node.addr_store):
329                         host, port = random.choice(list(self.preferred_addrs))
330                     else:
331                         (host, port), = self.node.get_good_peers(1)
332                     
333                     if (host, port) not in self.attempts:
334                         #print 'Trying to connect to', host, port
335                         reactor.connectTCP(host, port, self, timeout=5)
336             except:
337                 log.err()
338             
339             yield deferral.sleep(random.expovariate(1/1))
340
341 class Node(object):
342     def __init__(self, best_share_hash_func, port, net, addr_store={}, preferred_addrs=set(), desired_outgoing_conns=10, max_outgoing_attempts=30, max_incoming_conns=50, preferred_storage=1000):
343         self.best_share_hash_func = best_share_hash_func
344         self.port = port
345         self.net = net
346         self.addr_store = dict(addr_store)
347         self.preferred_storage = preferred_storage
348         
349         self.nonce = random.randrange(2**64)
350         self.peers = {}
351         self.clientfactory = ClientFactory(self, desired_outgoing_conns, max_outgoing_attempts, preferred_addrs)
352         self.serverfactory = ServerFactory(self, max_incoming_conns)
353         self.running = False
354     
355     def start(self):
356         if self.running:
357             raise ValueError('already running')
358         
359         self.clientfactory.start()
360         self.serverfactory.start()
361         
362         self.running = True
363         
364         self._think2()
365     
366     @defer.inlineCallbacks
367     def _think2(self):
368         while self.running:
369             try:
370                 if len(self.addr_store) < self.preferred_storage and self.peers:
371                     random.choice(self.peers.values()).send_getaddrs(count=8)
372             except:
373                 log.err()
374             
375             yield deferral.sleep(random.expovariate(1/20))
376     
377     def stop(self):
378         if not self.running:
379             raise ValueError('already stopped')
380         
381         self.running = False
382         
383         self.clientfactory.stop()
384         self.serverfactory.stop()
385     
386     def got_conn(self, conn):
387         if conn.nonce in self.peers:
388             raise ValueError('already have peer')
389         self.peers[conn.nonce] = conn
390         
391         print 'Connected to peer %s:%i. p2pool version: %i %r' % (conn.addr[0], conn.addr[1], conn.other_version, conn.other_sub_version)
392     
393     def lost_conn(self, conn):
394         if conn.nonce not in self.peers:
395             raise ValueError('''don't have peer''')
396         if conn is not self.peers[conn.nonce]:
397             raise ValueError('wrong conn')
398         del self.peers[conn.nonce]
399         
400         print 'Lost peer %s:%i' % (conn.addr[0], conn.addr[1])
401     
402     
403     def got_addr(self, (host, port), services, timestamp):
404         if (host, port) in self.addr_store:
405             old_services, old_first_seen, old_last_seen = self.addr_store[host, port]
406             self.addr_store[host, port] = services, old_first_seen, max(old_last_seen, timestamp)
407         else:
408             self.addr_store[host, port] = services, timestamp, timestamp
409     
410     def handle_shares(self, shares, peer):
411         print 'handle_shares', (shares, peer)
412     
413     def handle_share_hashes(self, hashes, peer):
414         print 'handle_share_hashes', (hashes, peer)
415     
416     def handle_get_shares(self, hashes, parents, stops, peer):
417         print 'handle_get_shares', (hashes, parents, stops, peer)
418     
419     def get_good_peers(self, max_count):
420         t = time.time()
421         return [x[0] for x in sorted(self.addr_store.iteritems(), key=lambda (k, (services, first_seen, last_seen)): -(last_seen - first_seen)/max(3600, t - last_seen)*random.expovariate(1))][:max_count]
422
423 if __name__ == '__main__':
424     p = random.randrange(2**15, 2**16)
425     for i in xrange(5):
426         p2 = random.randrange(2**15, 2**16)
427         print p, p2
428         n = Node(p2, True, {addrdb_key.pack(dict(address='127.0.0.1', port=p)): addrdb_value.pack(dict(services=0, first_seen=int(time.time())-10, last_seen=int(time.time())))})
429         n.start()
430         p = p2
431     
432     reactor.run()