Chord Module

class py2p.chord.chord_connection(sock, server, outgoing=False)[source]

The class for chord connection abstraction. This inherits from py2p.base.base_connection

found_terminator()[source]

This method is called when the expected amount of data is received

Returns:None
id_10

Returns the nodes ID as an integer

__init__(sock, server, outgoing=False)

Sets up a connection to another peer-to-peer socket

Parameters:
  • sock – The connected socket object
  • server – A reference to your peer-to-peer socket
  • outgoing – Whether this connection is outgoing (default: False)
collect_incoming_data(data)

Collects incoming data

Parameters:data – The most recently received byte
Returns:True if the data collection was successful, False if the connection was closed
fileno()

Mirror for the fileno() method of the connection’s underlying socket

find_terminator()

Returns whether the definied return sequences is found

handle_renegotiate(packets)

The handler for connection renegotiations

This is to deal with connection maintenence. For instance, it could be that a compression method fails to decode on the other end, and a node will need to renegotiate which methods it is using. Hence the name of the flag associated with it, “renegotiate”.

Parameters:packets – A list containing the packets received in this message
Returns:True if an action was taken, None if not
protocol

Returns server.protocol

send(msg_type, *args, **kargs)

Sends a message through its connection.

Parameters:
  • msg_type – Message type, corresponds to the header in a py2p.base.pathfinding_message object
  • *args – A list of bytes-like objects, which correspond to the packets to send to you
  • **kargs – There are two available keywords:
  • id – The ID this message should appear to be sent from (default: your ID)
  • time – The time this message should appear to be sent from (default: now in UTC)
Returns:

the pathfinding_message object you just sent, or None if the sending was unsuccessful

class py2p.chord.chord_daemon(addr, port, server)[source]

The class for chord daemon. This inherits from py2p.base.base_daemon

mainloop()[source]

Daemon thread which handles all incoming data and connections

handle_accept()[source]

Handle an incoming connection

process_data(handler)[source]

Collects incoming data from nodes

__init__(addr, port, server)

Sets up a daemon process for your peer-to-peer socket

Parameters:
  • addr – The address you wish to bind to
  • port – The port you wish to bind to
  • server – A reference to the peer-to-peer socket
Raises:
  • socket.error – The address you wanted is already in use
  • ValueError – If your peer-to-peer socket is set up with an unknown encryption method
kill_old_nodes(handler)

Cleans out connections which never finish a message

protocol

Returns server.protocol

class py2p.chord.chord_socket(addr, port, k=6, prot=<protocol object>, out_addr=None, debug_level=0)[source]

The class for chord socket abstraction. This inherits from py2p.base.base_socket

__init__(addr, port, k=6, prot=<protocol object>, out_addr=None, debug_level=0)[source]

Initializes a chord socket

Parameters:
  • addr – The address you wish to bind to (ie: “192.168.1.1”)
  • port – The port you wish to bind to (ie: 44565)
  • k – This number indicates the node counts the network can support. You must have > (k+1) nodes. You may only have up to 2**k nodes, but at that count you will likely get ID conficts.
  • prot – The protocol you wish to operate over, defined by a py2p.base.protocol object
  • out_addr – Your outward facing address. Only needed if you’re connecting over the internet. If you use ‘0.0.0.0’ for the addr argument, this will automatically be set to your LAN address.
  • debug_level – The verbosity you want this socket to use when printing event data
Raises:

socket.error – The address you wanted could not be bound, or is otherwise used

addr

An alternate binding for self.out_addr, in order to better handle self-references in the daemon thread

set_fingers(handler)[source]

Given a handler, check to see if it’s the closest connection to an ideal slot.

In other words, if it’s the closest ID you know of to a power of two distance from you, add it to your connection table.

Parameters:handler – A chord_connection
is_saturated()[source]

Returns whether all ideal connection slots are filled

update_fingers()[source]

Updates your connection table, and sends a request for more peers whenever getUTC() % 5 == 0 and not self.is_saturated()

Is this efficient? No.

Will it be fixed? Yes. See the warning up top.

handle_msg(msg, conn)[source]

Decides how to handle various message types, allowing some to be handled automatically

dump_data(start, end=None)[source]
Parameters:
  • start – An int which indicates the start of the desired key range. 0 will get all data.
  • end – An int which indicates the end of the desired key range. None will get all data. (default: None)
Returns:

A nested dict containing your data from start to end

connect(addr, port)[source]

