Here are the examples of the python api protocol.Connection taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3 Examples
0
Example 1
Project: bitnodes Source File: crawl.py
def connect(redis_conn, key):
"""
Establishes connection with a node to:
1) Send version message
2) Receive version and verack message
3) Send getaddr message
4) Receive addr message containing list of peering nodes
Stores state and height for node in Redis.
"""
handshake_msgs = []
addr_msgs = []
redis_conn.hset(key, 'state', "") # Set Redis hash for a new node
(address, port, services) = key[5:].split("-", 2)
services = int(services)
height = redis_conn.get('height')
if height:
height = int(height)
proxy = None
if address.endswith(".onion"):
proxy = SETTINGS['tor_proxy']
conn = Connection((address, int(port)),
(SETTINGS['source_address'], 0),
network=SETTINGS['network'],
socket_timeout=SETTINGS['socket_timeout'],
proxy=proxy,
protocol_version=SETTINGS['protocol_version'],
to_services=services,
from_services=SETTINGS['services'],
user_agent=SETTINGS['user_agent'],
height=height,
relay=SETTINGS['relay'])
try:
logging.debug("Connecting to %s", conn.to_addr)
conn.open()
handshake_msgs = conn.handshake()
addr_msgs = conn.getaddr()
except (ProtocolError, ConnectionError, socket.error) as err:
logging.debug("%s: %s", conn.to_addr, err)
finally:
conn.close()
gevent.sleep(0.3)
redis_pipe = redis_conn.pipeline()
if len(handshake_msgs) > 0:
version_msg = handshake_msgs[0]
from_services = version_msg.get('services', 0)
if from_services != services:
logging.debug("%s Expected %d, got %d for services", conn.to_addr,
services, from_services)
key = "node:{}-{}-{}".format(address, port, from_services)
height_key = "height:{}-{}-{}".format(address, port, from_services)
redis_pipe.setex(height_key, SETTINGS['max_age'],
version_msg.get('height', 0))
now = int(time.time())
peers = enumerate_node(redis_pipe, addr_msgs, now)
logging.debug("%s Peers: %d", conn.to_addr, peers)
redis_pipe.hset(key, 'state', "up")
redis_pipe.execute()
0
Example 2
def task():
"""
Assigned to a worker to retrieve (pop) a node from the reachable set and
attempt to establish and maintain connection with the node.
"""
node = REDIS_CONN.spop('reachable')
if node is None:
return
(address, port, services, height) = eval(node)
node = (address, port)
# Check if prefix has hit its limit
cidr_key = None
if ":" in address and SETTINGS['ipv6_prefix'] < 128:
cidr = ip_to_network(address, SETTINGS['ipv6_prefix'])
cidr_key = 'ping:cidr:{}'.format(cidr)
nodes = REDIS_CONN.incr(cidr_key)
logging.info("+CIDR %s: %d", cidr, nodes)
if nodes > SETTINGS['nodes_per_ipv6_prefix']:
logging.info("CIDR limit reached: %s", cidr)
nodes = REDIS_CONN.decr(cidr_key)
logging.info("-CIDR %s: %d", cidr, nodes)
return
if REDIS_CONN.sadd('open', node) == 0:
logging.info("Connection exists: %s", node)
if cidr_key:
nodes = REDIS_CONN.decr(cidr_key)
logging.info("-CIDR %s: %d", cidr, nodes)
return
proxy = None
if address.endswith(".onion"):
proxy = SETTINGS['tor_proxy']
handshake_msgs = []
conn = Connection(node, (SETTINGS['source_address'], 0),
socket_timeout=SETTINGS['socket_timeout'],
proxy=proxy,
protocol_version=SETTINGS['protocol_version'],
to_services=services,
from_services=SETTINGS['services'],
user_agent=SETTINGS['user_agent'],
height=height,
relay=SETTINGS['relay'])
try:
logging.debug("Connecting to %s", conn.to_addr)
conn.open()
handshake_msgs = conn.handshake()
except (ProtocolError, ConnectionError, socket.error) as err:
logging.debug("Closing %s (%s)", node, err)
conn.close()
if len(handshake_msgs) == 0:
if cidr_key:
nodes = REDIS_CONN.decr(cidr_key)
logging.info("-CIDR %s: %d", cidr, nodes)
REDIS_CONN.srem('open', node)
return
if address.endswith(".onion"):
# Map local port to .onion node
local_port = conn.socket.getsockname()[1]
logging.info("%s: 127.0.0.1:%d", conn.to_addr, local_port)
REDIS_CONN.set('onion:{}'.format(local_port), conn.to_addr)
Keepalive(conn=conn, version_msg=handshake_msgs[0]).keepalive()
conn.close()
if cidr_key:
nodes = REDIS_CONN.decr(cidr_key)
logging.info("-CIDR %s: %d", cidr, nodes)
REDIS_CONN.srem('open', node)
0
Example 3
def __init__(self, dsn="", user=None, host=None, unix_sock=None, port=5432, database=None, password=None, socket_timeout=60, ssl=False):
self._row_desc = None
if dsn:
# update connection parameters parsed of the conninfo dsn
opts = conninfo_parse(dsn)
database = opts.get("dbname", database)
user = opts.get("user", user)
password = opts.get("password", user)
host = opts.get("host", host)
port = int(opts.get("port", port))
ssl = opts.get("sslmode", 'disable') != 'disable'
try:
self.c = protocol.Connection(unix_sock=unix_sock, host=host, port=port, socket_timeout=socket_timeout, ssl=ssl)
self.c.authenticate(user, password=password, database=database)
except socket.error, e:
raise InterfaceError("communication error", e)
Cursor.__init__(self, self)
self._begin = PreparedStatement(self, "BEGIN TRANSACTION")
self._commit = PreparedStatement(self, "COMMIT TRANSACTION")
self._rollback = PreparedStatement(self, "ROLLBACK TRANSACTION")
self._unnamed_prepared_statement_lock = threading.RLock()
self.in_transaction = False
self.autocommit = False