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