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