work
[p2pool.git] / p2p.py
1 from entangled.kademlia import node, encoding, protocol
2 from twisted.internet import defer
3
4 import bitcoin_p2p
5
6 class CustomBencode(encoding.Bencode):
7     def __init__(self, prefix=""):
8         self.prefix = prefix
9     
10     def encode(self, data):
11         return self.prefix + encoding.Bencode.encode(self, data)
12     
13     def decode(self, data):
14         print repr(data)
15         if not data.startswith(self.prefix):
16             raise ValueError("invalid prefix")
17         return encoding.Bencode.decode(self, data[len(self.prefix):])
18
19 class Node(node.Node):
20     @property
21     def peers(self):
22         for bucket in self._routingTable._buckets:
23             for contact in bucket._contacts:
24                 yield contact
25     
26     def __init__(self, blockCallback, getBlocksCallback, **kwargs):
27         #node.Node.__init__(self, networkProtocol=protocol.KademliaProtocol(self, msgEncoder=CustomBencode("p2pool")), **kwargs)
28         node.Node.__init__(self, **kwargs)
29         self.blockCallback = blockCallback
30         self.getBlocksCallback = getBlocksCallback
31     
32     # disable data storage
33     
34     @node.rpcmethod
35     def store(self, key, value, originalPublisherID=None, age=0, **kwargs):
36         return
37     
38     @node.rpcmethod
39     def findValue(self, key, value, originalPublisherID=None, age=0, **kwargs):
40         return
41     
42     def _republishData(self, *args):
43         return defer.succeed(None)
44     
45     # meat
46     
47     @node.rpcmethod
48     def block(self, block_data, _rpcNodeID, _rpcNodeContact):
49         self.blockCallback(bitcoin_p2p.block.unpack(block_data), _rpcNodeContact)
50     
51     @node.rpcmethod
52     def get_blocks(self, chain_id, _rpcNodeID, _rpcNodeContact):
53         try:
54             self.getBlocksCallback(chain_id, _rpcNodeContact)
55         except:
56             traceback.print_exc()