本文整理汇总了Python中dht.node.Node类的典型用法代码示例。如果您正苦于以下问题:Python Node类的具体用法?Python Node怎么用?Python Node使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Node类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_create_proto
def test_create_proto(self):
rid = hashlib.sha1(str(random.getrandbits(255))).digest()
pubkey = digest("pubkey")
addr = objects.Node.IPAddress()
addr.ip = "127.0.0.1"
addr.port = 1234
relay_addr = objects.Node.IPAddress()
relay_addr.ip = "127.0.0.1"
relay_addr.port = 1234
n1 = objects.Node()
n1.guid = rid
n1.signedPublicKey = pubkey
n1.vendor = False
n1.nodeAddress.MergeFrom(addr)
n1.natType = objects.FULL_CONE
n2 = Node(rid, "127.0.0.1", 1234, digest("pubkey"), None, objects.FULL_CONE, False)
self.assertEqual(n1, n2.getProto())
n1.vendor = True
n1.relayAddress.MergeFrom(relay_addr)
n2 = Node(rid, "127.0.0.1", 1234, digest("pubkey"), ("127.0.0.1", 1234), objects.FULL_CONE, True)
self.assertEqual(n1, n2.getProto())
示例2: test_rpc_find_without_value
def test_rpc_find_without_value(self):
self._connecting_to_connected()
node1 = Node(digest("id1"), "127.0.0.1", 12345, digest("key1"))
node2 = Node(digest("id2"), "127.0.0.1", 22222, digest("key2"))
node3 = Node(digest("id3"), "127.0.0.1", 77777, digest("key3"))
self.protocol.router.addContact(node1)
self.protocol.router.addContact(node2)
self.protocol.router.addContact(node3)
m = message.Message()
m.messageID = digest("msgid")
m.sender.MergeFrom(self.protocol.sourceNode.getProto())
m.command = message.Command.Value("FIND_VALUE")
m.arguments.append(digest("Keyword"))
data = m.SerializeToString()
self.handler.receive_message(data)
del m.arguments[-1]
m.arguments.extend([node2.getProto().SerializeToString(), node3.getProto().SerializeToString(), node1.getProto().SerializeToString()])
expected_message = m.SerializeToString()
self.clock.advance(100 * constants.PACKET_TIMEOUT)
connection.REACTOR.runUntilCurrent()
m_calls = self.proto_mock.send_datagram.call_args_list
sent_packet = packet.Packet.from_bytes(self.proto_mock.send_datagram.call_args_list[0][0][0])
received_message = sent_packet.payload
m = message.Message()
m.ParseFromString(received_message)
self.assertEqual(received_message, expected_message)
self.assertEqual(len(m_calls), 2)
示例3: test_distanceCalculation
def test_distanceCalculation(self):
ridone = hashlib.sha1(str(random.getrandbits(255)))
ridtwo = hashlib.sha1(str(random.getrandbits(255)))
shouldbe = int(ridone.hexdigest(), 16) ^ int(ridtwo.hexdigest(), 16)
none = Node(ridone.digest())
ntwo = Node(ridtwo.digest())
self.assertEqual(none.distanceTo(ntwo), shouldbe)
示例4: test_create_proto
def test_create_proto(self):
rid = hashlib.sha1(str(random.getrandbits(255))).digest()
pubkey = digest("pubkey")
vendor = True
n1 = objects.Node()
n1.guid = rid
n1.signedPublicKey = pubkey
n1.vendor = False
n2 = Node(rid, signed_pubkey=digest("pubkey"))
self.assertEqual(n1, n2.getProto())
n1.vendor = True
n2 = Node(rid, signed_pubkey=pubkey, vendor=vendor)
self.assertEqual(n1, n2.getProto())
示例5: test_getNodeList
def test_getNodeList(self):
node1 = Node(digest("id1"), "127.0.0.1", 1234, digest("key1"), None, FULL_CONE, True)
node2 = Node(digest("id2"), "248.130.11.21", 1111, digest("key2"), None, FULL_CONE, True)
node3 = Node(digest("id3"), "987.567.23.1", 23456, digest("key3"), None, FULL_CONE, False)
response = (True, (node1.getProto().SerializeToString(), node2.getProto().SerializeToString(),
node3.getProto().SerializeToString(),
"sdfasdfsd"))
r = RPCFindResponse(response)
nodes = r.getNodeList()
self.assertEqual(nodes[0].getProto(), node1.getProto())
self.assertEqual(nodes[1].getProto(), node2.getProto())
self.assertEqual(nodes[2].getProto(), node3.getProto())
示例6: test_getNodeList
def test_getNodeList(self):
node1 = Node(digest("id1"), "127.0.0.1", 12345, signed_pubkey=digest("key1"), vendor=True)
node2 = Node(digest("id2"), "127.0.0.1", 22222, signed_pubkey=digest("key2"), vendor=True)
node3 = Node(digest("id3"), "127.0.0.1", 77777, signed_pubkey=digest("key3"))
response = (True, (node1.getProto().SerializeToString(), node2.getProto().SerializeToString(),
node3.getProto().SerializeToString(),
"sdfasdfsd"))
r = RPCFindResponse(response)
nodes = r.getNodeList()
self.assertEqual(nodes[0].getProto(), node1.getProto())
self.assertEqual(nodes[1].getProto(), node2.getProto())
self.assertEqual(nodes[2].getProto(), node3.getProto())
示例7: __init__
def __init__(self, private_key, public_key, alias=None):
self.private_key = private_key
self.public_key = public_key
self._node = Node()
if alias:
self.alias = alias
else:
self.alias = {}
示例8: setUp
def setUp(self):
self.public_ip = '123.45.67.89'
self.port = 12345
self.own_addr = (self.public_ip, self.port)
self.addr1 = ('132.54.76.98', 54321)
self.addr2 = ('231.76.45.89', 15243)
self.addr3 = ("193.193.111.00", 99999)
self.clock = task.Clock()
connection.REACTOR.callLater = self.clock.callLater
self.proto_mock = mock.Mock(spec_set=rudp.ConnectionMultiplexer)
self.handler_mock = mock.Mock(spec_set=connection.Handler)
self.con = connection.Connection(
self.proto_mock,
self.handler_mock,
self.own_addr,
self.addr1
)
valid_key = "63d901c4d57cde34fc1f1e28b9af5d56ed342cae5c2fb470046d0130a4226b0c"
self.signing_key = nacl.signing.SigningKey(valid_key, encoder=nacl.encoding.HexEncoder)
verify_key = self.signing_key.verify_key
h = nacl.hash.sha512(verify_key.encode())
self.storage = ForgetfulStorage()
self.node = Node(unhexlify(h[:40]), self.public_ip, self.port, verify_key.encode(), None, FULL_CONE, True)
self.db = Database(filepath="test.db")
self.protocol = KademliaProtocol(self.node, self.storage, 20, self.db, self.signing_key)
self.wire_protocol = PulseShopProtocol(self.db, self.own_addr, FULL_CONE)
self.wire_protocol.register_processor(self.protocol)
self.protocol.connect_multiplexer(self.wire_protocol)
self.handler = self.wire_protocol.ConnHandler([self.protocol], self.wire_protocol, None,
self.wire_protocol.ban_score)
transport = mock.Mock(spec_set=udp.Port)
ret_val = address.IPv4Address('UDP', self.public_ip, self.port)
transport.attach_mock(mock.Mock(return_value=ret_val), 'getHost')
self.wire_protocol.makeConnection(transport)
self.node1 = Node(digest("id1"), self.addr1[0], self.addr1[1], digest("key1"), None, FULL_CONE, True)
self.node2 = Node(digest("id2"), self.addr2[0], self.addr2[1], digest("key2"), None, FULL_CONE, True)
self.node3 = Node(digest("id3"), self.addr3[0], self.addr3[1], digest("key3"), None, FULL_CONE, True)
示例9: setUp
def setUp(self):
self.public_ip = '123.45.67.89'
self.port = 12345
self.own_addr = (self.public_ip, self.port)
self.addr1 = ('132.54.76.98', 54321)
self.addr2 = ('231.76.45.89', 15243)
self.addr3 = ("193.193.111.00", 99999)
self.clock = task.Clock()
connection.REACTOR.callLater = self.clock.callLater
self.proto_mock = mock.Mock(spec_set=rudp.ConnectionMultiplexer)
self.handler_mock = mock.Mock(spec_set=connection.Handler)
self.con = connection.Connection(
self.proto_mock,
self.handler_mock,
self.own_addr,
self.addr1
)
valid_key = "1a5c8e67edb8d279d1ae32fa2da97e236b95e95c837dc8c3c7c2ff7a7cc29855"
self.signing_key = nacl.signing.SigningKey(valid_key, encoder=nacl.encoding.HexEncoder)
verify_key = self.signing_key.verify_key
signed_pubkey = self.signing_key.sign(str(verify_key))
h = nacl.hash.sha512(signed_pubkey)
self.storage = ForgetfulStorage()
self.node = Node(unhexlify(h[:40]), self.public_ip, self.port, signed_pubkey, True)
self.db = Database(filepath=":memory:")
self.protocol = KademliaProtocol(self.node, self.storage, 20, self.db)
self.wire_protocol = OpenBazaarProtocol(self.own_addr)
self.wire_protocol.register_processor(self.protocol)
self.protocol.connect_multiplexer(self.wire_protocol)
self.handler = self.wire_protocol.ConnHandler([self.protocol], self.wire_protocol)
transport = mock.Mock(spec_set=udp.Port)
ret_val = address.IPv4Address('UDP', self.public_ip, self.port)
transport.attach_mock(mock.Mock(return_value=ret_val), 'getHost')
self.wire_protocol.makeConnection(transport)
self.node1 = Node(digest("id1"), self.addr1[0], self.addr1[1], digest("key1"), True)
self.node2 = Node(digest("id2"), self.addr2[0], self.addr2[1], digest("key2"), True)
self.node3 = Node(digest("id3"), self.addr3[0], self.addr3[1], digest("key3"), True)
示例10: on_response_received
def on_response_received(self, transaction):
# Update the id of the remote node.
transaction.response_node.id_20 = transaction.response["r"]["id"]
# Add the node that reponded to us. We most likely already have this one.
self._server.remote_nodes.add(transaction.response_node)
# A find_node or get_peers response may carry extra nodes.
if transaction.query["q"] == "find_node" or transaction.query["q"] == "get_peers":
nodes = transaction.response["r"].get("nodes", "")
for i in xrange(0, len(nodes), 26):
id_26 = nodes[i : i + 26]
if not self._server.remote_nodes.get_node(id_26):
self._server.remote_nodes.add(Node.from_id_26(id_26))
示例11: _receiver
def _receiver(self):
"""
Run in a different thread, and have as only goal to receive messages,
parse them, and put them into a thread safe queue for further handling
"""
while True:
try:
# Receive message
raw_message, connect_info = self._sock.recvfrom(4096)
message = bdecode(raw_message)
# print "Received f " + str(connect_info) + ":\t" + str(message)
# This is a query from another peer.
if message['y'] == 'q':
# Retrieve or create source node.
id_26 = message['a']['id'] + socket.inet_aton(connect_info[0]) + struct.pack(r'!H', connect_info[1])
source_node = self.remote_nodes.get_node(id_26) or Node.from_id_26(id_26)
transaction = Transaction(query=message, query_node=source_node, response_node=self.node) # create transaction
self._running_transactions[transaction.id] = transaction # Add it to running transactions
for handler in self.on_query_received:
handler(transaction) # Notify listeners
elif message['y'] == 'e':
raise Exception
# This is a response to a transaction we started.
elif message['y'] == 'r':
transaction = self._running_transactions.pop(message["t"]) # pop transaction
transaction.response = message
for handler in self.on_response_received:
handler(transaction) # Notify listeners
else:
raise Exception
except socket.timeout:
pass
except BTFailure:
pass
except:
print traceback.format_exc()
示例12: test_rpc_find_node
def test_rpc_find_node(self):
self._connecting_to_connected()
node1 = Node(digest("id1"), "127.0.0.1", 12345, digest("key1"), nat_type=objects.FULL_CONE)
node2 = Node(digest("id2"), "127.0.0.1", 22222, digest("key2"), nat_type=objects.FULL_CONE)
node3 = Node(digest("id3"), "127.0.0.1", 77777, digest("key3"), nat_type=objects.FULL_CONE)
self.protocol.router.addContact(node1)
self.protocol.router.addContact(node2)
self.protocol.router.addContact(node3)
m = message.Message()
m.messageID = digest("msgid")
m.sender.MergeFrom(self.protocol.sourceNode.getProto())
m.command = message.Command.Value("FIND_NODE")
m.protoVer = self.version
m.testnet = False
m.arguments.append(digest("nodetofind"))
m.signature = self.signing_key.sign(m.SerializeToString())[:64]
data = m.SerializeToString()
del m.arguments[-1]
m.arguments.extend(
[
node2.getProto().SerializeToString(),
node1.getProto().SerializeToString(),
node3.getProto().SerializeToString(),
]
)
m.ClearField("signature")
expected_message = m.SerializeToString()
self.handler.on_connection_made()
self.handler.receive_message(data)
self.clock.advance(100 * constants.PACKET_TIMEOUT)
connection.REACTOR.runUntilCurrent()
m_calls = self.proto_mock.send_datagram.call_args_list
sent_packet = packet.Packet.from_bytes(self.proto_mock.send_datagram.call_args_list[0][0][0])
received_message = sent_packet.payload
a = message.Message()
a.ParseFromString(received_message)
a.ClearField("signature")
received_message = a.SerializeToString()
self.assertEqual(received_message, expected_message)
self.assertEqual(len(m_calls), 2)
示例13: Drogulus
class Drogulus(object):
"""
Represents a node in the Drogulus distributed hash table. This is the
class that generally should be instantiated.
"""
def __init__(self, private_key, public_key, alias=None):
self.private_key = private_key
self.public_key = public_key
self._node = Node()
if alias:
self.alias = alias
else:
self.alias = {}
def join(self):
"""
Causes the node to join the distributed hash table. Returns a deferred
that fires when the operation is complete.
"""
pass
def whois(self, public_key):
"""
Given the public key of an entity that uses the drogulus will return a
deferred that fires when information about them stored in the DHT is
retrieved.
"""
return self.get(public_key, None)
def get(self, public_key, key_name):
"""
Gets the value associated with a compound key made of the passed in
public key and meaningful key name. Returns a deferred that fires when
the value is retrieved.
"""
target = construct_key(public_key, key_name)
return self._node.retrieve(target)
def set(self, key_name, value, duplicate=DUPLICATION_COUNT, meta=None,
expires=EXPIRY_DURATION):
"""
Stores a value at a compound key made from the local node's public key
and the passed in meaningful key name. Returns a deferred that fires
when the value has been stored to duplicate number of nodes. An
optional meta dictionary and expires duration (to be added to the
current time) can also be specified.
"""
timestamp = time.time()
if meta is None:
meta = {}
if expires < 1:
expires = -1
else:
expires = timestamp + expires
signature = generate_signature(value, timestamp, expires, key_name,
meta, self.private_key)
return self._node.replicate(self.public_key, key_name, value,
timestamp, expires, meta, signature,
duplicate)
示例14: ValueSpiderCrawlTest
class ValueSpiderCrawlTest(unittest.TestCase):
def setUp(self):
self.public_ip = '123.45.67.89'
self.port = 12345
self.own_addr = (self.public_ip, self.port)
self.addr1 = ('132.54.76.98', 54321)
self.addr2 = ('231.76.45.89', 15243)
self.addr3 = ("193.193.111.00", 99999)
self.clock = task.Clock()
connection.REACTOR.callLater = self.clock.callLater
self.proto_mock = mock.Mock(spec_set=rudp.ConnectionMultiplexer)
self.handler_mock = mock.Mock(spec_set=connection.Handler)
self.con = connection.Connection(
self.proto_mock,
self.handler_mock,
self.own_addr,
self.addr1
)
valid_key = "1a5c8e67edb8d279d1ae32fa2da97e236b95e95c837dc8c3c7c2ff7a7cc29855"
self.signing_key = nacl.signing.SigningKey(valid_key, encoder=nacl.encoding.HexEncoder)
verify_key = self.signing_key.verify_key
signed_pubkey = self.signing_key.sign(str(verify_key))
h = nacl.hash.sha512(signed_pubkey)
self.storage = ForgetfulStorage()
self.node = Node(unhexlify(h[:40]), self.public_ip, self.port, signed_pubkey, True)
self.protocol = KademliaProtocol(self.node, self.storage, 20)
transport = mock.Mock(spec_set=udp.Port)
ret_val = address.IPv4Address('UDP', self.public_ip, self.port)
transport.attach_mock(mock.Mock(return_value=ret_val), 'getHost')
self.protocol.makeConnection(transport)
self.node1 = Node(digest("id1"), self.addr1[0], self.addr1[1], digest("key1"), True)
self.node2 = Node(digest("id2"), self.addr2[0], self.addr2[1], digest("key2"), True)
self.node3 = Node(digest("id3"), self.addr3[0], self.addr3[1], digest("key3"), True)
def tearDown(self):
self.con.shutdown()
self.protocol.shutdown()
def test_find(self):
self._connecting_to_connected()
self.protocol[self.addr1] = self.con
self.protocol[self.addr2] = self.con
self.protocol[self.addr3] = self.con
self.protocol.router.addContact(self.node1)
self.protocol.router.addContact(self.node2)
self.protocol.router.addContact(self.node3)
node = Node(digest("s"))
nearest = self.protocol.router.findNeighbors(node)
spider = ValueSpiderCrawl(self.protocol, node, nearest, 20, 3)
spider.find()
self.clock.advance(100 * constants.PACKET_TIMEOUT)
connection.REACTOR.runUntilCurrent()
self.assertEqual(len(self.proto_mock.send_datagram.call_args_list), 4)
def test_nodesFound(self):
self._connecting_to_connected()
self.protocol[self.addr1] = self.con
self.protocol[self.addr2] = self.con
self.protocol[self.addr3] = self.con
self.protocol.router.addContact(self.node1)
self.protocol.router.addContact(self.node2)
self.protocol.router.addContact(self.node3)
# test resonse with uncontacted nodes
node = Node(digest("s"))
nearest = self.protocol.router.findNeighbors(node)
spider = ValueSpiderCrawl(self.protocol, node, nearest, 20, 3)
response = (True, (self.node1.getProto().SerializeToString(), self.node2.getProto().SerializeToString(),
self.node3.getProto().SerializeToString()))
responses = {self.node1.id: response}
spider._nodesFound(responses)
self.clock.advance(100 * constants.PACKET_TIMEOUT)
connection.REACTOR.runUntilCurrent()
self.assertEqual(len(self.proto_mock.send_datagram.call_args_list), 4)
# test all been contacted
spider = ValueSpiderCrawl(self.protocol, node, nearest, 20, 3)
for peer in spider.nearest.getUncontacted():
spider.nearest.markContacted(peer)
response = (True, (self.node1.getProto().SerializeToString(), self.node2.getProto().SerializeToString(),
self.node3.getProto().SerializeToString()))
responses = {self.node2.id: response}
resp = spider._nodesFound(responses)
self.assertTrue(resp is None)
# test didn't happen
spider = ValueSpiderCrawl(self.protocol, node, nearest, 20, 3)
response = (False, (self.node1.getProto().SerializeToString(), self.node2.getProto().SerializeToString(),
self.node3.getProto().SerializeToString()))
responses = {self.node1.id: response}
#.........这里部分代码省略.........
示例15: test_tuple
def test_tuple(self):
n = Node('127.0.0.1', 0, 'testkey')
i = n.__iter__()
self.assertIn('127.0.0.1', i)
self.assertIn(0, i)
self.assertIn('testkey', i)