This function connects you to a specific node in the overall network. Connecting to one node should connect you to the rest of the network, however if you connect to the wrong subnet, the handshake failure involved is silent. You can check this by looking at the truthiness of this objects routing table. Example:

>>> conn = chord.chord_socket('localhost', 4444)
>>> conn.connect('localhost', 5555)
>>> conn.join()
>>> # do some other setup for your program
>>> if (!conn.routing_table):
...     conn.connect('localhost', 6666)  # any fallback address
...     conn.join()
Parameters:
  • addr – A string address
  • port – A positive, integral port
  • id – A string-like object which represents the expected ID of this node
_send_handshake(handler)[source]

Shortcut method for sending a handshake to a given handler

Parameters:handler – A chord_connection
join()[source]

Tells the node to start seeding the chord table

unjoin()[source]

Tells the node to stop seeding the chord table, and dumps the data to the proper nodes

lookup(key)[source]

Looks up the value at a given key.

Under the covers, this actually checks five different hash tables, and returns the most common value given.

Parameters:

key – The key that you wish to check. Must be a str or bytes-like object

Returns:

The value at said key

Raises:
  • socket.timeout – If the request goes partly-unanswered for >=10 seconds
  • KeyError – If the request is made for a key with no agreed-upon value
get(key)[source]
store(key, value)[source]

Updates the value at a given key.

Under the covers, this actually uses five different hash tables, and updates the value in all of them.

Parameters:
  • key – The key that you wish to update. Must be a str or bytes-like object
  • value – The value you wish to put at this key. Must be a str or bytes-like object
set(key, value)[source]
update(update_dict)[source]

Equivalent to dict.update()

This calls chord_socket.store() for each key/value pair in the given dictionary.

Parameters:update_dict – A dict-like object to extract key/value pairs from. Key and value be a str or bytes-like object
disconnect(handler)[source]

Closes a given connection, and removes it from your routing tables

Parameters:handler – the connection you would like to close
_chord_socket__connect(addr, port)

Private API method for connecting and handshaking

Parameters:
  • addr – the address you want to connect to/handshake
  • port – the port you want to connect to/handshake
_chord_socket__get_fingers()

Returns a finger table for your peer

_chord_socket__handle_handshake(msg, handler)

This callback is used to deal with handshake signals. Its two primary jobs are:

  • reject connections seeking a different network
  • set connection state
Parameters:
Returns:

Either True or None

_chord_socket__handle_peers(msg, handler)

This callback is used to deal with peer signals. Its primary jobs is to connect to the given peers, if they are a better connection given the chord schema

Parameters:
Returns:

Either True or None

_chord_socket__handle_request(msg, handler)

This callback is used to deal with request signals. Its three primary jobs are:

  • respond with a peers signal if packets[1] is '*'
  • if you know the ID requested, respond to it
  • if you don’t, make a request with your peers
Parameters:
Returns:

Either True or None

_chord_socket__handle_response(msg, handler)

This callback is used to deal with response signals. Its two primary jobs are:

  • if it was your request, send the deferred message
  • if it was someone else’s request, relay the information
Parameters:
Returns:

Either True or None

_chord_socket__handle_retrieve(msg, handler)

This callback is used to deal with data retrieval signals. Its two primary jobs are:

  • respond with data you possess
  • if you don’t possess it, make a request with your closest peer to that key
Parameters:
Returns:

Either True or None

_chord_socket__handle_store(msg, handler)

This callback is used to deal with data storage signals. Its two primary jobs are:

  • store data in keys you’re responsible for
  • if you aren’t responsible, make a request with your closest peer to that key
Parameters:
Returns:

Either True or None

_chord_socket__lookup(method, key, handler=None)
_chord_socket__store(method, key, value)
close()

If the socket is not closed, close the socket

Raises:RuntimeError – The socket was already closed
register_handler(method)

Register a handler for incoming method.

Parameters:method – A function with two given arguments. Its signature should be of the form handler(msg, handler), where msg is a py2p.base.message object, and handler is a py2p.base.base_connection object. It should return True if it performed an action, to reduce the number of handlers checked.
Raises:ValueError – If the method signature doesn’t parse correctly
status

The status of the socket.

Returns:"Nominal" if all is going well, or a list of unexpected (Excpetion, traceback) tuples if not
py2p.chord.distance(a, b, limit)[source]

This is a clockwise ring distance function. It depends on a globally defined k, the key size. The largest possible node id is limit (or 2**k).