Base Module

A library to store common functions and protocol definitions

class py2p.base.flags[source]

A namespace to hold protocol-defined flags

reserved = ['\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\t', '\n', '\x0b', '\x0c', '\r', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/']

Main flags:

  • broadcast
  • whisper
  • renegotiate
  • ping
  • pong

Sub-flags:

  • broadcast
  • compression
  • whisper
  • handshake
  • ping
  • pong
  • notify
  • peers
  • request
  • resend
  • response
  • store
  • retrieve

Python-implemented compression methods:

Other implementations’ and/or planned compression methods:

class py2p.base.protocol[source]

Defines service variables so that you can reject connections looking for a different service

subnet

The subnet flag this protocol uses

encryption

The encryption method this protocol uses

id

The SHA-256 based ID of this protocol

class py2p.base.InternalMessage(msg_type, sender, payload, compression=None, timestamp=None)[source]

An object used to build and parse protocol-defined message structures

__init__(msg_type, sender, payload, compression=None, timestamp=None)[source]

Initializes a InternalMessage instance

Parameters:
  • msg_type – A bytes-like header for the message you wish to send
  • sender – A bytes-like sender ID the message is using
  • payload – A iterable of bytes-like objects containing the payload of the message
  • compression – A list of the compression methods this message may use (default: [])
  • timestamp – The current UTC timestamp (as an integer) (default: result of utils.getUTC())
Raises:

TypeError – If you feed an object which cannot convert to bytes

Warning

If you feed a unicode object, it will be decoded using utf-8. All other objects are treated as raw bytes. If you desire a particular codec, encode it yourself before feeding it in.

compression_used

Returns the compression method this message is using

classmethod feed_string(string, sizeless=False, compressions=None)[source]

Constructs a InternalMessage from a string or bytes object.

Parameters:
  • string – The string you wish to parse
  • sizeless – A boolean which describes whether this string has its size header (default: it does)
  • compressions – A list containing the standardized compression methods this message might be under (default: [])
Returns:

A base.InternalMessage from the given string

Raises:
  • AttributeError – Fed a non-string, non-bytes argument
  • AssertionError – Initial size header is incorrect
  • ValueError – Unrecognized compression method fed in compressions
  • IndexError – Packet headers are incorrect OR unrecognized compression
id

Returns the message id

len

Return the struct-encoded length header

packets

Returns the full tuple of packets in this message encoded as bytes, excluding the header

payload

Returns a tuple containing the message payload encoded as bytes

string

Returns a bytes representation of the message

time_58

Returns this message’s timestamp in base_58

class py2p.base.base_connection(sock, server, outgoing=False)[source]

The base class for a connection

__init__(sock, server, outgoing=False)[source]

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)[source]

Collects incoming data

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

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

find_terminator()[source]

Returns whether the defined return sequences is found

found_terminator()[source]

Processes received messages

handle_renegotiate(packets)[source]

The handler for connection renegotiations

This is to deal with connection maintenance. 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 tuple containing the packets received in this message
Returns:True if an action was taken, None if not
send(msg_type, *args, **kargs)[source]

Sends a message through its connection.

Parameters:
  • msg_type – Message type, corresponds to the header in a InternalMessage 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 IntenalMessage object you just sent, or None if the sending was unsuccessful

send_InternalMessage(msg)[source]

Sends a preconstructed message

Parameters:msg – The IntenalMessage you wish to send
Returns:the IntenalMessage object you just sent, or None if the sending was unsuccessful
class py2p.base.base_daemon(addr, port, server)[source]

The base class for a daemon

__init__(addr, port, server)[source]

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)[source]

Cleans out connections which never finish a message

process_data(handler)[source]

Collects incoming data from nodes

class py2p.base.base_socket(addr, port, prot=protocol(subnet='', encryption='Plaintext'), out_addr=None, debug_level=0)[source]

The base class for a peer-to-peer socket abstractor

__init__(addr, port, prot=protocol(subnet='', encryption='Plaintext'), out_addr=None, debug_level=0)[source]

Initializes a peer to peer 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)
  • 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
close()[source]

If the socket is not closed, close the socket

Raises:RuntimeError – The socket was already closed
handle_msg(msg, conn)[source]

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

Parameters:
Returns:

True if an action was taken, None if not.

incoming

IDs of incoming connections

outgoing

IDs of outgoing connections

register_handler(method)[source]

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 (Exception, traceback) tuples if not
py2p.base.compress(msg, method)[source]

Shortcut method for compression

Parameters:
  • msg – The message you wish to compress, the type required is defined by the requested method
  • method

    The compression method you wish to use. Supported (assuming installed):

    gzip, zlib, bz2, lzma
Returns:

Defined by the compression method, but typically the bytes of the compressed message

Warning

The types fed are dependent on which compression method you use. Best to assume most values are bytes or bytearray

Raises:A :py:class:`ValueError` if there is an unknown compression method, – or a method-specific error
py2p.base.decompress(msg, method)[source]

Shortcut method for decompression

Parameters:
  • msg – The message you wish to decompress, the type required is defined by the requested method
  • method

    The decompression method you wish to use. Supported (assuming installed):

    gzip, zlib, bz2, lzma
Returns:

Defined by the decompression method, but typically the bytes of the compressed message

Warning

The types fed are dependent on which decompression method you use. Best to assume most values are bytes or bytearray

Raises:A :py:class:`ValueError` if there is an unknown compression method, – or a method-specific error
py2p.base.from_base_58(string)[source]

Takes a base_58 string and returns its corresponding integer

Parameters:string – The base_58 value you wish to decode (string, bytes, or bytearray)
Returns:Returns integral value which corresponds to the fed string
class py2p.base.message(msg, server)[source]

An object which gets returned to a user, containing all necessary information to parse and reply to a message

__init__(msg, server)[source]

Initializes a message object

Parameters:
id

Returns the message id

packets

Returns a tuple containing the message payload encoded as bytes

reply(*args)[source]

Replies to the sender if you’re directly connected. Tries to make a connection otherwise

Parameters:*args – Each argument given is a packet you wish to send. This is prefixed with base.flags.whisper, so the other end will receive [base.flags.whisper, *args]
sender

The ID of this message’s sender

time

The time this message was sent at

time_58

Returns this message’s timestamp in base_58

py2p.base.pack_value(l, i)[source]

For value i, pack it into bytes of size length

Parameters:
  • length – A positive, integral value describing how long to make the packed array
  • i – A positive, integral value to pack into said array
Returns:

A bytes object containing the given value

Raises:

ValueError – If length is not large enough to contain the value provided

py2p.base.to_base_58(i)[source]

Takes an integer and returns its corresponding base_58 string

Parameters:i – The integral value you wish to encode
Returns:A bytes object which contains the base_58 string
Raises:TypeError – If you feed a non-integral value
py2p.base.unpack_value(string)[source]

For a string, return the packed value inside of it

Parameters:string – A string or bytes-like object
Returns:An integral value interpreted from this, as if it were a big-endian, unsigned integral