id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
230,400 | orbingol/NURBS-Python | geomdl/_tessellate.py | surface_tessellate | def surface_tessellate(v1, v2, v3, v4, vidx, tidx, trim_curves, tessellate_args):
""" Triangular tessellation algorithm for surfaces with no trims.
This function can be directly used as an input to :func:`.make_triangle_mesh` using ``tessellate_func`` keyword
argument.
:param v1: vertex 1
:type v1: Vertex
:param v2: vertex 2
:type v2: Vertex
:param v3: vertex 3
:type v3: Vertex
:param v4: vertex 4
:type v4: Vertex
:param vidx: vertex numbering start value
:type vidx: int
:param tidx: triangle numbering start value
:type tidx: int
:param trim_curves: trim curves
:type: list, tuple
:param tessellate_args: tessellation arguments
:type tessellate_args: dict
:return: lists of vertex and triangle objects in (vertex_list, triangle_list) format
:type: tuple
"""
# Triangulate vertices
tris = polygon_triangulate(tidx, v1, v2, v3, v4)
# Return vertex and triangle lists
return [], tris | python | def surface_tessellate(v1, v2, v3, v4, vidx, tidx, trim_curves, tessellate_args):
""" Triangular tessellation algorithm for surfaces with no trims.
This function can be directly used as an input to :func:`.make_triangle_mesh` using ``tessellate_func`` keyword
argument.
:param v1: vertex 1
:type v1: Vertex
:param v2: vertex 2
:type v2: Vertex
:param v3: vertex 3
:type v3: Vertex
:param v4: vertex 4
:type v4: Vertex
:param vidx: vertex numbering start value
:type vidx: int
:param tidx: triangle numbering start value
:type tidx: int
:param trim_curves: trim curves
:type: list, tuple
:param tessellate_args: tessellation arguments
:type tessellate_args: dict
:return: lists of vertex and triangle objects in (vertex_list, triangle_list) format
:type: tuple
"""
# Triangulate vertices
tris = polygon_triangulate(tidx, v1, v2, v3, v4)
# Return vertex and triangle lists
return [], tris | [
"def",
"surface_tessellate",
"(",
"v1",
",",
"v2",
",",
"v3",
",",
"v4",
",",
"vidx",
",",
"tidx",
",",
"trim_curves",
",",
"tessellate_args",
")",
":",
"# Triangulate vertices",
"tris",
"=",
"polygon_triangulate",
"(",
"tidx",
",",
"v1",
",",
"v2",
",",
"v3",
",",
"v4",
")",
"# Return vertex and triangle lists",
"return",
"[",
"]",
",",
"tris"
] | Triangular tessellation algorithm for surfaces with no trims.
This function can be directly used as an input to :func:`.make_triangle_mesh` using ``tessellate_func`` keyword
argument.
:param v1: vertex 1
:type v1: Vertex
:param v2: vertex 2
:type v2: Vertex
:param v3: vertex 3
:type v3: Vertex
:param v4: vertex 4
:type v4: Vertex
:param vidx: vertex numbering start value
:type vidx: int
:param tidx: triangle numbering start value
:type tidx: int
:param trim_curves: trim curves
:type: list, tuple
:param tessellate_args: tessellation arguments
:type tessellate_args: dict
:return: lists of vertex and triangle objects in (vertex_list, triangle_list) format
:type: tuple | [
"Triangular",
"tessellation",
"algorithm",
"for",
"surfaces",
"with",
"no",
"trims",
"."
] | b1c6a8b51cf143ff58761438e93ba6baef470627 | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_tessellate.py#L217-L246 |
230,401 | Bearle/django-private-chat | django_private_chat/handlers.py | gone_online | def gone_online(stream):
"""
Distributes the users online status to everyone he has dialog with
"""
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
if session_id:
user_owner = get_user_from_session(session_id)
if user_owner:
logger.debug('User ' + user_owner.username + ' gone online')
# find all connections including user_owner as opponent,
# send them a message that the user has gone online
online_opponents = list(filter(lambda x: x[1] == user_owner.username, ws_connections))
online_opponents_sockets = [ws_connections[i] for i in online_opponents]
yield from fanout_message(online_opponents_sockets,
{'type': 'gone-online', 'usernames': [user_owner.username]})
else:
pass # invalid session id
else:
pass | python | def gone_online(stream):
"""
Distributes the users online status to everyone he has dialog with
"""
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
if session_id:
user_owner = get_user_from_session(session_id)
if user_owner:
logger.debug('User ' + user_owner.username + ' gone online')
# find all connections including user_owner as opponent,
# send them a message that the user has gone online
online_opponents = list(filter(lambda x: x[1] == user_owner.username, ws_connections))
online_opponents_sockets = [ws_connections[i] for i in online_opponents]
yield from fanout_message(online_opponents_sockets,
{'type': 'gone-online', 'usernames': [user_owner.username]})
else:
pass # invalid session id
else:
pass | [
"def",
"gone_online",
"(",
"stream",
")",
":",
"while",
"True",
":",
"packet",
"=",
"yield",
"from",
"stream",
".",
"get",
"(",
")",
"session_id",
"=",
"packet",
".",
"get",
"(",
"'session_key'",
")",
"if",
"session_id",
":",
"user_owner",
"=",
"get_user_from_session",
"(",
"session_id",
")",
"if",
"user_owner",
":",
"logger",
".",
"debug",
"(",
"'User '",
"+",
"user_owner",
".",
"username",
"+",
"' gone online'",
")",
"# find all connections including user_owner as opponent,\r",
"# send them a message that the user has gone online\r",
"online_opponents",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
"==",
"user_owner",
".",
"username",
",",
"ws_connections",
")",
")",
"online_opponents_sockets",
"=",
"[",
"ws_connections",
"[",
"i",
"]",
"for",
"i",
"in",
"online_opponents",
"]",
"yield",
"from",
"fanout_message",
"(",
"online_opponents_sockets",
",",
"{",
"'type'",
":",
"'gone-online'",
",",
"'usernames'",
":",
"[",
"user_owner",
".",
"username",
"]",
"}",
")",
"else",
":",
"pass",
"# invalid session id\r",
"else",
":",
"pass"
] | Distributes the users online status to everyone he has dialog with | [
"Distributes",
"the",
"users",
"online",
"status",
"to",
"everyone",
"he",
"has",
"dialog",
"with"
] | 5b51e65875795c5c0ce21bb631c53bd3aac4c26b | https://github.com/Bearle/django-private-chat/blob/5b51e65875795c5c0ce21bb631c53bd3aac4c26b/django_private_chat/handlers.py#L40-L60 |
230,402 | Bearle/django-private-chat | django_private_chat/handlers.py | new_messages_handler | def new_messages_handler(stream):
"""
Saves a new chat message to db and distributes msg to connected users
"""
# TODO: handle no user found exception
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
msg = packet.get('message')
username_opponent = packet.get('username')
if session_id and msg and username_opponent:
user_owner = get_user_from_session(session_id)
if user_owner:
user_opponent = get_user_model().objects.get(username=username_opponent)
dialog = get_dialogs_with_user(user_owner, user_opponent)
if len(dialog) > 0:
# Save the message
msg = models.Message.objects.create(
dialog=dialog[0],
sender=user_owner,
text=packet['message'],
read=False
)
packet['created'] = msg.get_formatted_create_datetime()
packet['sender_name'] = msg.sender.username
packet['message_id'] = msg.id
# Send the message
connections = []
# Find socket of the user which sent the message
if (user_owner.username, user_opponent.username) in ws_connections:
connections.append(ws_connections[(user_owner.username, user_opponent.username)])
# Find socket of the opponent
if (user_opponent.username, user_owner.username) in ws_connections:
connections.append(ws_connections[(user_opponent.username, user_owner.username)])
else:
# Find sockets of people who the opponent is talking with
opponent_connections = list(filter(lambda x: x[0] == user_opponent.username, ws_connections))
opponent_connections_sockets = [ws_connections[i] for i in opponent_connections]
connections.extend(opponent_connections_sockets)
yield from fanout_message(connections, packet)
else:
pass # no dialog found
else:
pass # no user_owner
else:
pass | python | def new_messages_handler(stream):
"""
Saves a new chat message to db and distributes msg to connected users
"""
# TODO: handle no user found exception
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
msg = packet.get('message')
username_opponent = packet.get('username')
if session_id and msg and username_opponent:
user_owner = get_user_from_session(session_id)
if user_owner:
user_opponent = get_user_model().objects.get(username=username_opponent)
dialog = get_dialogs_with_user(user_owner, user_opponent)
if len(dialog) > 0:
# Save the message
msg = models.Message.objects.create(
dialog=dialog[0],
sender=user_owner,
text=packet['message'],
read=False
)
packet['created'] = msg.get_formatted_create_datetime()
packet['sender_name'] = msg.sender.username
packet['message_id'] = msg.id
# Send the message
connections = []
# Find socket of the user which sent the message
if (user_owner.username, user_opponent.username) in ws_connections:
connections.append(ws_connections[(user_owner.username, user_opponent.username)])
# Find socket of the opponent
if (user_opponent.username, user_owner.username) in ws_connections:
connections.append(ws_connections[(user_opponent.username, user_owner.username)])
else:
# Find sockets of people who the opponent is talking with
opponent_connections = list(filter(lambda x: x[0] == user_opponent.username, ws_connections))
opponent_connections_sockets = [ws_connections[i] for i in opponent_connections]
connections.extend(opponent_connections_sockets)
yield from fanout_message(connections, packet)
else:
pass # no dialog found
else:
pass # no user_owner
else:
pass | [
"def",
"new_messages_handler",
"(",
"stream",
")",
":",
"# TODO: handle no user found exception\r",
"while",
"True",
":",
"packet",
"=",
"yield",
"from",
"stream",
".",
"get",
"(",
")",
"session_id",
"=",
"packet",
".",
"get",
"(",
"'session_key'",
")",
"msg",
"=",
"packet",
".",
"get",
"(",
"'message'",
")",
"username_opponent",
"=",
"packet",
".",
"get",
"(",
"'username'",
")",
"if",
"session_id",
"and",
"msg",
"and",
"username_opponent",
":",
"user_owner",
"=",
"get_user_from_session",
"(",
"session_id",
")",
"if",
"user_owner",
":",
"user_opponent",
"=",
"get_user_model",
"(",
")",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username_opponent",
")",
"dialog",
"=",
"get_dialogs_with_user",
"(",
"user_owner",
",",
"user_opponent",
")",
"if",
"len",
"(",
"dialog",
")",
">",
"0",
":",
"# Save the message\r",
"msg",
"=",
"models",
".",
"Message",
".",
"objects",
".",
"create",
"(",
"dialog",
"=",
"dialog",
"[",
"0",
"]",
",",
"sender",
"=",
"user_owner",
",",
"text",
"=",
"packet",
"[",
"'message'",
"]",
",",
"read",
"=",
"False",
")",
"packet",
"[",
"'created'",
"]",
"=",
"msg",
".",
"get_formatted_create_datetime",
"(",
")",
"packet",
"[",
"'sender_name'",
"]",
"=",
"msg",
".",
"sender",
".",
"username",
"packet",
"[",
"'message_id'",
"]",
"=",
"msg",
".",
"id",
"# Send the message\r",
"connections",
"=",
"[",
"]",
"# Find socket of the user which sent the message\r",
"if",
"(",
"user_owner",
".",
"username",
",",
"user_opponent",
".",
"username",
")",
"in",
"ws_connections",
":",
"connections",
".",
"append",
"(",
"ws_connections",
"[",
"(",
"user_owner",
".",
"username",
",",
"user_opponent",
".",
"username",
")",
"]",
")",
"# Find socket of the opponent\r",
"if",
"(",
"user_opponent",
".",
"username",
",",
"user_owner",
".",
"username",
")",
"in",
"ws_connections",
":",
"connections",
".",
"append",
"(",
"ws_connections",
"[",
"(",
"user_opponent",
".",
"username",
",",
"user_owner",
".",
"username",
")",
"]",
")",
"else",
":",
"# Find sockets of people who the opponent is talking with\r",
"opponent_connections",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
"==",
"user_opponent",
".",
"username",
",",
"ws_connections",
")",
")",
"opponent_connections_sockets",
"=",
"[",
"ws_connections",
"[",
"i",
"]",
"for",
"i",
"in",
"opponent_connections",
"]",
"connections",
".",
"extend",
"(",
"opponent_connections_sockets",
")",
"yield",
"from",
"fanout_message",
"(",
"connections",
",",
"packet",
")",
"else",
":",
"pass",
"# no dialog found\r",
"else",
":",
"pass",
"# no user_owner\r",
"else",
":",
"pass"
] | Saves a new chat message to db and distributes msg to connected users | [
"Saves",
"a",
"new",
"chat",
"message",
"to",
"db",
"and",
"distributes",
"msg",
"to",
"connected",
"users"
] | 5b51e65875795c5c0ce21bb631c53bd3aac4c26b | https://github.com/Bearle/django-private-chat/blob/5b51e65875795c5c0ce21bb631c53bd3aac4c26b/django_private_chat/handlers.py#L118-L165 |
230,403 | Bearle/django-private-chat | django_private_chat/handlers.py | users_changed_handler | def users_changed_handler(stream):
"""
Sends connected client list of currently active users in the chatroom
"""
while True:
yield from stream.get()
# Get list list of current active users
users = [
{'username': username, 'uuid': uuid_str}
for username, uuid_str in ws_connections.values()
]
# Make packet with list of new users (sorted by username)
packet = {
'type': 'users-changed',
'value': sorted(users, key=lambda i: i['username'])
}
logger.debug(packet)
yield from fanout_message(ws_connections.keys(), packet) | python | def users_changed_handler(stream):
"""
Sends connected client list of currently active users in the chatroom
"""
while True:
yield from stream.get()
# Get list list of current active users
users = [
{'username': username, 'uuid': uuid_str}
for username, uuid_str in ws_connections.values()
]
# Make packet with list of new users (sorted by username)
packet = {
'type': 'users-changed',
'value': sorted(users, key=lambda i: i['username'])
}
logger.debug(packet)
yield from fanout_message(ws_connections.keys(), packet) | [
"def",
"users_changed_handler",
"(",
"stream",
")",
":",
"while",
"True",
":",
"yield",
"from",
"stream",
".",
"get",
"(",
")",
"# Get list list of current active users\r",
"users",
"=",
"[",
"{",
"'username'",
":",
"username",
",",
"'uuid'",
":",
"uuid_str",
"}",
"for",
"username",
",",
"uuid_str",
"in",
"ws_connections",
".",
"values",
"(",
")",
"]",
"# Make packet with list of new users (sorted by username)\r",
"packet",
"=",
"{",
"'type'",
":",
"'users-changed'",
",",
"'value'",
":",
"sorted",
"(",
"users",
",",
"key",
"=",
"lambda",
"i",
":",
"i",
"[",
"'username'",
"]",
")",
"}",
"logger",
".",
"debug",
"(",
"packet",
")",
"yield",
"from",
"fanout_message",
"(",
"ws_connections",
".",
"keys",
"(",
")",
",",
"packet",
")"
] | Sends connected client list of currently active users in the chatroom | [
"Sends",
"connected",
"client",
"list",
"of",
"currently",
"active",
"users",
"in",
"the",
"chatroom"
] | 5b51e65875795c5c0ce21bb631c53bd3aac4c26b | https://github.com/Bearle/django-private-chat/blob/5b51e65875795c5c0ce21bb631c53bd3aac4c26b/django_private_chat/handlers.py#L169-L188 |
230,404 | Bearle/django-private-chat | django_private_chat/handlers.py | is_typing_handler | def is_typing_handler(stream):
"""
Show message to opponent if user is typing message
"""
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
user_opponent = packet.get('username')
typing = packet.get('typing')
if session_id and user_opponent and typing is not None:
user_owner = get_user_from_session(session_id)
if user_owner:
opponent_socket = ws_connections.get((user_opponent, user_owner.username))
if typing and opponent_socket:
yield from target_message(opponent_socket,
{'type': 'opponent-typing', 'username': user_opponent})
else:
pass # invalid session id
else:
pass | python | def is_typing_handler(stream):
"""
Show message to opponent if user is typing message
"""
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
user_opponent = packet.get('username')
typing = packet.get('typing')
if session_id and user_opponent and typing is not None:
user_owner = get_user_from_session(session_id)
if user_owner:
opponent_socket = ws_connections.get((user_opponent, user_owner.username))
if typing and opponent_socket:
yield from target_message(opponent_socket,
{'type': 'opponent-typing', 'username': user_opponent})
else:
pass # invalid session id
else:
pass | [
"def",
"is_typing_handler",
"(",
"stream",
")",
":",
"while",
"True",
":",
"packet",
"=",
"yield",
"from",
"stream",
".",
"get",
"(",
")",
"session_id",
"=",
"packet",
".",
"get",
"(",
"'session_key'",
")",
"user_opponent",
"=",
"packet",
".",
"get",
"(",
"'username'",
")",
"typing",
"=",
"packet",
".",
"get",
"(",
"'typing'",
")",
"if",
"session_id",
"and",
"user_opponent",
"and",
"typing",
"is",
"not",
"None",
":",
"user_owner",
"=",
"get_user_from_session",
"(",
"session_id",
")",
"if",
"user_owner",
":",
"opponent_socket",
"=",
"ws_connections",
".",
"get",
"(",
"(",
"user_opponent",
",",
"user_owner",
".",
"username",
")",
")",
"if",
"typing",
"and",
"opponent_socket",
":",
"yield",
"from",
"target_message",
"(",
"opponent_socket",
",",
"{",
"'type'",
":",
"'opponent-typing'",
",",
"'username'",
":",
"user_opponent",
"}",
")",
"else",
":",
"pass",
"# invalid session id\r",
"else",
":",
"pass"
] | Show message to opponent if user is typing message | [
"Show",
"message",
"to",
"opponent",
"if",
"user",
"is",
"typing",
"message"
] | 5b51e65875795c5c0ce21bb631c53bd3aac4c26b | https://github.com/Bearle/django-private-chat/blob/5b51e65875795c5c0ce21bb631c53bd3aac4c26b/django_private_chat/handlers.py#L192-L211 |
230,405 | Bearle/django-private-chat | django_private_chat/handlers.py | read_message_handler | def read_message_handler(stream):
"""
Send message to user if the opponent has read the message
"""
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
user_opponent = packet.get('username')
message_id = packet.get('message_id')
if session_id and user_opponent and message_id is not None:
user_owner = get_user_from_session(session_id)
if user_owner:
message = models.Message.objects.filter(id=message_id).first()
if message:
message.read = True
message.save()
logger.debug('Message ' + str(message_id) + ' is now read')
opponent_socket = ws_connections.get((user_opponent, user_owner.username))
if opponent_socket:
yield from target_message(opponent_socket,
{'type': 'opponent-read-message',
'username': user_opponent, 'message_id': message_id})
else:
pass # message not found
else:
pass # invalid session id
else:
pass | python | def read_message_handler(stream):
"""
Send message to user if the opponent has read the message
"""
while True:
packet = yield from stream.get()
session_id = packet.get('session_key')
user_opponent = packet.get('username')
message_id = packet.get('message_id')
if session_id and user_opponent and message_id is not None:
user_owner = get_user_from_session(session_id)
if user_owner:
message = models.Message.objects.filter(id=message_id).first()
if message:
message.read = True
message.save()
logger.debug('Message ' + str(message_id) + ' is now read')
opponent_socket = ws_connections.get((user_opponent, user_owner.username))
if opponent_socket:
yield from target_message(opponent_socket,
{'type': 'opponent-read-message',
'username': user_opponent, 'message_id': message_id})
else:
pass # message not found
else:
pass # invalid session id
else:
pass | [
"def",
"read_message_handler",
"(",
"stream",
")",
":",
"while",
"True",
":",
"packet",
"=",
"yield",
"from",
"stream",
".",
"get",
"(",
")",
"session_id",
"=",
"packet",
".",
"get",
"(",
"'session_key'",
")",
"user_opponent",
"=",
"packet",
".",
"get",
"(",
"'username'",
")",
"message_id",
"=",
"packet",
".",
"get",
"(",
"'message_id'",
")",
"if",
"session_id",
"and",
"user_opponent",
"and",
"message_id",
"is",
"not",
"None",
":",
"user_owner",
"=",
"get_user_from_session",
"(",
"session_id",
")",
"if",
"user_owner",
":",
"message",
"=",
"models",
".",
"Message",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"message_id",
")",
".",
"first",
"(",
")",
"if",
"message",
":",
"message",
".",
"read",
"=",
"True",
"message",
".",
"save",
"(",
")",
"logger",
".",
"debug",
"(",
"'Message '",
"+",
"str",
"(",
"message_id",
")",
"+",
"' is now read'",
")",
"opponent_socket",
"=",
"ws_connections",
".",
"get",
"(",
"(",
"user_opponent",
",",
"user_owner",
".",
"username",
")",
")",
"if",
"opponent_socket",
":",
"yield",
"from",
"target_message",
"(",
"opponent_socket",
",",
"{",
"'type'",
":",
"'opponent-read-message'",
",",
"'username'",
":",
"user_opponent",
",",
"'message_id'",
":",
"message_id",
"}",
")",
"else",
":",
"pass",
"# message not found\r",
"else",
":",
"pass",
"# invalid session id\r",
"else",
":",
"pass"
] | Send message to user if the opponent has read the message | [
"Send",
"message",
"to",
"user",
"if",
"the",
"opponent",
"has",
"read",
"the",
"message"
] | 5b51e65875795c5c0ce21bb631c53bd3aac4c26b | https://github.com/Bearle/django-private-chat/blob/5b51e65875795c5c0ce21bb631c53bd3aac4c26b/django_private_chat/handlers.py#L215-L242 |
230,406 | Bearle/django-private-chat | django_private_chat/handlers.py | main_handler | def main_handler(websocket, path):
"""
An Asyncio Task is created for every new websocket client connection
that is established. This coroutine listens to messages from the connected
client and routes the message to the proper queue.
This coroutine can be thought of as a producer.
"""
# Get users name from the path
path = path.split('/')
username = path[2]
session_id = path[1]
user_owner = get_user_from_session(session_id)
if user_owner:
user_owner = user_owner.username
# Persist users connection, associate user w/a unique ID
ws_connections[(user_owner, username)] = websocket
# While the websocket is open, listen for incoming messages/events
# if unable to listening for messages/events, then disconnect the client
try:
while websocket.open:
data = yield from websocket.recv()
if not data:
continue
logger.debug(data)
try:
yield from router.MessageRouter(data)()
except Exception as e:
logger.error('could not route msg', e)
except websockets.exceptions.InvalidState: # User disconnected
pass
finally:
del ws_connections[(user_owner, username)]
else:
logger.info("Got invalid session_id attempt to connect " + session_id) | python | def main_handler(websocket, path):
"""
An Asyncio Task is created for every new websocket client connection
that is established. This coroutine listens to messages from the connected
client and routes the message to the proper queue.
This coroutine can be thought of as a producer.
"""
# Get users name from the path
path = path.split('/')
username = path[2]
session_id = path[1]
user_owner = get_user_from_session(session_id)
if user_owner:
user_owner = user_owner.username
# Persist users connection, associate user w/a unique ID
ws_connections[(user_owner, username)] = websocket
# While the websocket is open, listen for incoming messages/events
# if unable to listening for messages/events, then disconnect the client
try:
while websocket.open:
data = yield from websocket.recv()
if not data:
continue
logger.debug(data)
try:
yield from router.MessageRouter(data)()
except Exception as e:
logger.error('could not route msg', e)
except websockets.exceptions.InvalidState: # User disconnected
pass
finally:
del ws_connections[(user_owner, username)]
else:
logger.info("Got invalid session_id attempt to connect " + session_id) | [
"def",
"main_handler",
"(",
"websocket",
",",
"path",
")",
":",
"# Get users name from the path\r",
"path",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"username",
"=",
"path",
"[",
"2",
"]",
"session_id",
"=",
"path",
"[",
"1",
"]",
"user_owner",
"=",
"get_user_from_session",
"(",
"session_id",
")",
"if",
"user_owner",
":",
"user_owner",
"=",
"user_owner",
".",
"username",
"# Persist users connection, associate user w/a unique ID\r",
"ws_connections",
"[",
"(",
"user_owner",
",",
"username",
")",
"]",
"=",
"websocket",
"# While the websocket is open, listen for incoming messages/events\r",
"# if unable to listening for messages/events, then disconnect the client\r",
"try",
":",
"while",
"websocket",
".",
"open",
":",
"data",
"=",
"yield",
"from",
"websocket",
".",
"recv",
"(",
")",
"if",
"not",
"data",
":",
"continue",
"logger",
".",
"debug",
"(",
"data",
")",
"try",
":",
"yield",
"from",
"router",
".",
"MessageRouter",
"(",
"data",
")",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"'could not route msg'",
",",
"e",
")",
"except",
"websockets",
".",
"exceptions",
".",
"InvalidState",
":",
"# User disconnected\r",
"pass",
"finally",
":",
"del",
"ws_connections",
"[",
"(",
"user_owner",
",",
"username",
")",
"]",
"else",
":",
"logger",
".",
"info",
"(",
"\"Got invalid session_id attempt to connect \"",
"+",
"session_id",
")"
] | An Asyncio Task is created for every new websocket client connection
that is established. This coroutine listens to messages from the connected
client and routes the message to the proper queue.
This coroutine can be thought of as a producer. | [
"An",
"Asyncio",
"Task",
"is",
"created",
"for",
"every",
"new",
"websocket",
"client",
"connection",
"that",
"is",
"established",
".",
"This",
"coroutine",
"listens",
"to",
"messages",
"from",
"the",
"connected",
"client",
"and",
"routes",
"the",
"message",
"to",
"the",
"proper",
"queue",
".",
"This",
"coroutine",
"can",
"be",
"thought",
"of",
"as",
"a",
"producer",
"."
] | 5b51e65875795c5c0ce21bb631c53bd3aac4c26b | https://github.com/Bearle/django-private-chat/blob/5b51e65875795c5c0ce21bb631c53bd3aac4c26b/django_private_chat/handlers.py#L246-L283 |
230,407 | blockstack/blockstack-core | api/search/substring_search.py | anyword_substring_search_inner | def anyword_substring_search_inner(query_word, target_words):
""" return True if ANY target_word matches a query_word
"""
for target_word in target_words:
if(target_word.startswith(query_word)):
return query_word
return False | python | def anyword_substring_search_inner(query_word, target_words):
""" return True if ANY target_word matches a query_word
"""
for target_word in target_words:
if(target_word.startswith(query_word)):
return query_word
return False | [
"def",
"anyword_substring_search_inner",
"(",
"query_word",
",",
"target_words",
")",
":",
"for",
"target_word",
"in",
"target_words",
":",
"if",
"(",
"target_word",
".",
"startswith",
"(",
"query_word",
")",
")",
":",
"return",
"query_word",
"return",
"False"
] | return True if ANY target_word matches a query_word | [
"return",
"True",
"if",
"ANY",
"target_word",
"matches",
"a",
"query_word"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/search/substring_search.py#L41-L50 |
230,408 | blockstack/blockstack-core | api/search/substring_search.py | anyword_substring_search | def anyword_substring_search(target_words, query_words):
""" return True if all query_words match
"""
matches_required = len(query_words)
matches_found = 0
for query_word in query_words:
reply = anyword_substring_search_inner(query_word, target_words)
if reply is not False:
matches_found += 1
else:
# this is imp, otherwise will keep checking
# when the final answer is already False
return False
if(matches_found == matches_required):
return True
else:
return False | python | def anyword_substring_search(target_words, query_words):
""" return True if all query_words match
"""
matches_required = len(query_words)
matches_found = 0
for query_word in query_words:
reply = anyword_substring_search_inner(query_word, target_words)
if reply is not False:
matches_found += 1
else:
# this is imp, otherwise will keep checking
# when the final answer is already False
return False
if(matches_found == matches_required):
return True
else:
return False | [
"def",
"anyword_substring_search",
"(",
"target_words",
",",
"query_words",
")",
":",
"matches_required",
"=",
"len",
"(",
"query_words",
")",
"matches_found",
"=",
"0",
"for",
"query_word",
"in",
"query_words",
":",
"reply",
"=",
"anyword_substring_search_inner",
"(",
"query_word",
",",
"target_words",
")",
"if",
"reply",
"is",
"not",
"False",
":",
"matches_found",
"+=",
"1",
"else",
":",
"# this is imp, otherwise will keep checking",
"# when the final answer is already False",
"return",
"False",
"if",
"(",
"matches_found",
"==",
"matches_required",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | return True if all query_words match | [
"return",
"True",
"if",
"all",
"query_words",
"match"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/search/substring_search.py#L53-L76 |
230,409 | blockstack/blockstack-core | api/search/substring_search.py | substring_search | def substring_search(query, list_of_strings, limit_results=DEFAULT_LIMIT):
""" main function to call for searching
"""
matching = []
query_words = query.split(' ')
# sort by longest word (higest probability of not finding a match)
query_words.sort(key=len, reverse=True)
counter = 0
for s in list_of_strings:
target_words = s.split(' ')
# the anyword searching function is separate
if(anyword_substring_search(target_words, query_words)):
matching.append(s)
# limit results
counter += 1
if(counter == limit_results):
break
return matching | python | def substring_search(query, list_of_strings, limit_results=DEFAULT_LIMIT):
""" main function to call for searching
"""
matching = []
query_words = query.split(' ')
# sort by longest word (higest probability of not finding a match)
query_words.sort(key=len, reverse=True)
counter = 0
for s in list_of_strings:
target_words = s.split(' ')
# the anyword searching function is separate
if(anyword_substring_search(target_words, query_words)):
matching.append(s)
# limit results
counter += 1
if(counter == limit_results):
break
return matching | [
"def",
"substring_search",
"(",
"query",
",",
"list_of_strings",
",",
"limit_results",
"=",
"DEFAULT_LIMIT",
")",
":",
"matching",
"=",
"[",
"]",
"query_words",
"=",
"query",
".",
"split",
"(",
"' '",
")",
"# sort by longest word (higest probability of not finding a match)",
"query_words",
".",
"sort",
"(",
"key",
"=",
"len",
",",
"reverse",
"=",
"True",
")",
"counter",
"=",
"0",
"for",
"s",
"in",
"list_of_strings",
":",
"target_words",
"=",
"s",
".",
"split",
"(",
"' '",
")",
"# the anyword searching function is separate",
"if",
"(",
"anyword_substring_search",
"(",
"target_words",
",",
"query_words",
")",
")",
":",
"matching",
".",
"append",
"(",
"s",
")",
"# limit results",
"counter",
"+=",
"1",
"if",
"(",
"counter",
"==",
"limit_results",
")",
":",
"break",
"return",
"matching"
] | main function to call for searching | [
"main",
"function",
"to",
"call",
"for",
"searching"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/search/substring_search.py#L79-L105 |
230,410 | blockstack/blockstack-core | api/search/substring_search.py | search_people_by_bio | def search_people_by_bio(query, limit_results=DEFAULT_LIMIT,
index=['onename_people_index']):
""" queries lucene index to find a nearest match, output is profile username
"""
from pyes import QueryStringQuery, ES
conn = ES()
q = QueryStringQuery(query,
search_fields=['username', 'profile_bio'],
default_operator='and')
results = conn.search(query=q, size=20, indices=index)
count = conn.count(query=q)
count = count.count
# having 'or' gives more results but results quality goes down
if(count == 0):
q = QueryStringQuery(query,
search_fields=['username', 'profile_bio'],
default_operator='or')
results = conn.search(query=q, size=20, indices=index)
results_list = []
counter = 0
for profile in results:
username = profile['username']
results_list.append(username)
counter += 1
if(counter == limit_results):
break
return results_list | python | def search_people_by_bio(query, limit_results=DEFAULT_LIMIT,
index=['onename_people_index']):
""" queries lucene index to find a nearest match, output is profile username
"""
from pyes import QueryStringQuery, ES
conn = ES()
q = QueryStringQuery(query,
search_fields=['username', 'profile_bio'],
default_operator='and')
results = conn.search(query=q, size=20, indices=index)
count = conn.count(query=q)
count = count.count
# having 'or' gives more results but results quality goes down
if(count == 0):
q = QueryStringQuery(query,
search_fields=['username', 'profile_bio'],
default_operator='or')
results = conn.search(query=q, size=20, indices=index)
results_list = []
counter = 0
for profile in results:
username = profile['username']
results_list.append(username)
counter += 1
if(counter == limit_results):
break
return results_list | [
"def",
"search_people_by_bio",
"(",
"query",
",",
"limit_results",
"=",
"DEFAULT_LIMIT",
",",
"index",
"=",
"[",
"'onename_people_index'",
"]",
")",
":",
"from",
"pyes",
"import",
"QueryStringQuery",
",",
"ES",
"conn",
"=",
"ES",
"(",
")",
"q",
"=",
"QueryStringQuery",
"(",
"query",
",",
"search_fields",
"=",
"[",
"'username'",
",",
"'profile_bio'",
"]",
",",
"default_operator",
"=",
"'and'",
")",
"results",
"=",
"conn",
".",
"search",
"(",
"query",
"=",
"q",
",",
"size",
"=",
"20",
",",
"indices",
"=",
"index",
")",
"count",
"=",
"conn",
".",
"count",
"(",
"query",
"=",
"q",
")",
"count",
"=",
"count",
".",
"count",
"# having 'or' gives more results but results quality goes down",
"if",
"(",
"count",
"==",
"0",
")",
":",
"q",
"=",
"QueryStringQuery",
"(",
"query",
",",
"search_fields",
"=",
"[",
"'username'",
",",
"'profile_bio'",
"]",
",",
"default_operator",
"=",
"'or'",
")",
"results",
"=",
"conn",
".",
"search",
"(",
"query",
"=",
"q",
",",
"size",
"=",
"20",
",",
"indices",
"=",
"index",
")",
"results_list",
"=",
"[",
"]",
"counter",
"=",
"0",
"for",
"profile",
"in",
"results",
":",
"username",
"=",
"profile",
"[",
"'username'",
"]",
"results_list",
".",
"append",
"(",
"username",
")",
"counter",
"+=",
"1",
"if",
"(",
"counter",
"==",
"limit_results",
")",
":",
"break",
"return",
"results_list"
] | queries lucene index to find a nearest match, output is profile username | [
"queries",
"lucene",
"index",
"to",
"find",
"a",
"nearest",
"match",
"output",
"is",
"profile",
"username"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/search/substring_search.py#L172-L210 |
230,411 | blockstack/blockstack-core | api/search/substring_search.py | order_search_results | def order_search_results(query, search_results):
""" order of results should be a) query in first name, b) query in last name
"""
results = search_results
results_names = []
old_query = query
query = query.split(' ')
first_word = ''
second_word = ''
third_word = ''
if(len(query) < 2):
first_word = old_query
else:
first_word = query[0]
second_word = query[1]
if(len(query) > 2):
third_word = query[2]
# save results for multiple passes
results_second = []
results_third = []
for result in results:
result_list = result.split(' ')
try:
if(result_list[0].startswith(first_word)):
results_names.append(result)
else:
results_second.append(result)
except:
results_second.append(result)
for result in results_second:
result_list = result.split(' ')
try:
if(result_list[1].startswith(first_word)):
results_names.append(result)
else:
results_third.append(result)
except:
results_third.append(result)
# results are either in results_names (filtered)
# or unprocessed in results_third (last pass)
return results_names + results_third | python | def order_search_results(query, search_results):
""" order of results should be a) query in first name, b) query in last name
"""
results = search_results
results_names = []
old_query = query
query = query.split(' ')
first_word = ''
second_word = ''
third_word = ''
if(len(query) < 2):
first_word = old_query
else:
first_word = query[0]
second_word = query[1]
if(len(query) > 2):
third_word = query[2]
# save results for multiple passes
results_second = []
results_third = []
for result in results:
result_list = result.split(' ')
try:
if(result_list[0].startswith(first_word)):
results_names.append(result)
else:
results_second.append(result)
except:
results_second.append(result)
for result in results_second:
result_list = result.split(' ')
try:
if(result_list[1].startswith(first_word)):
results_names.append(result)
else:
results_third.append(result)
except:
results_third.append(result)
# results are either in results_names (filtered)
# or unprocessed in results_third (last pass)
return results_names + results_third | [
"def",
"order_search_results",
"(",
"query",
",",
"search_results",
")",
":",
"results",
"=",
"search_results",
"results_names",
"=",
"[",
"]",
"old_query",
"=",
"query",
"query",
"=",
"query",
".",
"split",
"(",
"' '",
")",
"first_word",
"=",
"''",
"second_word",
"=",
"''",
"third_word",
"=",
"''",
"if",
"(",
"len",
"(",
"query",
")",
"<",
"2",
")",
":",
"first_word",
"=",
"old_query",
"else",
":",
"first_word",
"=",
"query",
"[",
"0",
"]",
"second_word",
"=",
"query",
"[",
"1",
"]",
"if",
"(",
"len",
"(",
"query",
")",
">",
"2",
")",
":",
"third_word",
"=",
"query",
"[",
"2",
"]",
"# save results for multiple passes",
"results_second",
"=",
"[",
"]",
"results_third",
"=",
"[",
"]",
"for",
"result",
"in",
"results",
":",
"result_list",
"=",
"result",
".",
"split",
"(",
"' '",
")",
"try",
":",
"if",
"(",
"result_list",
"[",
"0",
"]",
".",
"startswith",
"(",
"first_word",
")",
")",
":",
"results_names",
".",
"append",
"(",
"result",
")",
"else",
":",
"results_second",
".",
"append",
"(",
"result",
")",
"except",
":",
"results_second",
".",
"append",
"(",
"result",
")",
"for",
"result",
"in",
"results_second",
":",
"result_list",
"=",
"result",
".",
"split",
"(",
"' '",
")",
"try",
":",
"if",
"(",
"result_list",
"[",
"1",
"]",
".",
"startswith",
"(",
"first_word",
")",
")",
":",
"results_names",
".",
"append",
"(",
"result",
")",
"else",
":",
"results_third",
".",
"append",
"(",
"result",
")",
"except",
":",
"results_third",
".",
"append",
"(",
"result",
")",
"# results are either in results_names (filtered)",
"# or unprocessed in results_third (last pass)",
"return",
"results_names",
"+",
"results_third"
] | order of results should be a) query in first name, b) query in last name | [
"order",
"of",
"results",
"should",
"be",
"a",
")",
"query",
"in",
"first",
"name",
"b",
")",
"query",
"in",
"last",
"name"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/search/substring_search.py#L242-L295 |
230,412 | blockstack/blockstack-core | blockstack/lib/storage/auth.py | get_data_hash | def get_data_hash(data_txt):
"""
Generate a hash over data for immutable storage.
Return the hex string.
"""
h = hashlib.sha256()
h.update(data_txt)
return h.hexdigest() | python | def get_data_hash(data_txt):
"""
Generate a hash over data for immutable storage.
Return the hex string.
"""
h = hashlib.sha256()
h.update(data_txt)
return h.hexdigest() | [
"def",
"get_data_hash",
"(",
"data_txt",
")",
":",
"h",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"h",
".",
"update",
"(",
"data_txt",
")",
"return",
"h",
".",
"hexdigest",
"(",
")"
] | Generate a hash over data for immutable storage.
Return the hex string. | [
"Generate",
"a",
"hash",
"over",
"data",
"for",
"immutable",
"storage",
".",
"Return",
"the",
"hex",
"string",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/storage/auth.py#L32-L39 |
230,413 | blockstack/blockstack-core | blockstack/lib/storage/auth.py | verify_zonefile | def verify_zonefile( zonefile_str, value_hash ):
"""
Verify that a zonefile hashes to the given value hash
@zonefile_str must be the zonefile as a serialized string
"""
zonefile_hash = get_zonefile_data_hash( zonefile_str )
if zonefile_hash != value_hash:
log.debug("Zonefile hash mismatch: expected %s, got %s" % (value_hash, zonefile_hash))
return False
return True | python | def verify_zonefile( zonefile_str, value_hash ):
"""
Verify that a zonefile hashes to the given value hash
@zonefile_str must be the zonefile as a serialized string
"""
zonefile_hash = get_zonefile_data_hash( zonefile_str )
if zonefile_hash != value_hash:
log.debug("Zonefile hash mismatch: expected %s, got %s" % (value_hash, zonefile_hash))
return False
return True | [
"def",
"verify_zonefile",
"(",
"zonefile_str",
",",
"value_hash",
")",
":",
"zonefile_hash",
"=",
"get_zonefile_data_hash",
"(",
"zonefile_str",
")",
"if",
"zonefile_hash",
"!=",
"value_hash",
":",
"log",
".",
"debug",
"(",
"\"Zonefile hash mismatch: expected %s, got %s\"",
"%",
"(",
"value_hash",
",",
"zonefile_hash",
")",
")",
"return",
"False",
"return",
"True"
] | Verify that a zonefile hashes to the given value hash
@zonefile_str must be the zonefile as a serialized string | [
"Verify",
"that",
"a",
"zonefile",
"hashes",
"to",
"the",
"given",
"value",
"hash"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/storage/auth.py#L50-L60 |
230,414 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_table_lock | def atlas_peer_table_lock():
"""
Lock the global health info table.
Return the table.
"""
global PEER_TABLE_LOCK, PEER_TABLE, PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK
if PEER_TABLE_LOCK_HOLDER is not None:
assert PEER_TABLE_LOCK_HOLDER != threading.current_thread(), "DEADLOCK"
# log.warning("\n\nPossible contention: lock from %s (but held by %s at)\n%s\n\n" % (threading.current_thread(), PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK))
PEER_TABLE_LOCK.acquire()
PEER_TABLE_LOCK_HOLDER = threading.current_thread()
PEER_TABLE_LOCK_TRACEBACK = traceback.format_stack()
# log.debug("\n\npeer table lock held by %s at \n%s\n\n" % (PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK))
return PEER_TABLE | python | def atlas_peer_table_lock():
"""
Lock the global health info table.
Return the table.
"""
global PEER_TABLE_LOCK, PEER_TABLE, PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK
if PEER_TABLE_LOCK_HOLDER is not None:
assert PEER_TABLE_LOCK_HOLDER != threading.current_thread(), "DEADLOCK"
# log.warning("\n\nPossible contention: lock from %s (but held by %s at)\n%s\n\n" % (threading.current_thread(), PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK))
PEER_TABLE_LOCK.acquire()
PEER_TABLE_LOCK_HOLDER = threading.current_thread()
PEER_TABLE_LOCK_TRACEBACK = traceback.format_stack()
# log.debug("\n\npeer table lock held by %s at \n%s\n\n" % (PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK))
return PEER_TABLE | [
"def",
"atlas_peer_table_lock",
"(",
")",
":",
"global",
"PEER_TABLE_LOCK",
",",
"PEER_TABLE",
",",
"PEER_TABLE_LOCK_HOLDER",
",",
"PEER_TABLE_LOCK_TRACEBACK",
"if",
"PEER_TABLE_LOCK_HOLDER",
"is",
"not",
"None",
":",
"assert",
"PEER_TABLE_LOCK_HOLDER",
"!=",
"threading",
".",
"current_thread",
"(",
")",
",",
"\"DEADLOCK\"",
"# log.warning(\"\\n\\nPossible contention: lock from %s (but held by %s at)\\n%s\\n\\n\" % (threading.current_thread(), PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK))",
"PEER_TABLE_LOCK",
".",
"acquire",
"(",
")",
"PEER_TABLE_LOCK_HOLDER",
"=",
"threading",
".",
"current_thread",
"(",
")",
"PEER_TABLE_LOCK_TRACEBACK",
"=",
"traceback",
".",
"format_stack",
"(",
")",
"# log.debug(\"\\n\\npeer table lock held by %s at \\n%s\\n\\n\" % (PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK))",
"return",
"PEER_TABLE"
] | Lock the global health info table.
Return the table. | [
"Lock",
"the",
"global",
"health",
"info",
"table",
".",
"Return",
"the",
"table",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L352-L368 |
230,415 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_table_unlock | def atlas_peer_table_unlock():
"""
Unlock the global health info table.
"""
global PEER_TABLE_LOCK, PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK
try:
assert PEER_TABLE_LOCK_HOLDER == threading.current_thread()
except:
log.error("Locked by %s, unlocked by %s" % (PEER_TABLE_LOCK_HOLDER, threading.current_thread()))
log.error("Holder locked from:\n%s" % "".join(PEER_TABLE_LOCK_TRACEBACK))
log.error("Errant thread unlocked from:\n%s" % "".join(traceback.format_stack()))
os.abort()
# log.debug("\n\npeer table lock released by %s at \n%s\n\n" % (PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK))
PEER_TABLE_LOCK_HOLDER = None
PEER_TABLE_LOCK_TRACEBACK = None
PEER_TABLE_LOCK.release()
return | python | def atlas_peer_table_unlock():
"""
Unlock the global health info table.
"""
global PEER_TABLE_LOCK, PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK
try:
assert PEER_TABLE_LOCK_HOLDER == threading.current_thread()
except:
log.error("Locked by %s, unlocked by %s" % (PEER_TABLE_LOCK_HOLDER, threading.current_thread()))
log.error("Holder locked from:\n%s" % "".join(PEER_TABLE_LOCK_TRACEBACK))
log.error("Errant thread unlocked from:\n%s" % "".join(traceback.format_stack()))
os.abort()
# log.debug("\n\npeer table lock released by %s at \n%s\n\n" % (PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK))
PEER_TABLE_LOCK_HOLDER = None
PEER_TABLE_LOCK_TRACEBACK = None
PEER_TABLE_LOCK.release()
return | [
"def",
"atlas_peer_table_unlock",
"(",
")",
":",
"global",
"PEER_TABLE_LOCK",
",",
"PEER_TABLE_LOCK_HOLDER",
",",
"PEER_TABLE_LOCK_TRACEBACK",
"try",
":",
"assert",
"PEER_TABLE_LOCK_HOLDER",
"==",
"threading",
".",
"current_thread",
"(",
")",
"except",
":",
"log",
".",
"error",
"(",
"\"Locked by %s, unlocked by %s\"",
"%",
"(",
"PEER_TABLE_LOCK_HOLDER",
",",
"threading",
".",
"current_thread",
"(",
")",
")",
")",
"log",
".",
"error",
"(",
"\"Holder locked from:\\n%s\"",
"%",
"\"\"",
".",
"join",
"(",
"PEER_TABLE_LOCK_TRACEBACK",
")",
")",
"log",
".",
"error",
"(",
"\"Errant thread unlocked from:\\n%s\"",
"%",
"\"\"",
".",
"join",
"(",
"traceback",
".",
"format_stack",
"(",
")",
")",
")",
"os",
".",
"abort",
"(",
")",
"# log.debug(\"\\n\\npeer table lock released by %s at \\n%s\\n\\n\" % (PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK))",
"PEER_TABLE_LOCK_HOLDER",
"=",
"None",
"PEER_TABLE_LOCK_TRACEBACK",
"=",
"None",
"PEER_TABLE_LOCK",
".",
"release",
"(",
")",
"return"
] | Unlock the global health info table. | [
"Unlock",
"the",
"global",
"health",
"info",
"table",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L387-L405 |
230,416 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_format_query | def atlasdb_format_query( query, values ):
"""
Turn a query into a string for printing.
Useful for debugging.
"""
return "".join( ["%s %s" % (frag, "'%s'" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split("?"), values + ("",))] ) | python | def atlasdb_format_query( query, values ):
"""
Turn a query into a string for printing.
Useful for debugging.
"""
return "".join( ["%s %s" % (frag, "'%s'" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split("?"), values + ("",))] ) | [
"def",
"atlasdb_format_query",
"(",
"query",
",",
"values",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"[",
"\"%s %s\"",
"%",
"(",
"frag",
",",
"\"'%s'\"",
"%",
"val",
"if",
"type",
"(",
"val",
")",
"in",
"[",
"str",
",",
"unicode",
"]",
"else",
"val",
")",
"for",
"(",
"frag",
",",
"val",
")",
"in",
"zip",
"(",
"query",
".",
"split",
"(",
"\"?\"",
")",
",",
"values",
"+",
"(",
"\"\"",
",",
")",
")",
"]",
")"
] | Turn a query into a string for printing.
Useful for debugging. | [
"Turn",
"a",
"query",
"into",
"a",
"string",
"for",
"printing",
".",
"Useful",
"for",
"debugging",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L532-L537 |
230,417 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_open | def atlasdb_open( path ):
"""
Open the atlas db.
Return a connection.
Return None if it doesn't exist
"""
if not os.path.exists(path):
log.debug("Atlas DB doesn't exist at %s" % path)
return None
con = sqlite3.connect( path, isolation_level=None )
con.row_factory = atlasdb_row_factory
return con | python | def atlasdb_open( path ):
"""
Open the atlas db.
Return a connection.
Return None if it doesn't exist
"""
if not os.path.exists(path):
log.debug("Atlas DB doesn't exist at %s" % path)
return None
con = sqlite3.connect( path, isolation_level=None )
con.row_factory = atlasdb_row_factory
return con | [
"def",
"atlasdb_open",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"log",
".",
"debug",
"(",
"\"Atlas DB doesn't exist at %s\"",
"%",
"path",
")",
"return",
"None",
"con",
"=",
"sqlite3",
".",
"connect",
"(",
"path",
",",
"isolation_level",
"=",
"None",
")",
"con",
".",
"row_factory",
"=",
"atlasdb_row_factory",
"return",
"con"
] | Open the atlas db.
Return a connection.
Return None if it doesn't exist | [
"Open",
"the",
"atlas",
"db",
".",
"Return",
"a",
"connection",
".",
"Return",
"None",
"if",
"it",
"doesn",
"t",
"exist"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L550-L562 |
230,418 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_add_zonefile_info | def atlasdb_add_zonefile_info( name, zonefile_hash, txid, present, tried_storage, block_height, con=None, path=None ):
"""
Add a zonefile to the database.
Mark it as present or absent.
Keep our in-RAM inventory vector up-to-date
"""
global ZONEFILE_INV, NUM_ZONEFILES, ZONEFILE_INV_LOCK
with AtlasDBOpen( con=con, path=path ) as dbcon:
with ZONEFILE_INV_LOCK:
# need to lock here since someone could call atlasdb_cache_zonefile_info
if present:
present = 1
else:
present = 0
if tried_storage:
tried_storage = 1
else:
tried_storage = 0
sql = "UPDATE zonefiles SET name = ?, zonefile_hash = ?, txid = ?, present = ?, tried_storage = ?, block_height = ? WHERE txid = ?;"
args = (name, zonefile_hash, txid, present, tried_storage, block_height, txid )
cur = dbcon.cursor()
update_res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
if update_res.rowcount == 0:
sql = "INSERT OR IGNORE INTO zonefiles (name, zonefile_hash, txid, present, tried_storage, block_height) VALUES (?,?,?,?,?,?);"
args = (name, zonefile_hash, txid, present, tried_storage, block_height)
cur = dbcon.cursor()
atlasdb_query_execute( cur, sql, args )
dbcon.commit()
# keep in-RAM zonefile inv coherent
zfbits = atlasdb_get_zonefile_bits( zonefile_hash, con=dbcon, path=path )
inv_vec = None
if ZONEFILE_INV is None:
inv_vec = ""
else:
inv_vec = ZONEFILE_INV[:]
ZONEFILE_INV = atlas_inventory_flip_zonefile_bits( inv_vec, zfbits, present )
log.debug('Set {} ({}) to {}'.format(zonefile_hash, ','.join(str(i) for i in zfbits), present))
# keep in-RAM zonefile count coherent
NUM_ZONEFILES = atlasdb_zonefile_inv_length( con=dbcon, path=path )
return True | python | def atlasdb_add_zonefile_info( name, zonefile_hash, txid, present, tried_storage, block_height, con=None, path=None ):
"""
Add a zonefile to the database.
Mark it as present or absent.
Keep our in-RAM inventory vector up-to-date
"""
global ZONEFILE_INV, NUM_ZONEFILES, ZONEFILE_INV_LOCK
with AtlasDBOpen( con=con, path=path ) as dbcon:
with ZONEFILE_INV_LOCK:
# need to lock here since someone could call atlasdb_cache_zonefile_info
if present:
present = 1
else:
present = 0
if tried_storage:
tried_storage = 1
else:
tried_storage = 0
sql = "UPDATE zonefiles SET name = ?, zonefile_hash = ?, txid = ?, present = ?, tried_storage = ?, block_height = ? WHERE txid = ?;"
args = (name, zonefile_hash, txid, present, tried_storage, block_height, txid )
cur = dbcon.cursor()
update_res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
if update_res.rowcount == 0:
sql = "INSERT OR IGNORE INTO zonefiles (name, zonefile_hash, txid, present, tried_storage, block_height) VALUES (?,?,?,?,?,?);"
args = (name, zonefile_hash, txid, present, tried_storage, block_height)
cur = dbcon.cursor()
atlasdb_query_execute( cur, sql, args )
dbcon.commit()
# keep in-RAM zonefile inv coherent
zfbits = atlasdb_get_zonefile_bits( zonefile_hash, con=dbcon, path=path )
inv_vec = None
if ZONEFILE_INV is None:
inv_vec = ""
else:
inv_vec = ZONEFILE_INV[:]
ZONEFILE_INV = atlas_inventory_flip_zonefile_bits( inv_vec, zfbits, present )
log.debug('Set {} ({}) to {}'.format(zonefile_hash, ','.join(str(i) for i in zfbits), present))
# keep in-RAM zonefile count coherent
NUM_ZONEFILES = atlasdb_zonefile_inv_length( con=dbcon, path=path )
return True | [
"def",
"atlasdb_add_zonefile_info",
"(",
"name",
",",
"zonefile_hash",
",",
"txid",
",",
"present",
",",
"tried_storage",
",",
"block_height",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"global",
"ZONEFILE_INV",
",",
"NUM_ZONEFILES",
",",
"ZONEFILE_INV_LOCK",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"with",
"ZONEFILE_INV_LOCK",
":",
"# need to lock here since someone could call atlasdb_cache_zonefile_info",
"if",
"present",
":",
"present",
"=",
"1",
"else",
":",
"present",
"=",
"0",
"if",
"tried_storage",
":",
"tried_storage",
"=",
"1",
"else",
":",
"tried_storage",
"=",
"0",
"sql",
"=",
"\"UPDATE zonefiles SET name = ?, zonefile_hash = ?, txid = ?, present = ?, tried_storage = ?, block_height = ? WHERE txid = ?;\"",
"args",
"=",
"(",
"name",
",",
"zonefile_hash",
",",
"txid",
",",
"present",
",",
"tried_storage",
",",
"block_height",
",",
"txid",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"update_res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"dbcon",
".",
"commit",
"(",
")",
"if",
"update_res",
".",
"rowcount",
"==",
"0",
":",
"sql",
"=",
"\"INSERT OR IGNORE INTO zonefiles (name, zonefile_hash, txid, present, tried_storage, block_height) VALUES (?,?,?,?,?,?);\"",
"args",
"=",
"(",
"name",
",",
"zonefile_hash",
",",
"txid",
",",
"present",
",",
"tried_storage",
",",
"block_height",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"dbcon",
".",
"commit",
"(",
")",
"# keep in-RAM zonefile inv coherent",
"zfbits",
"=",
"atlasdb_get_zonefile_bits",
"(",
"zonefile_hash",
",",
"con",
"=",
"dbcon",
",",
"path",
"=",
"path",
")",
"inv_vec",
"=",
"None",
"if",
"ZONEFILE_INV",
"is",
"None",
":",
"inv_vec",
"=",
"\"\"",
"else",
":",
"inv_vec",
"=",
"ZONEFILE_INV",
"[",
":",
"]",
"ZONEFILE_INV",
"=",
"atlas_inventory_flip_zonefile_bits",
"(",
"inv_vec",
",",
"zfbits",
",",
"present",
")",
"log",
".",
"debug",
"(",
"'Set {} ({}) to {}'",
".",
"format",
"(",
"zonefile_hash",
",",
"','",
".",
"join",
"(",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"zfbits",
")",
",",
"present",
")",
")",
"# keep in-RAM zonefile count coherent",
"NUM_ZONEFILES",
"=",
"atlasdb_zonefile_inv_length",
"(",
"con",
"=",
"dbcon",
",",
"path",
"=",
"path",
")",
"return",
"True"
] | Add a zonefile to the database.
Mark it as present or absent.
Keep our in-RAM inventory vector up-to-date | [
"Add",
"a",
"zonefile",
"to",
"the",
"database",
".",
"Mark",
"it",
"as",
"present",
"or",
"absent",
".",
"Keep",
"our",
"in",
"-",
"RAM",
"inventory",
"vector",
"up",
"-",
"to",
"-",
"date"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L565-L616 |
230,419 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_get_lastblock | def atlasdb_get_lastblock( con=None, path=None ):
"""
Get the highest block height in the atlas db
"""
row = None
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT MAX(block_height) FROM zonefiles;"
args = ()
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
row = {}
for r in res:
row.update(r)
break
return row['MAX(block_height)'] | python | def atlasdb_get_lastblock( con=None, path=None ):
"""
Get the highest block height in the atlas db
"""
row = None
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT MAX(block_height) FROM zonefiles;"
args = ()
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
row = {}
for r in res:
row.update(r)
break
return row['MAX(block_height)'] | [
"def",
"atlasdb_get_lastblock",
"(",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"row",
"=",
"None",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"sql",
"=",
"\"SELECT MAX(block_height) FROM zonefiles;\"",
"args",
"=",
"(",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"row",
"=",
"{",
"}",
"for",
"r",
"in",
"res",
":",
"row",
".",
"update",
"(",
"r",
")",
"break",
"return",
"row",
"[",
"'MAX(block_height)'",
"]"
] | Get the highest block height in the atlas db | [
"Get",
"the",
"highest",
"block",
"height",
"in",
"the",
"atlas",
"db"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L619-L637 |
230,420 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_get_zonefiles_missing_count_by_name | def atlasdb_get_zonefiles_missing_count_by_name(name, max_index=None, indexes_exclude=[], con=None, path=None):
"""
Get the number of missing zone files for a particular name, optionally up to a maximum
zonefile index and optionally omitting particular zone files in the count.
Returns an integer
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = 'SELECT COUNT(*) FROM zonefiles WHERE name = ? AND present = 0 {} {};'.format(
'AND inv_index <= ?' if max_index is not None else '',
'AND inv_index NOT IN ({})'.format(','.join([str(int(i)) for i in indexes_exclude])) if len(indexes_exclude) > 0 else ''
)
args = (name,)
if max_index is not None:
args += (max_index,)
cur = dbcon.cursor()
res = atlasdb_query_execute(cur, sql, args)
for row in res:
return row['COUNT(*)'] | python | def atlasdb_get_zonefiles_missing_count_by_name(name, max_index=None, indexes_exclude=[], con=None, path=None):
"""
Get the number of missing zone files for a particular name, optionally up to a maximum
zonefile index and optionally omitting particular zone files in the count.
Returns an integer
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = 'SELECT COUNT(*) FROM zonefiles WHERE name = ? AND present = 0 {} {};'.format(
'AND inv_index <= ?' if max_index is not None else '',
'AND inv_index NOT IN ({})'.format(','.join([str(int(i)) for i in indexes_exclude])) if len(indexes_exclude) > 0 else ''
)
args = (name,)
if max_index is not None:
args += (max_index,)
cur = dbcon.cursor()
res = atlasdb_query_execute(cur, sql, args)
for row in res:
return row['COUNT(*)'] | [
"def",
"atlasdb_get_zonefiles_missing_count_by_name",
"(",
"name",
",",
"max_index",
"=",
"None",
",",
"indexes_exclude",
"=",
"[",
"]",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"sql",
"=",
"'SELECT COUNT(*) FROM zonefiles WHERE name = ? AND present = 0 {} {};'",
".",
"format",
"(",
"'AND inv_index <= ?'",
"if",
"max_index",
"is",
"not",
"None",
"else",
"''",
",",
"'AND inv_index NOT IN ({})'",
".",
"format",
"(",
"','",
".",
"join",
"(",
"[",
"str",
"(",
"int",
"(",
"i",
")",
")",
"for",
"i",
"in",
"indexes_exclude",
"]",
")",
")",
"if",
"len",
"(",
"indexes_exclude",
")",
">",
"0",
"else",
"''",
")",
"args",
"=",
"(",
"name",
",",
")",
"if",
"max_index",
"is",
"not",
"None",
":",
"args",
"+=",
"(",
"max_index",
",",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"for",
"row",
"in",
"res",
":",
"return",
"row",
"[",
"'COUNT(*)'",
"]"
] | Get the number of missing zone files for a particular name, optionally up to a maximum
zonefile index and optionally omitting particular zone files in the count.
Returns an integer | [
"Get",
"the",
"number",
"of",
"missing",
"zone",
"files",
"for",
"a",
"particular",
"name",
"optionally",
"up",
"to",
"a",
"maximum",
"zonefile",
"index",
"and",
"optionally",
"omitting",
"particular",
"zone",
"files",
"in",
"the",
"count",
".",
"Returns",
"an",
"integer"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L764-L783 |
230,421 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_get_zonefiles_by_hash | def atlasdb_get_zonefiles_by_hash(zonefile_hash, block_height=None, con=None, path=None):
"""
Find all instances of this zone file in the atlasdb.
Optionally filter on block height
Returns [{'name': ..., 'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order
Returns None if the zone file is not in the db, or if block_height is set, return None if the zone file is not at this block height.
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = 'SELECT * FROM zonefiles WHERE zonefile_hash = ?'
args = (zonefile_hash,)
if block_height:
sql += ' AND block_height = ?'
args += (block_height,)
sql += ' ORDER BY inv_index;'
cur = dbcon.cursor()
res = atlasdb_query_execute(cur, sql, args)
ret = []
for zfinfo in res:
row = {}
row.update(zfinfo)
ret.append(row)
if len(ret) == 0:
return None
return ret | python | def atlasdb_get_zonefiles_by_hash(zonefile_hash, block_height=None, con=None, path=None):
"""
Find all instances of this zone file in the atlasdb.
Optionally filter on block height
Returns [{'name': ..., 'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order
Returns None if the zone file is not in the db, or if block_height is set, return None if the zone file is not at this block height.
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = 'SELECT * FROM zonefiles WHERE zonefile_hash = ?'
args = (zonefile_hash,)
if block_height:
sql += ' AND block_height = ?'
args += (block_height,)
sql += ' ORDER BY inv_index;'
cur = dbcon.cursor()
res = atlasdb_query_execute(cur, sql, args)
ret = []
for zfinfo in res:
row = {}
row.update(zfinfo)
ret.append(row)
if len(ret) == 0:
return None
return ret | [
"def",
"atlasdb_get_zonefiles_by_hash",
"(",
"zonefile_hash",
",",
"block_height",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"sql",
"=",
"'SELECT * FROM zonefiles WHERE zonefile_hash = ?'",
"args",
"=",
"(",
"zonefile_hash",
",",
")",
"if",
"block_height",
":",
"sql",
"+=",
"' AND block_height = ?'",
"args",
"+=",
"(",
"block_height",
",",
")",
"sql",
"+=",
"' ORDER BY inv_index;'",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"zfinfo",
"in",
"res",
":",
"row",
"=",
"{",
"}",
"row",
".",
"update",
"(",
"zfinfo",
")",
"ret",
".",
"append",
"(",
"row",
")",
"if",
"len",
"(",
"ret",
")",
"==",
"0",
":",
"return",
"None",
"return",
"ret"
] | Find all instances of this zone file in the atlasdb.
Optionally filter on block height
Returns [{'name': ..., 'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_storage': ...}], in blockchain order
Returns None if the zone file is not in the db, or if block_height is set, return None if the zone file is not at this block height. | [
"Find",
"all",
"instances",
"of",
"this",
"zone",
"file",
"in",
"the",
"atlasdb",
".",
"Optionally",
"filter",
"on",
"block",
"height"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L786-L817 |
230,422 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_set_zonefile_tried_storage | def atlasdb_set_zonefile_tried_storage( zonefile_hash, tried_storage, con=None, path=None ):
"""
Make a note that we tried to get the zonefile from storage
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
if tried_storage:
tried_storage = 1
else:
tried_storage = 0
sql = "UPDATE zonefiles SET tried_storage = ? WHERE zonefile_hash = ?;"
args = (tried_storage, zonefile_hash)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
return True | python | def atlasdb_set_zonefile_tried_storage( zonefile_hash, tried_storage, con=None, path=None ):
"""
Make a note that we tried to get the zonefile from storage
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
if tried_storage:
tried_storage = 1
else:
tried_storage = 0
sql = "UPDATE zonefiles SET tried_storage = ? WHERE zonefile_hash = ?;"
args = (tried_storage, zonefile_hash)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
return True | [
"def",
"atlasdb_set_zonefile_tried_storage",
"(",
"zonefile_hash",
",",
"tried_storage",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"if",
"tried_storage",
":",
"tried_storage",
"=",
"1",
"else",
":",
"tried_storage",
"=",
"0",
"sql",
"=",
"\"UPDATE zonefiles SET tried_storage = ? WHERE zonefile_hash = ?;\"",
"args",
"=",
"(",
"tried_storage",
",",
"zonefile_hash",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"dbcon",
".",
"commit",
"(",
")",
"return",
"True"
] | Make a note that we tried to get the zonefile from storage | [
"Make",
"a",
"note",
"that",
"we",
"tried",
"to",
"get",
"the",
"zonefile",
"from",
"storage"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L865-L882 |
230,423 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_reset_zonefile_tried_storage | def atlasdb_reset_zonefile_tried_storage( con=None, path=None ):
"""
For zonefiles that we don't have, re-attempt to fetch them from storage.
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "UPDATE zonefiles SET tried_storage = ? WHERE present = ?;"
args = (0, 0)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
return True | python | def atlasdb_reset_zonefile_tried_storage( con=None, path=None ):
"""
For zonefiles that we don't have, re-attempt to fetch them from storage.
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "UPDATE zonefiles SET tried_storage = ? WHERE present = ?;"
args = (0, 0)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
return True | [
"def",
"atlasdb_reset_zonefile_tried_storage",
"(",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"sql",
"=",
"\"UPDATE zonefiles SET tried_storage = ? WHERE present = ?;\"",
"args",
"=",
"(",
"0",
",",
"0",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"dbcon",
".",
"commit",
"(",
")",
"return",
"True"
] | For zonefiles that we don't have, re-attempt to fetch them from storage. | [
"For",
"zonefiles",
"that",
"we",
"don",
"t",
"have",
"re",
"-",
"attempt",
"to",
"fetch",
"them",
"from",
"storage",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L885-L899 |
230,424 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_cache_zonefile_info | def atlasdb_cache_zonefile_info( con=None, path=None ):
"""
Load up and cache our zonefile inventory from the database
"""
global ZONEFILE_INV, NUM_ZONEFILES, ZONEFILE_INV_LOCK
inv = None
with ZONEFILE_INV_LOCK:
inv_len = atlasdb_zonefile_inv_length( con=con, path=path )
inv = atlas_make_zonefile_inventory( 0, inv_len, con=con, path=path )
ZONEFILE_INV = inv
NUM_ZONEFILES = inv_len
return inv | python | def atlasdb_cache_zonefile_info( con=None, path=None ):
"""
Load up and cache our zonefile inventory from the database
"""
global ZONEFILE_INV, NUM_ZONEFILES, ZONEFILE_INV_LOCK
inv = None
with ZONEFILE_INV_LOCK:
inv_len = atlasdb_zonefile_inv_length( con=con, path=path )
inv = atlas_make_zonefile_inventory( 0, inv_len, con=con, path=path )
ZONEFILE_INV = inv
NUM_ZONEFILES = inv_len
return inv | [
"def",
"atlasdb_cache_zonefile_info",
"(",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"global",
"ZONEFILE_INV",
",",
"NUM_ZONEFILES",
",",
"ZONEFILE_INV_LOCK",
"inv",
"=",
"None",
"with",
"ZONEFILE_INV_LOCK",
":",
"inv_len",
"=",
"atlasdb_zonefile_inv_length",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"inv",
"=",
"atlas_make_zonefile_inventory",
"(",
"0",
",",
"inv_len",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"ZONEFILE_INV",
"=",
"inv",
"NUM_ZONEFILES",
"=",
"inv_len",
"return",
"inv"
] | Load up and cache our zonefile inventory from the database | [
"Load",
"up",
"and",
"cache",
"our",
"zonefile",
"inventory",
"from",
"the",
"database"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L902-L916 |
230,425 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_queue_zonefiles | def atlasdb_queue_zonefiles( con, db, start_block, zonefile_dir, recover=False, validate=True, end_block=None ):
"""
Queue all zonefile hashes in the BlockstackDB
to the zonefile queue
NOT THREAD SAFE
Returns the list of zonefile infos queued, and whether or not they are present.
"""
# populate zonefile queue
total = 0
if end_block is None:
end_block = db.lastblock+1
ret = [] # map zonefile hash to zfinfo
for block_height in range(start_block, end_block, 1):
# TODO: can we do this transactionally?
zonefile_info = db.get_atlas_zonefile_info_at( block_height )
for name_txid_zfhash in zonefile_info:
name = str(name_txid_zfhash['name'])
zfhash = str(name_txid_zfhash['value_hash'])
txid = str(name_txid_zfhash['txid'])
tried_storage = 0
present = is_zonefile_cached( zfhash, zonefile_dir, validate=validate )
zfinfo = atlasdb_get_zonefile( zfhash, con=con )
if zfinfo is not None:
tried_storage = zfinfo['tried_storage']
if recover and present:
log.debug('Recover: assume that {} is absent so we will reprocess it'.format(zfhash))
present = False
log.debug("Add %s %s %s at %s (present: %s, tried_storage: %s)" % (name, zfhash, txid, block_height, present, tried_storage) )
atlasdb_add_zonefile_info( name, zfhash, txid, present, tried_storage, block_height, con=con )
total += 1
ret.append({
'name': name,
'zonefile_hash': zfhash,
'txid': txid,
'block_height': block_height,
'present': present,
'tried_storage': tried_storage
})
log.debug("Queued %s zonefiles from %s-%s" % (total, start_block, db.lastblock))
return ret | python | def atlasdb_queue_zonefiles( con, db, start_block, zonefile_dir, recover=False, validate=True, end_block=None ):
"""
Queue all zonefile hashes in the BlockstackDB
to the zonefile queue
NOT THREAD SAFE
Returns the list of zonefile infos queued, and whether or not they are present.
"""
# populate zonefile queue
total = 0
if end_block is None:
end_block = db.lastblock+1
ret = [] # map zonefile hash to zfinfo
for block_height in range(start_block, end_block, 1):
# TODO: can we do this transactionally?
zonefile_info = db.get_atlas_zonefile_info_at( block_height )
for name_txid_zfhash in zonefile_info:
name = str(name_txid_zfhash['name'])
zfhash = str(name_txid_zfhash['value_hash'])
txid = str(name_txid_zfhash['txid'])
tried_storage = 0
present = is_zonefile_cached( zfhash, zonefile_dir, validate=validate )
zfinfo = atlasdb_get_zonefile( zfhash, con=con )
if zfinfo is not None:
tried_storage = zfinfo['tried_storage']
if recover and present:
log.debug('Recover: assume that {} is absent so we will reprocess it'.format(zfhash))
present = False
log.debug("Add %s %s %s at %s (present: %s, tried_storage: %s)" % (name, zfhash, txid, block_height, present, tried_storage) )
atlasdb_add_zonefile_info( name, zfhash, txid, present, tried_storage, block_height, con=con )
total += 1
ret.append({
'name': name,
'zonefile_hash': zfhash,
'txid': txid,
'block_height': block_height,
'present': present,
'tried_storage': tried_storage
})
log.debug("Queued %s zonefiles from %s-%s" % (total, start_block, db.lastblock))
return ret | [
"def",
"atlasdb_queue_zonefiles",
"(",
"con",
",",
"db",
",",
"start_block",
",",
"zonefile_dir",
",",
"recover",
"=",
"False",
",",
"validate",
"=",
"True",
",",
"end_block",
"=",
"None",
")",
":",
"# populate zonefile queue",
"total",
"=",
"0",
"if",
"end_block",
"is",
"None",
":",
"end_block",
"=",
"db",
".",
"lastblock",
"+",
"1",
"ret",
"=",
"[",
"]",
"# map zonefile hash to zfinfo",
"for",
"block_height",
"in",
"range",
"(",
"start_block",
",",
"end_block",
",",
"1",
")",
":",
"# TODO: can we do this transactionally?",
"zonefile_info",
"=",
"db",
".",
"get_atlas_zonefile_info_at",
"(",
"block_height",
")",
"for",
"name_txid_zfhash",
"in",
"zonefile_info",
":",
"name",
"=",
"str",
"(",
"name_txid_zfhash",
"[",
"'name'",
"]",
")",
"zfhash",
"=",
"str",
"(",
"name_txid_zfhash",
"[",
"'value_hash'",
"]",
")",
"txid",
"=",
"str",
"(",
"name_txid_zfhash",
"[",
"'txid'",
"]",
")",
"tried_storage",
"=",
"0",
"present",
"=",
"is_zonefile_cached",
"(",
"zfhash",
",",
"zonefile_dir",
",",
"validate",
"=",
"validate",
")",
"zfinfo",
"=",
"atlasdb_get_zonefile",
"(",
"zfhash",
",",
"con",
"=",
"con",
")",
"if",
"zfinfo",
"is",
"not",
"None",
":",
"tried_storage",
"=",
"zfinfo",
"[",
"'tried_storage'",
"]",
"if",
"recover",
"and",
"present",
":",
"log",
".",
"debug",
"(",
"'Recover: assume that {} is absent so we will reprocess it'",
".",
"format",
"(",
"zfhash",
")",
")",
"present",
"=",
"False",
"log",
".",
"debug",
"(",
"\"Add %s %s %s at %s (present: %s, tried_storage: %s)\"",
"%",
"(",
"name",
",",
"zfhash",
",",
"txid",
",",
"block_height",
",",
"present",
",",
"tried_storage",
")",
")",
"atlasdb_add_zonefile_info",
"(",
"name",
",",
"zfhash",
",",
"txid",
",",
"present",
",",
"tried_storage",
",",
"block_height",
",",
"con",
"=",
"con",
")",
"total",
"+=",
"1",
"ret",
".",
"append",
"(",
"{",
"'name'",
":",
"name",
",",
"'zonefile_hash'",
":",
"zfhash",
",",
"'txid'",
":",
"txid",
",",
"'block_height'",
":",
"block_height",
",",
"'present'",
":",
"present",
",",
"'tried_storage'",
":",
"tried_storage",
"}",
")",
"log",
".",
"debug",
"(",
"\"Queued %s zonefiles from %s-%s\"",
"%",
"(",
"total",
",",
"start_block",
",",
"db",
".",
"lastblock",
")",
")",
"return",
"ret"
] | Queue all zonefile hashes in the BlockstackDB
to the zonefile queue
NOT THREAD SAFE
Returns the list of zonefile infos queued, and whether or not they are present. | [
"Queue",
"all",
"zonefile",
"hashes",
"in",
"the",
"BlockstackDB",
"to",
"the",
"zonefile",
"queue"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L940-L989 |
230,426 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_sync_zonefiles | def atlasdb_sync_zonefiles( db, start_block, zonefile_dir, atlas_state, validate=True, end_block=None, path=None, con=None ):
"""
Synchronize atlas DB with name db
NOT THREAD SAFE
"""
ret = None
with AtlasDBOpen(con=con, path=path) as dbcon:
ret = atlasdb_queue_zonefiles( dbcon, db, start_block, zonefile_dir, validate=validate, end_block=end_block )
atlasdb_cache_zonefile_info( con=dbcon )
if atlas_state:
# it could have been the case that a zone file we already have was re-announced.
# if so, then inform any storage listeners in the crawler thread that this has happened
# (such as the subdomain system).
crawler_thread = atlas_state['zonefile_crawler']
for zfinfo in filter(lambda zfi: zfi['present'], ret):
log.debug('Store re-discovered zonefile {} at {}'.format(zfinfo['zonefile_hash'], zfinfo['block_height']))
crawler_thread.store_zonefile_cb(zfinfo['zonefile_hash'], zfinfo['block_height'])
return ret | python | def atlasdb_sync_zonefiles( db, start_block, zonefile_dir, atlas_state, validate=True, end_block=None, path=None, con=None ):
"""
Synchronize atlas DB with name db
NOT THREAD SAFE
"""
ret = None
with AtlasDBOpen(con=con, path=path) as dbcon:
ret = atlasdb_queue_zonefiles( dbcon, db, start_block, zonefile_dir, validate=validate, end_block=end_block )
atlasdb_cache_zonefile_info( con=dbcon )
if atlas_state:
# it could have been the case that a zone file we already have was re-announced.
# if so, then inform any storage listeners in the crawler thread that this has happened
# (such as the subdomain system).
crawler_thread = atlas_state['zonefile_crawler']
for zfinfo in filter(lambda zfi: zfi['present'], ret):
log.debug('Store re-discovered zonefile {} at {}'.format(zfinfo['zonefile_hash'], zfinfo['block_height']))
crawler_thread.store_zonefile_cb(zfinfo['zonefile_hash'], zfinfo['block_height'])
return ret | [
"def",
"atlasdb_sync_zonefiles",
"(",
"db",
",",
"start_block",
",",
"zonefile_dir",
",",
"atlas_state",
",",
"validate",
"=",
"True",
",",
"end_block",
"=",
"None",
",",
"path",
"=",
"None",
",",
"con",
"=",
"None",
")",
":",
"ret",
"=",
"None",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"ret",
"=",
"atlasdb_queue_zonefiles",
"(",
"dbcon",
",",
"db",
",",
"start_block",
",",
"zonefile_dir",
",",
"validate",
"=",
"validate",
",",
"end_block",
"=",
"end_block",
")",
"atlasdb_cache_zonefile_info",
"(",
"con",
"=",
"dbcon",
")",
"if",
"atlas_state",
":",
"# it could have been the case that a zone file we already have was re-announced.",
"# if so, then inform any storage listeners in the crawler thread that this has happened",
"# (such as the subdomain system).",
"crawler_thread",
"=",
"atlas_state",
"[",
"'zonefile_crawler'",
"]",
"for",
"zfinfo",
"in",
"filter",
"(",
"lambda",
"zfi",
":",
"zfi",
"[",
"'present'",
"]",
",",
"ret",
")",
":",
"log",
".",
"debug",
"(",
"'Store re-discovered zonefile {} at {}'",
".",
"format",
"(",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
",",
"zfinfo",
"[",
"'block_height'",
"]",
")",
")",
"crawler_thread",
".",
"store_zonefile_cb",
"(",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
",",
"zfinfo",
"[",
"'block_height'",
"]",
")",
"return",
"ret"
] | Synchronize atlas DB with name db
NOT THREAD SAFE | [
"Synchronize",
"atlas",
"DB",
"with",
"name",
"db"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L992-L1012 |
230,427 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_add_peer | def atlasdb_add_peer( peer_hostport, discovery_time=None, peer_table=None, con=None, path=None, ping_on_evict=True ):
"""
Add a peer to the peer table.
If the peer conflicts with another peer, ping it first, and only insert
the new peer if the old peer is dead.
Keep the in-RAM peer table cache-coherent as well.
Return True if this peer was added to the table (or preserved)
Return False if not
"""
# bound the number of peers we add to PEER_MAX_DB
assert len(peer_hostport) > 0
sk = random.randint(0, 2**32)
peer_host, peer_port = url_to_host_port( peer_hostport )
assert len(peer_host) > 0
peer_slot = int( hashlib.sha256("%s%s" % (sk, peer_host)).hexdigest(), 16 ) % PEER_MAX_DB
with AtlasDBOpen(con=con, path=path) as dbcon:
if discovery_time is None:
discovery_time = int(time.time())
do_evict_and_ping = False
with AtlasPeerTableLocked(peer_table) as ptbl:
# if the peer is already present, then we're done
if peer_hostport in ptbl.keys():
log.debug("%s already in the peer table" % peer_hostport)
return True
# not in the table yet. See if we can evict someone
if ping_on_evict:
do_evict_and_ping = True
if do_evict_and_ping:
# evict someone
# don't hold the peer table lock across network I/O
sql = "SELECT peer_hostport FROM peers WHERE peer_slot = ?;"
args = (peer_slot,)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
old_hostports = []
for row in res:
old_hostport = res['peer_hostport']
old_hostports.append( old_hostport )
for old_hostport in old_hostports:
# is this other peer still alive?
# is this other peer part of the same mainnet history?
# res = atlas_peer_ping( old_hostport )
res = atlas_peer_getinfo(old_hostport)
if res:
log.debug("Peer %s is still alive; will not replace" % (old_hostport))
return False
# insert new peer
with AtlasPeerTableLocked(peer_table) as ptbl:
log.debug("Add peer '%s' discovered at %s (slot %s)" % (peer_hostport, discovery_time, peer_slot))
# peer is dead (or we don't care). Can insert or update
sql = "INSERT OR REPLACE INTO peers (peer_hostport, peer_slot, discovery_time) VALUES (?,?,?);"
args = (peer_hostport, peer_slot, discovery_time)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
# add to peer table as well
atlas_init_peer_info( ptbl, peer_hostport, blacklisted=False, whitelisted=False )
return True | python | def atlasdb_add_peer( peer_hostport, discovery_time=None, peer_table=None, con=None, path=None, ping_on_evict=True ):
"""
Add a peer to the peer table.
If the peer conflicts with another peer, ping it first, and only insert
the new peer if the old peer is dead.
Keep the in-RAM peer table cache-coherent as well.
Return True if this peer was added to the table (or preserved)
Return False if not
"""
# bound the number of peers we add to PEER_MAX_DB
assert len(peer_hostport) > 0
sk = random.randint(0, 2**32)
peer_host, peer_port = url_to_host_port( peer_hostport )
assert len(peer_host) > 0
peer_slot = int( hashlib.sha256("%s%s" % (sk, peer_host)).hexdigest(), 16 ) % PEER_MAX_DB
with AtlasDBOpen(con=con, path=path) as dbcon:
if discovery_time is None:
discovery_time = int(time.time())
do_evict_and_ping = False
with AtlasPeerTableLocked(peer_table) as ptbl:
# if the peer is already present, then we're done
if peer_hostport in ptbl.keys():
log.debug("%s already in the peer table" % peer_hostport)
return True
# not in the table yet. See if we can evict someone
if ping_on_evict:
do_evict_and_ping = True
if do_evict_and_ping:
# evict someone
# don't hold the peer table lock across network I/O
sql = "SELECT peer_hostport FROM peers WHERE peer_slot = ?;"
args = (peer_slot,)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
old_hostports = []
for row in res:
old_hostport = res['peer_hostport']
old_hostports.append( old_hostport )
for old_hostport in old_hostports:
# is this other peer still alive?
# is this other peer part of the same mainnet history?
# res = atlas_peer_ping( old_hostport )
res = atlas_peer_getinfo(old_hostport)
if res:
log.debug("Peer %s is still alive; will not replace" % (old_hostport))
return False
# insert new peer
with AtlasPeerTableLocked(peer_table) as ptbl:
log.debug("Add peer '%s' discovered at %s (slot %s)" % (peer_hostport, discovery_time, peer_slot))
# peer is dead (or we don't care). Can insert or update
sql = "INSERT OR REPLACE INTO peers (peer_hostport, peer_slot, discovery_time) VALUES (?,?,?);"
args = (peer_hostport, peer_slot, discovery_time)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
# add to peer table as well
atlas_init_peer_info( ptbl, peer_hostport, blacklisted=False, whitelisted=False )
return True | [
"def",
"atlasdb_add_peer",
"(",
"peer_hostport",
",",
"discovery_time",
"=",
"None",
",",
"peer_table",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"ping_on_evict",
"=",
"True",
")",
":",
"# bound the number of peers we add to PEER_MAX_DB",
"assert",
"len",
"(",
"peer_hostport",
")",
">",
"0",
"sk",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"2",
"**",
"32",
")",
"peer_host",
",",
"peer_port",
"=",
"url_to_host_port",
"(",
"peer_hostport",
")",
"assert",
"len",
"(",
"peer_host",
")",
">",
"0",
"peer_slot",
"=",
"int",
"(",
"hashlib",
".",
"sha256",
"(",
"\"%s%s\"",
"%",
"(",
"sk",
",",
"peer_host",
")",
")",
".",
"hexdigest",
"(",
")",
",",
"16",
")",
"%",
"PEER_MAX_DB",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"if",
"discovery_time",
"is",
"None",
":",
"discovery_time",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"do_evict_and_ping",
"=",
"False",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"# if the peer is already present, then we're done",
"if",
"peer_hostport",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"log",
".",
"debug",
"(",
"\"%s already in the peer table\"",
"%",
"peer_hostport",
")",
"return",
"True",
"# not in the table yet. See if we can evict someone",
"if",
"ping_on_evict",
":",
"do_evict_and_ping",
"=",
"True",
"if",
"do_evict_and_ping",
":",
"# evict someone",
"# don't hold the peer table lock across network I/O",
"sql",
"=",
"\"SELECT peer_hostport FROM peers WHERE peer_slot = ?;\"",
"args",
"=",
"(",
"peer_slot",
",",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"old_hostports",
"=",
"[",
"]",
"for",
"row",
"in",
"res",
":",
"old_hostport",
"=",
"res",
"[",
"'peer_hostport'",
"]",
"old_hostports",
".",
"append",
"(",
"old_hostport",
")",
"for",
"old_hostport",
"in",
"old_hostports",
":",
"# is this other peer still alive?",
"# is this other peer part of the same mainnet history?",
"# res = atlas_peer_ping( old_hostport )",
"res",
"=",
"atlas_peer_getinfo",
"(",
"old_hostport",
")",
"if",
"res",
":",
"log",
".",
"debug",
"(",
"\"Peer %s is still alive; will not replace\"",
"%",
"(",
"old_hostport",
")",
")",
"return",
"False",
"# insert new peer",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"log",
".",
"debug",
"(",
"\"Add peer '%s' discovered at %s (slot %s)\"",
"%",
"(",
"peer_hostport",
",",
"discovery_time",
",",
"peer_slot",
")",
")",
"# peer is dead (or we don't care). Can insert or update",
"sql",
"=",
"\"INSERT OR REPLACE INTO peers (peer_hostport, peer_slot, discovery_time) VALUES (?,?,?);\"",
"args",
"=",
"(",
"peer_hostport",
",",
"peer_slot",
",",
"discovery_time",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"dbcon",
".",
"commit",
"(",
")",
"# add to peer table as well",
"atlas_init_peer_info",
"(",
"ptbl",
",",
"peer_hostport",
",",
"blacklisted",
"=",
"False",
",",
"whitelisted",
"=",
"False",
")",
"return",
"True"
] | Add a peer to the peer table.
If the peer conflicts with another peer, ping it first, and only insert
the new peer if the old peer is dead.
Keep the in-RAM peer table cache-coherent as well.
Return True if this peer was added to the table (or preserved)
Return False if not | [
"Add",
"a",
"peer",
"to",
"the",
"peer",
"table",
".",
"If",
"the",
"peer",
"conflicts",
"with",
"another",
"peer",
"ping",
"it",
"first",
"and",
"only",
"insert",
"the",
"new",
"peer",
"if",
"the",
"old",
"peer",
"is",
"dead",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1015-L1095 |
230,428 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_num_peers | def atlasdb_num_peers( con=None, path=None ):
"""
How many peers are there in the db?
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT MAX(peer_index) FROM peers;"
args = ()
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
ret = []
for row in res:
tmp = {}
tmp.update(row)
ret.append(tmp)
assert len(ret) == 1
return ret[0]['MAX(peer_index)'] | python | def atlasdb_num_peers( con=None, path=None ):
"""
How many peers are there in the db?
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT MAX(peer_index) FROM peers;"
args = ()
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
ret = []
for row in res:
tmp = {}
tmp.update(row)
ret.append(tmp)
assert len(ret) == 1
return ret[0]['MAX(peer_index)'] | [
"def",
"atlasdb_num_peers",
"(",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"sql",
"=",
"\"SELECT MAX(peer_index) FROM peers;\"",
"args",
"=",
"(",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"row",
"in",
"res",
":",
"tmp",
"=",
"{",
"}",
"tmp",
".",
"update",
"(",
"row",
")",
"ret",
".",
"append",
"(",
"tmp",
")",
"assert",
"len",
"(",
"ret",
")",
"==",
"1",
"return",
"ret",
"[",
"0",
"]",
"[",
"'MAX(peer_index)'",
"]"
] | How many peers are there in the db? | [
"How",
"many",
"peers",
"are",
"there",
"in",
"the",
"db?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1124-L1144 |
230,429 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_get_peer | def atlas_get_peer( peer_hostport, peer_table=None ):
"""
Get the given peer's info
"""
ret = None
with AtlasPeerTableLocked(peer_table) as ptbl:
ret = ptbl.get(peer_hostport, None)
return ret | python | def atlas_get_peer( peer_hostport, peer_table=None ):
"""
Get the given peer's info
"""
ret = None
with AtlasPeerTableLocked(peer_table) as ptbl:
ret = ptbl.get(peer_hostport, None)
return ret | [
"def",
"atlas_get_peer",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"None",
")",
":",
"ret",
"=",
"None",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"ret",
"=",
"ptbl",
".",
"get",
"(",
"peer_hostport",
",",
"None",
")",
"return",
"ret"
] | Get the given peer's info | [
"Get",
"the",
"given",
"peer",
"s",
"info"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1147-L1156 |
230,430 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_get_random_peer | def atlasdb_get_random_peer( con=None, path=None ):
"""
Select a peer from the db at random
Return None if the table is empty
"""
ret = {}
with AtlasDBOpen(con=con, path=path) as dbcon:
num_peers = atlasdb_num_peers( con=con, path=path )
if num_peers is None or num_peers == 0:
# no peers
ret['peer_hostport'] = None
else:
r = random.randint(1, num_peers)
sql = "SELECT * FROM peers WHERE peer_index = ?;"
args = (r,)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
ret = {'peer_hostport': None}
for row in res:
ret.update( row )
break
return ret['peer_hostport'] | python | def atlasdb_get_random_peer( con=None, path=None ):
"""
Select a peer from the db at random
Return None if the table is empty
"""
ret = {}
with AtlasDBOpen(con=con, path=path) as dbcon:
num_peers = atlasdb_num_peers( con=con, path=path )
if num_peers is None or num_peers == 0:
# no peers
ret['peer_hostport'] = None
else:
r = random.randint(1, num_peers)
sql = "SELECT * FROM peers WHERE peer_index = ?;"
args = (r,)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
ret = {'peer_hostport': None}
for row in res:
ret.update( row )
break
return ret['peer_hostport'] | [
"def",
"atlasdb_get_random_peer",
"(",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"num_peers",
"=",
"atlasdb_num_peers",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"if",
"num_peers",
"is",
"None",
"or",
"num_peers",
"==",
"0",
":",
"# no peers",
"ret",
"[",
"'peer_hostport'",
"]",
"=",
"None",
"else",
":",
"r",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"num_peers",
")",
"sql",
"=",
"\"SELECT * FROM peers WHERE peer_index = ?;\"",
"args",
"=",
"(",
"r",
",",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"ret",
"=",
"{",
"'peer_hostport'",
":",
"None",
"}",
"for",
"row",
"in",
"res",
":",
"ret",
".",
"update",
"(",
"row",
")",
"break",
"return",
"ret",
"[",
"'peer_hostport'",
"]"
] | Select a peer from the db at random
Return None if the table is empty | [
"Select",
"a",
"peer",
"from",
"the",
"db",
"at",
"random",
"Return",
"None",
"if",
"the",
"table",
"is",
"empty"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1159-L1188 |
230,431 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_get_old_peers | def atlasdb_get_old_peers( now, con=None, path=None ):
"""
Get peers older than now - PEER_LIFETIME
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
if now is None:
now = time.time()
expire = now - atlas_peer_max_age()
sql = "SELECT * FROM peers WHERE discovery_time < ?";
args = (expire,)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
rows = []
for row in res:
tmp = {}
tmp.update(row)
rows.append(tmp)
return rows | python | def atlasdb_get_old_peers( now, con=None, path=None ):
"""
Get peers older than now - PEER_LIFETIME
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
if now is None:
now = time.time()
expire = now - atlas_peer_max_age()
sql = "SELECT * FROM peers WHERE discovery_time < ?";
args = (expire,)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
rows = []
for row in res:
tmp = {}
tmp.update(row)
rows.append(tmp)
return rows | [
"def",
"atlasdb_get_old_peers",
"(",
"now",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"expire",
"=",
"now",
"-",
"atlas_peer_max_age",
"(",
")",
"sql",
"=",
"\"SELECT * FROM peers WHERE discovery_time < ?\"",
"args",
"=",
"(",
"expire",
",",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"rows",
"=",
"[",
"]",
"for",
"row",
"in",
"res",
":",
"tmp",
"=",
"{",
"}",
"tmp",
".",
"update",
"(",
"row",
")",
"rows",
".",
"append",
"(",
"tmp",
")",
"return",
"rows"
] | Get peers older than now - PEER_LIFETIME | [
"Get",
"peers",
"older",
"than",
"now",
"-",
"PEER_LIFETIME"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1191-L1213 |
230,432 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_renew_peer | def atlasdb_renew_peer( peer_hostport, now, con=None, path=None ):
"""
Renew a peer's discovery time
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
if now is None:
now = time.time()
sql = "UPDATE peers SET discovery_time = ? WHERE peer_hostport = ?;"
args = (now, peer_hostport)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
return True | python | def atlasdb_renew_peer( peer_hostport, now, con=None, path=None ):
"""
Renew a peer's discovery time
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
if now is None:
now = time.time()
sql = "UPDATE peers SET discovery_time = ? WHERE peer_hostport = ?;"
args = (now, peer_hostport)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
return True | [
"def",
"atlasdb_renew_peer",
"(",
"peer_hostport",
",",
"now",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"sql",
"=",
"\"UPDATE peers SET discovery_time = ? WHERE peer_hostport = ?;\"",
"args",
"=",
"(",
"now",
",",
"peer_hostport",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"dbcon",
".",
"commit",
"(",
")",
"return",
"True"
] | Renew a peer's discovery time | [
"Renew",
"a",
"peer",
"s",
"discovery",
"time"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1216-L1231 |
230,433 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_load_peer_table | def atlasdb_load_peer_table( con=None, path=None ):
"""
Create a peer table from the peer DB
"""
peer_table = {}
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT * FROM peers;"
args = ()
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
# build it up
count = 0
for row in res:
if count > 0 and count % 100 == 0:
log.debug("Loaded %s peers..." % count)
atlas_init_peer_info( peer_table, row['peer_hostport'] )
count += 1
return peer_table | python | def atlasdb_load_peer_table( con=None, path=None ):
"""
Create a peer table from the peer DB
"""
peer_table = {}
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT * FROM peers;"
args = ()
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
# build it up
count = 0
for row in res:
if count > 0 and count % 100 == 0:
log.debug("Loaded %s peers..." % count)
atlas_init_peer_info( peer_table, row['peer_hostport'] )
count += 1
return peer_table | [
"def",
"atlasdb_load_peer_table",
"(",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"peer_table",
"=",
"{",
"}",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"sql",
"=",
"\"SELECT * FROM peers;\"",
"args",
"=",
"(",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"# build it up ",
"count",
"=",
"0",
"for",
"row",
"in",
"res",
":",
"if",
"count",
">",
"0",
"and",
"count",
"%",
"100",
"==",
"0",
":",
"log",
".",
"debug",
"(",
"\"Loaded %s peers...\"",
"%",
"count",
")",
"atlas_init_peer_info",
"(",
"peer_table",
",",
"row",
"[",
"'peer_hostport'",
"]",
")",
"count",
"+=",
"1",
"return",
"peer_table"
] | Create a peer table from the peer DB | [
"Create",
"a",
"peer",
"table",
"from",
"the",
"peer",
"DB"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1234-L1257 |
230,434 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlasdb_zonefile_inv_list | def atlasdb_zonefile_inv_list( bit_offset, bit_length, con=None, path=None ):
"""
Get an inventory listing.
offset and length are in bits.
Return the list of zonefile information.
The list may be less than length elements.
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT * FROM zonefiles LIMIT ? OFFSET ?;"
args = (bit_length, bit_offset)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
ret = []
for row in res:
tmp = {}
tmp.update(row)
ret.append(tmp)
return ret | python | def atlasdb_zonefile_inv_list( bit_offset, bit_length, con=None, path=None ):
"""
Get an inventory listing.
offset and length are in bits.
Return the list of zonefile information.
The list may be less than length elements.
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
sql = "SELECT * FROM zonefiles LIMIT ? OFFSET ?;"
args = (bit_length, bit_offset)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
ret = []
for row in res:
tmp = {}
tmp.update(row)
ret.append(tmp)
return ret | [
"def",
"atlasdb_zonefile_inv_list",
"(",
"bit_offset",
",",
"bit_length",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"sql",
"=",
"\"SELECT * FROM zonefiles LIMIT ? OFFSET ?;\"",
"args",
"=",
"(",
"bit_length",
",",
"bit_offset",
")",
"cur",
"=",
"dbcon",
".",
"cursor",
"(",
")",
"res",
"=",
"atlasdb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"ret",
"=",
"[",
"]",
"for",
"row",
"in",
"res",
":",
"tmp",
"=",
"{",
"}",
"tmp",
".",
"update",
"(",
"row",
")",
"ret",
".",
"append",
"(",
"tmp",
")",
"return",
"ret"
] | Get an inventory listing.
offset and length are in bits.
Return the list of zonefile information.
The list may be less than length elements. | [
"Get",
"an",
"inventory",
"listing",
".",
"offset",
"and",
"length",
"are",
"in",
"bits",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1364-L1386 |
230,435 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_init_peer_info | def atlas_init_peer_info( peer_table, peer_hostport, blacklisted=False, whitelisted=False ):
"""
Initialize peer info table entry
"""
peer_table[peer_hostport] = {
"time": [],
"zonefile_inv": "",
"blacklisted": blacklisted,
"whitelisted": whitelisted
} | python | def atlas_init_peer_info( peer_table, peer_hostport, blacklisted=False, whitelisted=False ):
"""
Initialize peer info table entry
"""
peer_table[peer_hostport] = {
"time": [],
"zonefile_inv": "",
"blacklisted": blacklisted,
"whitelisted": whitelisted
} | [
"def",
"atlas_init_peer_info",
"(",
"peer_table",
",",
"peer_hostport",
",",
"blacklisted",
"=",
"False",
",",
"whitelisted",
"=",
"False",
")",
":",
"peer_table",
"[",
"peer_hostport",
"]",
"=",
"{",
"\"time\"",
":",
"[",
"]",
",",
"\"zonefile_inv\"",
":",
"\"\"",
",",
"\"blacklisted\"",
":",
"blacklisted",
",",
"\"whitelisted\"",
":",
"whitelisted",
"}"
] | Initialize peer info table entry | [
"Initialize",
"peer",
"info",
"table",
"entry"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1546-L1555 |
230,436 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_log_socket_error | def atlas_log_socket_error( method_invocation, peer_hostport, se ):
"""
Log a socket exception tastefully
"""
if isinstance( se, socket.timeout ):
log.debug("%s %s: timed out (socket.timeout)" % (method_invocation, peer_hostport))
elif isinstance( se, socket.gaierror ):
log.debug("%s %s: failed to query address or info (socket.gaierror)" % (method_invocation, peer_hostport ))
elif isinstance( se, socket.herror ):
log.debug("%s %s: failed to query host info (socket.herror)" % (method_invocation, peer_hostport ))
elif isinstance( se, socket.error ):
if se.errno == errno.ECONNREFUSED:
log.debug("%s %s: is unreachable (socket.error ECONNREFUSED)" % (method_invocation, peer_hostport))
elif se.errno == errno.ETIMEDOUT:
log.debug("%s %s: timed out (socket.error ETIMEDOUT)" % (method_invocation, peer_hostport))
else:
log.debug("%s %s: socket error" % (method_invocation, peer_hostport))
log.exception(se)
else:
log.debug("%s %s: general exception" % (method_invocation, peer_hostport))
log.exception(se) | python | def atlas_log_socket_error( method_invocation, peer_hostport, se ):
"""
Log a socket exception tastefully
"""
if isinstance( se, socket.timeout ):
log.debug("%s %s: timed out (socket.timeout)" % (method_invocation, peer_hostport))
elif isinstance( se, socket.gaierror ):
log.debug("%s %s: failed to query address or info (socket.gaierror)" % (method_invocation, peer_hostport ))
elif isinstance( se, socket.herror ):
log.debug("%s %s: failed to query host info (socket.herror)" % (method_invocation, peer_hostport ))
elif isinstance( se, socket.error ):
if se.errno == errno.ECONNREFUSED:
log.debug("%s %s: is unreachable (socket.error ECONNREFUSED)" % (method_invocation, peer_hostport))
elif se.errno == errno.ETIMEDOUT:
log.debug("%s %s: timed out (socket.error ETIMEDOUT)" % (method_invocation, peer_hostport))
else:
log.debug("%s %s: socket error" % (method_invocation, peer_hostport))
log.exception(se)
else:
log.debug("%s %s: general exception" % (method_invocation, peer_hostport))
log.exception(se) | [
"def",
"atlas_log_socket_error",
"(",
"method_invocation",
",",
"peer_hostport",
",",
"se",
")",
":",
"if",
"isinstance",
"(",
"se",
",",
"socket",
".",
"timeout",
")",
":",
"log",
".",
"debug",
"(",
"\"%s %s: timed out (socket.timeout)\"",
"%",
"(",
"method_invocation",
",",
"peer_hostport",
")",
")",
"elif",
"isinstance",
"(",
"se",
",",
"socket",
".",
"gaierror",
")",
":",
"log",
".",
"debug",
"(",
"\"%s %s: failed to query address or info (socket.gaierror)\"",
"%",
"(",
"method_invocation",
",",
"peer_hostport",
")",
")",
"elif",
"isinstance",
"(",
"se",
",",
"socket",
".",
"herror",
")",
":",
"log",
".",
"debug",
"(",
"\"%s %s: failed to query host info (socket.herror)\"",
"%",
"(",
"method_invocation",
",",
"peer_hostport",
")",
")",
"elif",
"isinstance",
"(",
"se",
",",
"socket",
".",
"error",
")",
":",
"if",
"se",
".",
"errno",
"==",
"errno",
".",
"ECONNREFUSED",
":",
"log",
".",
"debug",
"(",
"\"%s %s: is unreachable (socket.error ECONNREFUSED)\"",
"%",
"(",
"method_invocation",
",",
"peer_hostport",
")",
")",
"elif",
"se",
".",
"errno",
"==",
"errno",
".",
"ETIMEDOUT",
":",
"log",
".",
"debug",
"(",
"\"%s %s: timed out (socket.error ETIMEDOUT)\"",
"%",
"(",
"method_invocation",
",",
"peer_hostport",
")",
")",
"else",
":",
"log",
".",
"debug",
"(",
"\"%s %s: socket error\"",
"%",
"(",
"method_invocation",
",",
"peer_hostport",
")",
")",
"log",
".",
"exception",
"(",
"se",
")",
"else",
":",
"log",
".",
"debug",
"(",
"\"%s %s: general exception\"",
"%",
"(",
"method_invocation",
",",
"peer_hostport",
")",
")",
"log",
".",
"exception",
"(",
"se",
")"
] | Log a socket exception tastefully | [
"Log",
"a",
"socket",
"exception",
"tastefully"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1558-L1582 |
230,437 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_ping | def atlas_peer_ping( peer_hostport, timeout=None, peer_table=None ):
"""
Ping a host
Return True if alive
Return False if not
"""
if timeout is None:
timeout = atlas_ping_timeout()
assert not atlas_peer_table_is_locked_by_me()
host, port = url_to_host_port( peer_hostport )
RPC = get_rpc_client_class()
rpc = RPC( host, port, timeout=timeout )
log.debug("Ping %s" % peer_hostport)
ret = False
try:
res = blockstack_ping( proxy=rpc )
if 'error' not in res:
ret = True
except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
atlas_log_socket_error( "ping(%s)" % peer_hostport, peer_hostport, se )
pass
except Exception, e:
log.exception(e)
pass
# update health
with AtlasPeerTableLocked(peer_table) as ptbl:
atlas_peer_update_health( peer_hostport, ret, peer_table=ptbl )
return ret | python | def atlas_peer_ping( peer_hostport, timeout=None, peer_table=None ):
"""
Ping a host
Return True if alive
Return False if not
"""
if timeout is None:
timeout = atlas_ping_timeout()
assert not atlas_peer_table_is_locked_by_me()
host, port = url_to_host_port( peer_hostport )
RPC = get_rpc_client_class()
rpc = RPC( host, port, timeout=timeout )
log.debug("Ping %s" % peer_hostport)
ret = False
try:
res = blockstack_ping( proxy=rpc )
if 'error' not in res:
ret = True
except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
atlas_log_socket_error( "ping(%s)" % peer_hostport, peer_hostport, se )
pass
except Exception, e:
log.exception(e)
pass
# update health
with AtlasPeerTableLocked(peer_table) as ptbl:
atlas_peer_update_health( peer_hostport, ret, peer_table=ptbl )
return ret | [
"def",
"atlas_peer_ping",
"(",
"peer_hostport",
",",
"timeout",
"=",
"None",
",",
"peer_table",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"atlas_ping_timeout",
"(",
")",
"assert",
"not",
"atlas_peer_table_is_locked_by_me",
"(",
")",
"host",
",",
"port",
"=",
"url_to_host_port",
"(",
"peer_hostport",
")",
"RPC",
"=",
"get_rpc_client_class",
"(",
")",
"rpc",
"=",
"RPC",
"(",
"host",
",",
"port",
",",
"timeout",
"=",
"timeout",
")",
"log",
".",
"debug",
"(",
"\"Ping %s\"",
"%",
"peer_hostport",
")",
"ret",
"=",
"False",
"try",
":",
"res",
"=",
"blockstack_ping",
"(",
"proxy",
"=",
"rpc",
")",
"if",
"'error'",
"not",
"in",
"res",
":",
"ret",
"=",
"True",
"except",
"(",
"socket",
".",
"timeout",
",",
"socket",
".",
"gaierror",
",",
"socket",
".",
"herror",
",",
"socket",
".",
"error",
")",
",",
"se",
":",
"atlas_log_socket_error",
"(",
"\"ping(%s)\"",
"%",
"peer_hostport",
",",
"peer_hostport",
",",
"se",
")",
"pass",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"pass",
"# update health",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"atlas_peer_update_health",
"(",
"peer_hostport",
",",
"ret",
",",
"peer_table",
"=",
"ptbl",
")",
"return",
"ret"
] | Ping a host
Return True if alive
Return False if not | [
"Ping",
"a",
"host",
"Return",
"True",
"if",
"alive",
"Return",
"False",
"if",
"not"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1585-L1621 |
230,438 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_inventory_count_missing | def atlas_inventory_count_missing( inv1, inv2 ):
"""
Find out how many bits are set in inv2
that are not set in inv1.
"""
count = 0
common = min(len(inv1), len(inv2))
for i in xrange(0, common):
for j in xrange(0, 8):
if ((1 << (7 - j)) & ord(inv2[i])) != 0 and ((1 << (7 - j)) & ord(inv1[i])) == 0:
count += 1
if len(inv1) < len(inv2):
for i in xrange(len(inv1), len(inv2)):
for j in xrange(0, 8):
if ((1 << (7 - j)) & ord(inv2[i])) != 0:
count += 1
return count | python | def atlas_inventory_count_missing( inv1, inv2 ):
"""
Find out how many bits are set in inv2
that are not set in inv1.
"""
count = 0
common = min(len(inv1), len(inv2))
for i in xrange(0, common):
for j in xrange(0, 8):
if ((1 << (7 - j)) & ord(inv2[i])) != 0 and ((1 << (7 - j)) & ord(inv1[i])) == 0:
count += 1
if len(inv1) < len(inv2):
for i in xrange(len(inv1), len(inv2)):
for j in xrange(0, 8):
if ((1 << (7 - j)) & ord(inv2[i])) != 0:
count += 1
return count | [
"def",
"atlas_inventory_count_missing",
"(",
"inv1",
",",
"inv2",
")",
":",
"count",
"=",
"0",
"common",
"=",
"min",
"(",
"len",
"(",
"inv1",
")",
",",
"len",
"(",
"inv2",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"common",
")",
":",
"for",
"j",
"in",
"xrange",
"(",
"0",
",",
"8",
")",
":",
"if",
"(",
"(",
"1",
"<<",
"(",
"7",
"-",
"j",
")",
")",
"&",
"ord",
"(",
"inv2",
"[",
"i",
"]",
")",
")",
"!=",
"0",
"and",
"(",
"(",
"1",
"<<",
"(",
"7",
"-",
"j",
")",
")",
"&",
"ord",
"(",
"inv1",
"[",
"i",
"]",
")",
")",
"==",
"0",
":",
"count",
"+=",
"1",
"if",
"len",
"(",
"inv1",
")",
"<",
"len",
"(",
"inv2",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"inv1",
")",
",",
"len",
"(",
"inv2",
")",
")",
":",
"for",
"j",
"in",
"xrange",
"(",
"0",
",",
"8",
")",
":",
"if",
"(",
"(",
"1",
"<<",
"(",
"7",
"-",
"j",
")",
")",
"&",
"ord",
"(",
"inv2",
"[",
"i",
"]",
")",
")",
"!=",
"0",
":",
"count",
"+=",
"1",
"return",
"count"
] | Find out how many bits are set in inv2
that are not set in inv1. | [
"Find",
"out",
"how",
"many",
"bits",
"are",
"set",
"in",
"inv2",
"that",
"are",
"not",
"set",
"in",
"inv1",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1707-L1725 |
230,439 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_revalidate_peers | def atlas_revalidate_peers( con=None, path=None, now=None, peer_table=None ):
"""
Revalidate peers that are older than the maximum peer age.
Ping them, and if they don't respond, remove them.
"""
global MIN_PEER_HEALTH
if now is None:
now = time_now()
old_peer_infos = atlasdb_get_old_peers( now, con=con, path=path )
for old_peer_info in old_peer_infos:
res = atlas_peer_getinfo( old_peer_info['peer_hostport'] )
if not res:
log.debug("Failed to revalidate %s" % (old_peer_info['peer_hostport']))
if atlas_peer_is_whitelisted( old_peer_info['peer_hostport'], peer_table=peer_table ):
continue
if atlas_peer_is_blacklisted( old_peer_info['peer_hostport'], peer_table=peer_table ):
continue
if atlas_peer_get_health( old_peer_info['peer_hostport'], peer_table=peer_table ) < MIN_PEER_HEALTH:
atlasdb_remove_peer( old_peer_info['peer_hostport'], con=con, path=path, peer_table=peer_table )
else:
# renew
atlasdb_renew_peer( old_peer_info['peer_hostport'], now, con=con, path=path )
return True | python | def atlas_revalidate_peers( con=None, path=None, now=None, peer_table=None ):
"""
Revalidate peers that are older than the maximum peer age.
Ping them, and if they don't respond, remove them.
"""
global MIN_PEER_HEALTH
if now is None:
now = time_now()
old_peer_infos = atlasdb_get_old_peers( now, con=con, path=path )
for old_peer_info in old_peer_infos:
res = atlas_peer_getinfo( old_peer_info['peer_hostport'] )
if not res:
log.debug("Failed to revalidate %s" % (old_peer_info['peer_hostport']))
if atlas_peer_is_whitelisted( old_peer_info['peer_hostport'], peer_table=peer_table ):
continue
if atlas_peer_is_blacklisted( old_peer_info['peer_hostport'], peer_table=peer_table ):
continue
if atlas_peer_get_health( old_peer_info['peer_hostport'], peer_table=peer_table ) < MIN_PEER_HEALTH:
atlasdb_remove_peer( old_peer_info['peer_hostport'], con=con, path=path, peer_table=peer_table )
else:
# renew
atlasdb_renew_peer( old_peer_info['peer_hostport'], now, con=con, path=path )
return True | [
"def",
"atlas_revalidate_peers",
"(",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"now",
"=",
"None",
",",
"peer_table",
"=",
"None",
")",
":",
"global",
"MIN_PEER_HEALTH",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"time_now",
"(",
")",
"old_peer_infos",
"=",
"atlasdb_get_old_peers",
"(",
"now",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"for",
"old_peer_info",
"in",
"old_peer_infos",
":",
"res",
"=",
"atlas_peer_getinfo",
"(",
"old_peer_info",
"[",
"'peer_hostport'",
"]",
")",
"if",
"not",
"res",
":",
"log",
".",
"debug",
"(",
"\"Failed to revalidate %s\"",
"%",
"(",
"old_peer_info",
"[",
"'peer_hostport'",
"]",
")",
")",
"if",
"atlas_peer_is_whitelisted",
"(",
"old_peer_info",
"[",
"'peer_hostport'",
"]",
",",
"peer_table",
"=",
"peer_table",
")",
":",
"continue",
"if",
"atlas_peer_is_blacklisted",
"(",
"old_peer_info",
"[",
"'peer_hostport'",
"]",
",",
"peer_table",
"=",
"peer_table",
")",
":",
"continue",
"if",
"atlas_peer_get_health",
"(",
"old_peer_info",
"[",
"'peer_hostport'",
"]",
",",
"peer_table",
"=",
"peer_table",
")",
"<",
"MIN_PEER_HEALTH",
":",
"atlasdb_remove_peer",
"(",
"old_peer_info",
"[",
"'peer_hostport'",
"]",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
",",
"peer_table",
"=",
"peer_table",
")",
"else",
":",
"# renew ",
"atlasdb_renew_peer",
"(",
"old_peer_info",
"[",
"'peer_hostport'",
"]",
",",
"now",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"return",
"True"
] | Revalidate peers that are older than the maximum peer age.
Ping them, and if they don't respond, remove them. | [
"Revalidate",
"peers",
"that",
"are",
"older",
"than",
"the",
"maximum",
"peer",
"age",
".",
"Ping",
"them",
"and",
"if",
"they",
"don",
"t",
"respond",
"remove",
"them",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1775-L1803 |
230,440 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_get_request_count | def atlas_peer_get_request_count( peer_hostport, peer_table=None ):
"""
How many times have we contacted this peer?
"""
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return 0
count = 0
for (t, r) in ptbl[peer_hostport]['time']:
if r:
count += 1
return count | python | def atlas_peer_get_request_count( peer_hostport, peer_table=None ):
"""
How many times have we contacted this peer?
"""
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return 0
count = 0
for (t, r) in ptbl[peer_hostport]['time']:
if r:
count += 1
return count | [
"def",
"atlas_peer_get_request_count",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"None",
")",
":",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"0",
"count",
"=",
"0",
"for",
"(",
"t",
",",
"r",
")",
"in",
"ptbl",
"[",
"peer_hostport",
"]",
"[",
"'time'",
"]",
":",
"if",
"r",
":",
"count",
"+=",
"1",
"return",
"count"
] | How many times have we contacted this peer? | [
"How",
"many",
"times",
"have",
"we",
"contacted",
"this",
"peer?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1828-L1841 |
230,441 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_get_zonefile_inventory | def atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=None ):
"""
What's the zonefile inventory vector for this peer?
Return None if not defined
"""
inv = None
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return None
inv = ptbl[peer_hostport]['zonefile_inv']
return inv | python | def atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=None ):
"""
What's the zonefile inventory vector for this peer?
Return None if not defined
"""
inv = None
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return None
inv = ptbl[peer_hostport]['zonefile_inv']
return inv | [
"def",
"atlas_peer_get_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"None",
")",
":",
"inv",
"=",
"None",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"None",
"inv",
"=",
"ptbl",
"[",
"peer_hostport",
"]",
"[",
"'zonefile_inv'",
"]",
"return",
"inv"
] | What's the zonefile inventory vector for this peer?
Return None if not defined | [
"What",
"s",
"the",
"zonefile",
"inventory",
"vector",
"for",
"this",
"peer?",
"Return",
"None",
"if",
"not",
"defined"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1844-L1857 |
230,442 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_set_zonefile_inventory | def atlas_peer_set_zonefile_inventory( peer_hostport, peer_inv, peer_table=None ):
"""
Set this peer's zonefile inventory
"""
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return None
ptbl[peer_hostport]['zonefile_inv'] = peer_inv
return peer_inv | python | def atlas_peer_set_zonefile_inventory( peer_hostport, peer_inv, peer_table=None ):
"""
Set this peer's zonefile inventory
"""
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return None
ptbl[peer_hostport]['zonefile_inv'] = peer_inv
return peer_inv | [
"def",
"atlas_peer_set_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_inv",
",",
"peer_table",
"=",
"None",
")",
":",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"None",
"ptbl",
"[",
"peer_hostport",
"]",
"[",
"'zonefile_inv'",
"]",
"=",
"peer_inv",
"return",
"peer_inv"
] | Set this peer's zonefile inventory | [
"Set",
"this",
"peer",
"s",
"zonefile",
"inventory"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1860-L1870 |
230,443 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_is_whitelisted | def atlas_peer_is_whitelisted( peer_hostport, peer_table=None ):
"""
Is a peer whitelisted
"""
ret = None
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return None
ret = ptbl[peer_hostport].get("whitelisted", False)
return ret | python | def atlas_peer_is_whitelisted( peer_hostport, peer_table=None ):
"""
Is a peer whitelisted
"""
ret = None
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return None
ret = ptbl[peer_hostport].get("whitelisted", False)
return ret | [
"def",
"atlas_peer_is_whitelisted",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"None",
")",
":",
"ret",
"=",
"None",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"None",
"ret",
"=",
"ptbl",
"[",
"peer_hostport",
"]",
".",
"get",
"(",
"\"whitelisted\"",
",",
"False",
")",
"return",
"ret"
] | Is a peer whitelisted | [
"Is",
"a",
"peer",
"whitelisted"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1888-L1899 |
230,444 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_update_health | def atlas_peer_update_health( peer_hostport, received_response, peer_table=None ):
"""
Mark the given peer as alive at this time.
Update times at which we contacted it,
and update its health score.
Use the global health table by default,
or use the given health info if set.
"""
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
# record that we contacted this peer, and whether or not we useful info from it
now = time_now()
# update timestamps; remove old data
new_times = []
for (t, r) in ptbl[peer_hostport]['time']:
if t + atlas_peer_lifetime_interval() < now:
continue
new_times.append((t, r))
new_times.append((now, received_response))
ptbl[peer_hostport]['time'] = new_times
return True | python | def atlas_peer_update_health( peer_hostport, received_response, peer_table=None ):
"""
Mark the given peer as alive at this time.
Update times at which we contacted it,
and update its health score.
Use the global health table by default,
or use the given health info if set.
"""
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
# record that we contacted this peer, and whether or not we useful info from it
now = time_now()
# update timestamps; remove old data
new_times = []
for (t, r) in ptbl[peer_hostport]['time']:
if t + atlas_peer_lifetime_interval() < now:
continue
new_times.append((t, r))
new_times.append((now, received_response))
ptbl[peer_hostport]['time'] = new_times
return True | [
"def",
"atlas_peer_update_health",
"(",
"peer_hostport",
",",
"received_response",
",",
"peer_table",
"=",
"None",
")",
":",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"False",
"# record that we contacted this peer, and whether or not we useful info from it",
"now",
"=",
"time_now",
"(",
")",
"# update timestamps; remove old data",
"new_times",
"=",
"[",
"]",
"for",
"(",
"t",
",",
"r",
")",
"in",
"ptbl",
"[",
"peer_hostport",
"]",
"[",
"'time'",
"]",
":",
"if",
"t",
"+",
"atlas_peer_lifetime_interval",
"(",
")",
"<",
"now",
":",
"continue",
"new_times",
".",
"append",
"(",
"(",
"t",
",",
"r",
")",
")",
"new_times",
".",
"append",
"(",
"(",
"now",
",",
"received_response",
")",
")",
"ptbl",
"[",
"peer_hostport",
"]",
"[",
"'time'",
"]",
"=",
"new_times",
"return",
"True"
] | Mark the given peer as alive at this time.
Update times at which we contacted it,
and update its health score.
Use the global health table by default,
or use the given health info if set. | [
"Mark",
"the",
"given",
"peer",
"as",
"alive",
"at",
"this",
"time",
".",
"Update",
"times",
"at",
"which",
"we",
"contacted",
"it",
"and",
"update",
"its",
"health",
"score",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1902-L1930 |
230,445 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_download_zonefile_inventory | def atlas_peer_download_zonefile_inventory( my_hostport, peer_hostport, maxlen, bit_offset=0, timeout=None, peer_table={} ):
"""
Get the zonefile inventory from the remote peer
Start from the given bit_offset
NOTE: this doesn't update the peer table health by default;
you'll have to explicitly pass in a peer table (i.e. setting
to {} ensures that nothing happens).
"""
if timeout is None:
timeout = atlas_inv_timeout()
interval = 524288 # number of bits in 64KB
peer_inv = ""
log.debug("Download zonefile inventory %s-%s from %s" % (bit_offset, maxlen, peer_hostport))
if bit_offset > maxlen:
# synced already
return peer_inv
for offset in xrange( bit_offset, maxlen, interval):
next_inv = atlas_peer_get_zonefile_inventory_range( my_hostport, peer_hostport, offset, interval, timeout=timeout, peer_table=peer_table )
if next_inv is None:
# partial failure
log.debug("Failed to sync inventory for %s from %s to %s" % (peer_hostport, offset, offset+interval))
break
peer_inv += next_inv
if len(next_inv) < interval:
# end-of-interval
break
return peer_inv | python | def atlas_peer_download_zonefile_inventory( my_hostport, peer_hostport, maxlen, bit_offset=0, timeout=None, peer_table={} ):
"""
Get the zonefile inventory from the remote peer
Start from the given bit_offset
NOTE: this doesn't update the peer table health by default;
you'll have to explicitly pass in a peer table (i.e. setting
to {} ensures that nothing happens).
"""
if timeout is None:
timeout = atlas_inv_timeout()
interval = 524288 # number of bits in 64KB
peer_inv = ""
log.debug("Download zonefile inventory %s-%s from %s" % (bit_offset, maxlen, peer_hostport))
if bit_offset > maxlen:
# synced already
return peer_inv
for offset in xrange( bit_offset, maxlen, interval):
next_inv = atlas_peer_get_zonefile_inventory_range( my_hostport, peer_hostport, offset, interval, timeout=timeout, peer_table=peer_table )
if next_inv is None:
# partial failure
log.debug("Failed to sync inventory for %s from %s to %s" % (peer_hostport, offset, offset+interval))
break
peer_inv += next_inv
if len(next_inv) < interval:
# end-of-interval
break
return peer_inv | [
"def",
"atlas_peer_download_zonefile_inventory",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"maxlen",
",",
"bit_offset",
"=",
"0",
",",
"timeout",
"=",
"None",
",",
"peer_table",
"=",
"{",
"}",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"atlas_inv_timeout",
"(",
")",
"interval",
"=",
"524288",
"# number of bits in 64KB",
"peer_inv",
"=",
"\"\"",
"log",
".",
"debug",
"(",
"\"Download zonefile inventory %s-%s from %s\"",
"%",
"(",
"bit_offset",
",",
"maxlen",
",",
"peer_hostport",
")",
")",
"if",
"bit_offset",
">",
"maxlen",
":",
"# synced already",
"return",
"peer_inv",
"for",
"offset",
"in",
"xrange",
"(",
"bit_offset",
",",
"maxlen",
",",
"interval",
")",
":",
"next_inv",
"=",
"atlas_peer_get_zonefile_inventory_range",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"offset",
",",
"interval",
",",
"timeout",
"=",
"timeout",
",",
"peer_table",
"=",
"peer_table",
")",
"if",
"next_inv",
"is",
"None",
":",
"# partial failure",
"log",
".",
"debug",
"(",
"\"Failed to sync inventory for %s from %s to %s\"",
"%",
"(",
"peer_hostport",
",",
"offset",
",",
"offset",
"+",
"interval",
")",
")",
"break",
"peer_inv",
"+=",
"next_inv",
"if",
"len",
"(",
"next_inv",
")",
"<",
"interval",
":",
"# end-of-interval",
"break",
"return",
"peer_inv"
] | Get the zonefile inventory from the remote peer
Start from the given bit_offset
NOTE: this doesn't update the peer table health by default;
you'll have to explicitly pass in a peer table (i.e. setting
to {} ensures that nothing happens). | [
"Get",
"the",
"zonefile",
"inventory",
"from",
"the",
"remote",
"peer",
"Start",
"from",
"the",
"given",
"bit_offset"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1993-L2027 |
230,446 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_sync_zonefile_inventory | def atlas_peer_sync_zonefile_inventory( my_hostport, peer_hostport, maxlen, timeout=None, peer_table=None ):
"""
Synchronize our knowledge of a peer's zonefiles up to a given byte length
NOT THREAD SAFE; CALL FROM ONLY ONE THREAD.
maxlen is the maximum length in bits of the expected zonefile.
Return the new inv vector if we synced it (updating the peer table in the process)
Return None if not
"""
if timeout is None:
timeout = atlas_inv_timeout()
peer_inv = ""
bit_offset = None
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return None
peer_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
bit_offset = (len(peer_inv) - 1) * 8 # i.e. re-obtain the last byte
if bit_offset < 0:
bit_offset = 0
else:
peer_inv = peer_inv[:-1]
peer_inv = atlas_peer_download_zonefile_inventory( my_hostport, peer_hostport, maxlen, bit_offset=bit_offset, timeout=timeout, peer_table=peer_table )
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
log.debug("%s no longer a peer" % peer_hostport)
return None
inv_str = atlas_inventory_to_string(peer_inv)
if len(inv_str) > 40:
inv_str = inv_str[:40] + "..."
log.debug("Set zonefile inventory %s: %s" % (peer_hostport, inv_str))
atlas_peer_set_zonefile_inventory( peer_hostport, peer_inv, peer_table=ptbl ) # NOTE: may have trailing 0's for padding
return peer_inv | python | def atlas_peer_sync_zonefile_inventory( my_hostport, peer_hostport, maxlen, timeout=None, peer_table=None ):
"""
Synchronize our knowledge of a peer's zonefiles up to a given byte length
NOT THREAD SAFE; CALL FROM ONLY ONE THREAD.
maxlen is the maximum length in bits of the expected zonefile.
Return the new inv vector if we synced it (updating the peer table in the process)
Return None if not
"""
if timeout is None:
timeout = atlas_inv_timeout()
peer_inv = ""
bit_offset = None
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return None
peer_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
bit_offset = (len(peer_inv) - 1) * 8 # i.e. re-obtain the last byte
if bit_offset < 0:
bit_offset = 0
else:
peer_inv = peer_inv[:-1]
peer_inv = atlas_peer_download_zonefile_inventory( my_hostport, peer_hostport, maxlen, bit_offset=bit_offset, timeout=timeout, peer_table=peer_table )
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
log.debug("%s no longer a peer" % peer_hostport)
return None
inv_str = atlas_inventory_to_string(peer_inv)
if len(inv_str) > 40:
inv_str = inv_str[:40] + "..."
log.debug("Set zonefile inventory %s: %s" % (peer_hostport, inv_str))
atlas_peer_set_zonefile_inventory( peer_hostport, peer_inv, peer_table=ptbl ) # NOTE: may have trailing 0's for padding
return peer_inv | [
"def",
"atlas_peer_sync_zonefile_inventory",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"maxlen",
",",
"timeout",
"=",
"None",
",",
"peer_table",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"atlas_inv_timeout",
"(",
")",
"peer_inv",
"=",
"\"\"",
"bit_offset",
"=",
"None",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"None",
"peer_inv",
"=",
"atlas_peer_get_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"ptbl",
")",
"bit_offset",
"=",
"(",
"len",
"(",
"peer_inv",
")",
"-",
"1",
")",
"*",
"8",
"# i.e. re-obtain the last byte",
"if",
"bit_offset",
"<",
"0",
":",
"bit_offset",
"=",
"0",
"else",
":",
"peer_inv",
"=",
"peer_inv",
"[",
":",
"-",
"1",
"]",
"peer_inv",
"=",
"atlas_peer_download_zonefile_inventory",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"maxlen",
",",
"bit_offset",
"=",
"bit_offset",
",",
"timeout",
"=",
"timeout",
",",
"peer_table",
"=",
"peer_table",
")",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"log",
".",
"debug",
"(",
"\"%s no longer a peer\"",
"%",
"peer_hostport",
")",
"return",
"None",
"inv_str",
"=",
"atlas_inventory_to_string",
"(",
"peer_inv",
")",
"if",
"len",
"(",
"inv_str",
")",
">",
"40",
":",
"inv_str",
"=",
"inv_str",
"[",
":",
"40",
"]",
"+",
"\"...\"",
"log",
".",
"debug",
"(",
"\"Set zonefile inventory %s: %s\"",
"%",
"(",
"peer_hostport",
",",
"inv_str",
")",
")",
"atlas_peer_set_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_inv",
",",
"peer_table",
"=",
"ptbl",
")",
"# NOTE: may have trailing 0's for padding",
"return",
"peer_inv"
] | Synchronize our knowledge of a peer's zonefiles up to a given byte length
NOT THREAD SAFE; CALL FROM ONLY ONE THREAD.
maxlen is the maximum length in bits of the expected zonefile.
Return the new inv vector if we synced it (updating the peer table in the process)
Return None if not | [
"Synchronize",
"our",
"knowledge",
"of",
"a",
"peer",
"s",
"zonefiles",
"up",
"to",
"a",
"given",
"byte",
"length",
"NOT",
"THREAD",
"SAFE",
";",
"CALL",
"FROM",
"ONLY",
"ONE",
"THREAD",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2031-L2074 |
230,447 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_refresh_zonefile_inventory | def atlas_peer_refresh_zonefile_inventory( my_hostport, peer_hostport, byte_offset, timeout=None, peer_table=None, con=None, path=None, local_inv=None ):
"""
Refresh a peer's zonefile recent inventory vector entries,
by removing every bit after byte_offset and re-synchronizing them.
The intuition here is that recent zonefiles are much rarer than older
zonefiles (which will have been near-100% replicated), meaning the tail
of the peer's zonefile inventory is a lot less stable than the head (since
peers will be actively distributing recent zonefiles).
NOT THREAD SAFE; CALL FROM ONLY ONE THREAD.
Return True if we synced all the way up to the expected inventory length, and update the refresh time in the peer table.
Return False if not.
"""
if timeout is None:
timeout = atlas_inv_timeout()
if local_inv is None:
# get local zonefile inv
inv_len = atlasdb_zonefile_inv_length( con=con, path=path )
local_inv = atlas_make_zonefile_inventory( 0, inv_len, con=con, path=path )
maxlen = len(local_inv)
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
# reset the peer's zonefile inventory, back to offset
cur_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
atlas_peer_set_zonefile_inventory( peer_hostport, cur_inv[:byte_offset], peer_table=ptbl )
inv = atlas_peer_sync_zonefile_inventory( my_hostport, peer_hostport, maxlen, timeout=timeout, peer_table=peer_table )
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
# Update refresh time (even if we fail)
ptbl[peer_hostport]['zonefile_inventory_last_refresh'] = time_now()
if inv is not None:
inv_str = atlas_inventory_to_string(inv)
if len(inv_str) > 40:
inv_str = inv_str[:40] + "..."
log.debug("%s: inventory of %s is now '%s'" % (my_hostport, peer_hostport, inv_str))
if inv is None:
return False
else:
return True | python | def atlas_peer_refresh_zonefile_inventory( my_hostport, peer_hostport, byte_offset, timeout=None, peer_table=None, con=None, path=None, local_inv=None ):
"""
Refresh a peer's zonefile recent inventory vector entries,
by removing every bit after byte_offset and re-synchronizing them.
The intuition here is that recent zonefiles are much rarer than older
zonefiles (which will have been near-100% replicated), meaning the tail
of the peer's zonefile inventory is a lot less stable than the head (since
peers will be actively distributing recent zonefiles).
NOT THREAD SAFE; CALL FROM ONLY ONE THREAD.
Return True if we synced all the way up to the expected inventory length, and update the refresh time in the peer table.
Return False if not.
"""
if timeout is None:
timeout = atlas_inv_timeout()
if local_inv is None:
# get local zonefile inv
inv_len = atlasdb_zonefile_inv_length( con=con, path=path )
local_inv = atlas_make_zonefile_inventory( 0, inv_len, con=con, path=path )
maxlen = len(local_inv)
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
# reset the peer's zonefile inventory, back to offset
cur_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
atlas_peer_set_zonefile_inventory( peer_hostport, cur_inv[:byte_offset], peer_table=ptbl )
inv = atlas_peer_sync_zonefile_inventory( my_hostport, peer_hostport, maxlen, timeout=timeout, peer_table=peer_table )
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
# Update refresh time (even if we fail)
ptbl[peer_hostport]['zonefile_inventory_last_refresh'] = time_now()
if inv is not None:
inv_str = atlas_inventory_to_string(inv)
if len(inv_str) > 40:
inv_str = inv_str[:40] + "..."
log.debug("%s: inventory of %s is now '%s'" % (my_hostport, peer_hostport, inv_str))
if inv is None:
return False
else:
return True | [
"def",
"atlas_peer_refresh_zonefile_inventory",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"byte_offset",
",",
"timeout",
"=",
"None",
",",
"peer_table",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"local_inv",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"atlas_inv_timeout",
"(",
")",
"if",
"local_inv",
"is",
"None",
":",
"# get local zonefile inv ",
"inv_len",
"=",
"atlasdb_zonefile_inv_length",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"local_inv",
"=",
"atlas_make_zonefile_inventory",
"(",
"0",
",",
"inv_len",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"maxlen",
"=",
"len",
"(",
"local_inv",
")",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"False",
"# reset the peer's zonefile inventory, back to offset",
"cur_inv",
"=",
"atlas_peer_get_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"ptbl",
")",
"atlas_peer_set_zonefile_inventory",
"(",
"peer_hostport",
",",
"cur_inv",
"[",
":",
"byte_offset",
"]",
",",
"peer_table",
"=",
"ptbl",
")",
"inv",
"=",
"atlas_peer_sync_zonefile_inventory",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"maxlen",
",",
"timeout",
"=",
"timeout",
",",
"peer_table",
"=",
"peer_table",
")",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"False",
"# Update refresh time (even if we fail)",
"ptbl",
"[",
"peer_hostport",
"]",
"[",
"'zonefile_inventory_last_refresh'",
"]",
"=",
"time_now",
"(",
")",
"if",
"inv",
"is",
"not",
"None",
":",
"inv_str",
"=",
"atlas_inventory_to_string",
"(",
"inv",
")",
"if",
"len",
"(",
"inv_str",
")",
">",
"40",
":",
"inv_str",
"=",
"inv_str",
"[",
":",
"40",
"]",
"+",
"\"...\"",
"log",
".",
"debug",
"(",
"\"%s: inventory of %s is now '%s'\"",
"%",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"inv_str",
")",
")",
"if",
"inv",
"is",
"None",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | Refresh a peer's zonefile recent inventory vector entries,
by removing every bit after byte_offset and re-synchronizing them.
The intuition here is that recent zonefiles are much rarer than older
zonefiles (which will have been near-100% replicated), meaning the tail
of the peer's zonefile inventory is a lot less stable than the head (since
peers will be actively distributing recent zonefiles).
NOT THREAD SAFE; CALL FROM ONLY ONE THREAD.
Return True if we synced all the way up to the expected inventory length, and update the refresh time in the peer table.
Return False if not. | [
"Refresh",
"a",
"peer",
"s",
"zonefile",
"recent",
"inventory",
"vector",
"entries",
"by",
"removing",
"every",
"bit",
"after",
"byte_offset",
"and",
"re",
"-",
"synchronizing",
"them",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2077-L2131 |
230,448 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_has_fresh_zonefile_inventory | def atlas_peer_has_fresh_zonefile_inventory( peer_hostport, peer_table=None ):
"""
Does the given atlas node have a fresh zonefile inventory?
"""
fresh = False
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
now = time_now()
peer_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
# NOTE: zero-length or None peer inventory means the peer is simply dead, but we've pinged it
if ptbl[peer_hostport].has_key('zonefile_inventory_last_refresh') and \
ptbl[peer_hostport]['zonefile_inventory_last_refresh'] + atlas_peer_ping_interval() > now:
fresh = True
return fresh | python | def atlas_peer_has_fresh_zonefile_inventory( peer_hostport, peer_table=None ):
"""
Does the given atlas node have a fresh zonefile inventory?
"""
fresh = False
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
now = time_now()
peer_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
# NOTE: zero-length or None peer inventory means the peer is simply dead, but we've pinged it
if ptbl[peer_hostport].has_key('zonefile_inventory_last_refresh') and \
ptbl[peer_hostport]['zonefile_inventory_last_refresh'] + atlas_peer_ping_interval() > now:
fresh = True
return fresh | [
"def",
"atlas_peer_has_fresh_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"None",
")",
":",
"fresh",
"=",
"False",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"False",
"now",
"=",
"time_now",
"(",
")",
"peer_inv",
"=",
"atlas_peer_get_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"ptbl",
")",
"# NOTE: zero-length or None peer inventory means the peer is simply dead, but we've pinged it",
"if",
"ptbl",
"[",
"peer_hostport",
"]",
".",
"has_key",
"(",
"'zonefile_inventory_last_refresh'",
")",
"and",
"ptbl",
"[",
"peer_hostport",
"]",
"[",
"'zonefile_inventory_last_refresh'",
"]",
"+",
"atlas_peer_ping_interval",
"(",
")",
">",
"now",
":",
"fresh",
"=",
"True",
"return",
"fresh"
] | Does the given atlas node have a fresh zonefile inventory? | [
"Does",
"the",
"given",
"atlas",
"node",
"have",
"a",
"fresh",
"zonefile",
"inventory?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2134-L2153 |
230,449 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_find_missing_zonefile_availability | def atlas_find_missing_zonefile_availability( peer_table=None, con=None, path=None, missing_zonefile_info=None ):
"""
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
our clique (and we'll re-sync our neighborss' inventories
every so often to make sure we detect when zonefiles
become available).
Return a dict, structured as:
{
'zonefile hash': {
'names': [names],
'txid': first txid that set it,
'indexes': [...],
'popularity': ...,
'peers': [...],
'tried_storage': True|False
}
}
"""
# which zonefiles do we have?
bit_offset = 0
bit_count = 10000
missing = []
ret = {}
if missing_zonefile_info is None:
while True:
zfinfo = atlasdb_zonefile_find_missing( bit_offset, bit_count, con=con, path=path )
if len(zfinfo) == 0:
break
missing += zfinfo
bit_offset += len(zfinfo)
if len(missing) > 0:
log.debug("Missing %s zonefiles" % len(missing))
else:
missing = missing_zonefile_info
if len(missing) == 0:
# none!
return ret
with AtlasPeerTableLocked(peer_table) as ptbl:
# do any other peers have this zonefile?
for zfinfo in missing:
popularity = 0
byte_index = (zfinfo['inv_index'] - 1) / 8
bit_index = 7 - ((zfinfo['inv_index'] - 1) % 8)
peers = []
if not ret.has_key(zfinfo['zonefile_hash']):
ret[zfinfo['zonefile_hash']] = {
'names': [],
'txid': zfinfo['txid'],
'indexes': [],
'block_heights': [],
'popularity': 0,
'peers': [],
'tried_storage': False
}
for peer_hostport in ptbl.keys():
peer_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
if len(peer_inv) <= byte_index:
# too new for this peer
continue
if (ord(peer_inv[byte_index]) & (1 << bit_index)) == 0:
# this peer doesn't have it
continue
if peer_hostport not in ret[zfinfo['zonefile_hash']]['peers']:
popularity += 1
peers.append( peer_hostport )
ret[zfinfo['zonefile_hash']]['names'].append( zfinfo['name'] )
ret[zfinfo['zonefile_hash']]['indexes'].append( zfinfo['inv_index']-1 )
ret[zfinfo['zonefile_hash']]['block_heights'].append( zfinfo['block_height'] )
ret[zfinfo['zonefile_hash']]['popularity'] += popularity
ret[zfinfo['zonefile_hash']]['peers'] += peers
ret[zfinfo['zonefile_hash']]['tried_storage'] = zfinfo['tried_storage']
return ret | python | def atlas_find_missing_zonefile_availability( peer_table=None, con=None, path=None, missing_zonefile_info=None ):
"""
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
our clique (and we'll re-sync our neighborss' inventories
every so often to make sure we detect when zonefiles
become available).
Return a dict, structured as:
{
'zonefile hash': {
'names': [names],
'txid': first txid that set it,
'indexes': [...],
'popularity': ...,
'peers': [...],
'tried_storage': True|False
}
}
"""
# which zonefiles do we have?
bit_offset = 0
bit_count = 10000
missing = []
ret = {}
if missing_zonefile_info is None:
while True:
zfinfo = atlasdb_zonefile_find_missing( bit_offset, bit_count, con=con, path=path )
if len(zfinfo) == 0:
break
missing += zfinfo
bit_offset += len(zfinfo)
if len(missing) > 0:
log.debug("Missing %s zonefiles" % len(missing))
else:
missing = missing_zonefile_info
if len(missing) == 0:
# none!
return ret
with AtlasPeerTableLocked(peer_table) as ptbl:
# do any other peers have this zonefile?
for zfinfo in missing:
popularity = 0
byte_index = (zfinfo['inv_index'] - 1) / 8
bit_index = 7 - ((zfinfo['inv_index'] - 1) % 8)
peers = []
if not ret.has_key(zfinfo['zonefile_hash']):
ret[zfinfo['zonefile_hash']] = {
'names': [],
'txid': zfinfo['txid'],
'indexes': [],
'block_heights': [],
'popularity': 0,
'peers': [],
'tried_storage': False
}
for peer_hostport in ptbl.keys():
peer_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
if len(peer_inv) <= byte_index:
# too new for this peer
continue
if (ord(peer_inv[byte_index]) & (1 << bit_index)) == 0:
# this peer doesn't have it
continue
if peer_hostport not in ret[zfinfo['zonefile_hash']]['peers']:
popularity += 1
peers.append( peer_hostport )
ret[zfinfo['zonefile_hash']]['names'].append( zfinfo['name'] )
ret[zfinfo['zonefile_hash']]['indexes'].append( zfinfo['inv_index']-1 )
ret[zfinfo['zonefile_hash']]['block_heights'].append( zfinfo['block_height'] )
ret[zfinfo['zonefile_hash']]['popularity'] += popularity
ret[zfinfo['zonefile_hash']]['peers'] += peers
ret[zfinfo['zonefile_hash']]['tried_storage'] = zfinfo['tried_storage']
return ret | [
"def",
"atlas_find_missing_zonefile_availability",
"(",
"peer_table",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"missing_zonefile_info",
"=",
"None",
")",
":",
"# which zonefiles do we have?",
"bit_offset",
"=",
"0",
"bit_count",
"=",
"10000",
"missing",
"=",
"[",
"]",
"ret",
"=",
"{",
"}",
"if",
"missing_zonefile_info",
"is",
"None",
":",
"while",
"True",
":",
"zfinfo",
"=",
"atlasdb_zonefile_find_missing",
"(",
"bit_offset",
",",
"bit_count",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"if",
"len",
"(",
"zfinfo",
")",
"==",
"0",
":",
"break",
"missing",
"+=",
"zfinfo",
"bit_offset",
"+=",
"len",
"(",
"zfinfo",
")",
"if",
"len",
"(",
"missing",
")",
">",
"0",
":",
"log",
".",
"debug",
"(",
"\"Missing %s zonefiles\"",
"%",
"len",
"(",
"missing",
")",
")",
"else",
":",
"missing",
"=",
"missing_zonefile_info",
"if",
"len",
"(",
"missing",
")",
"==",
"0",
":",
"# none!",
"return",
"ret",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"# do any other peers have this zonefile?",
"for",
"zfinfo",
"in",
"missing",
":",
"popularity",
"=",
"0",
"byte_index",
"=",
"(",
"zfinfo",
"[",
"'inv_index'",
"]",
"-",
"1",
")",
"/",
"8",
"bit_index",
"=",
"7",
"-",
"(",
"(",
"zfinfo",
"[",
"'inv_index'",
"]",
"-",
"1",
")",
"%",
"8",
")",
"peers",
"=",
"[",
"]",
"if",
"not",
"ret",
".",
"has_key",
"(",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
")",
":",
"ret",
"[",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
"]",
"=",
"{",
"'names'",
":",
"[",
"]",
",",
"'txid'",
":",
"zfinfo",
"[",
"'txid'",
"]",
",",
"'indexes'",
":",
"[",
"]",
",",
"'block_heights'",
":",
"[",
"]",
",",
"'popularity'",
":",
"0",
",",
"'peers'",
":",
"[",
"]",
",",
"'tried_storage'",
":",
"False",
"}",
"for",
"peer_hostport",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"peer_inv",
"=",
"atlas_peer_get_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"ptbl",
")",
"if",
"len",
"(",
"peer_inv",
")",
"<=",
"byte_index",
":",
"# too new for this peer",
"continue",
"if",
"(",
"ord",
"(",
"peer_inv",
"[",
"byte_index",
"]",
")",
"&",
"(",
"1",
"<<",
"bit_index",
")",
")",
"==",
"0",
":",
"# this peer doesn't have it",
"continue",
"if",
"peer_hostport",
"not",
"in",
"ret",
"[",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
"]",
"[",
"'peers'",
"]",
":",
"popularity",
"+=",
"1",
"peers",
".",
"append",
"(",
"peer_hostport",
")",
"ret",
"[",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
"]",
"[",
"'names'",
"]",
".",
"append",
"(",
"zfinfo",
"[",
"'name'",
"]",
")",
"ret",
"[",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
"]",
"[",
"'indexes'",
"]",
".",
"append",
"(",
"zfinfo",
"[",
"'inv_index'",
"]",
"-",
"1",
")",
"ret",
"[",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
"]",
"[",
"'block_heights'",
"]",
".",
"append",
"(",
"zfinfo",
"[",
"'block_height'",
"]",
")",
"ret",
"[",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
"]",
"[",
"'popularity'",
"]",
"+=",
"popularity",
"ret",
"[",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
"]",
"[",
"'peers'",
"]",
"+=",
"peers",
"ret",
"[",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
"]",
"[",
"'tried_storage'",
"]",
"=",
"zfinfo",
"[",
"'tried_storage'",
"]",
"return",
"ret"
] | Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
our clique (and we'll re-sync our neighborss' inventories
every so often to make sure we detect when zonefiles
become available).
Return a dict, structured as:
{
'zonefile hash': {
'names': [names],
'txid': first txid that set it,
'indexes': [...],
'popularity': ...,
'peers': [...],
'tried_storage': True|False
}
} | [
"Find",
"the",
"set",
"of",
"missing",
"zonefiles",
"as",
"well",
"as",
"their",
"popularity",
"amongst",
"our",
"neighbors",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2177-L2266 |
230,450 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_has_zonefile | def atlas_peer_has_zonefile( peer_hostport, zonefile_hash, zonefile_bits=None, con=None, path=None, peer_table=None ):
"""
Does the given peer have the given zonefile defined?
Check its inventory vector
Return True if present
Return False if not present
Return None if we don't know about the zonefile ourselves, or if we don't know about the peer
"""
bits = None
if zonefile_bits is None:
bits = atlasdb_get_zonefile_bits( zonefile_hash, con=con, path=path )
if len(bits) == 0:
return None
else:
bits = zonefile_bits
zonefile_inv = None
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
zonefile_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
res = atlas_inventory_test_zonefile_bits( zonefile_inv, bits )
return res | python | def atlas_peer_has_zonefile( peer_hostport, zonefile_hash, zonefile_bits=None, con=None, path=None, peer_table=None ):
"""
Does the given peer have the given zonefile defined?
Check its inventory vector
Return True if present
Return False if not present
Return None if we don't know about the zonefile ourselves, or if we don't know about the peer
"""
bits = None
if zonefile_bits is None:
bits = atlasdb_get_zonefile_bits( zonefile_hash, con=con, path=path )
if len(bits) == 0:
return None
else:
bits = zonefile_bits
zonefile_inv = None
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
zonefile_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
res = atlas_inventory_test_zonefile_bits( zonefile_inv, bits )
return res | [
"def",
"atlas_peer_has_zonefile",
"(",
"peer_hostport",
",",
"zonefile_hash",
",",
"zonefile_bits",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"peer_table",
"=",
"None",
")",
":",
"bits",
"=",
"None",
"if",
"zonefile_bits",
"is",
"None",
":",
"bits",
"=",
"atlasdb_get_zonefile_bits",
"(",
"zonefile_hash",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"0",
":",
"return",
"None",
"else",
":",
"bits",
"=",
"zonefile_bits",
"zonefile_inv",
"=",
"None",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_hostport",
"not",
"in",
"ptbl",
".",
"keys",
"(",
")",
":",
"return",
"False",
"zonefile_inv",
"=",
"atlas_peer_get_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"ptbl",
")",
"res",
"=",
"atlas_inventory_test_zonefile_bits",
"(",
"zonefile_inv",
",",
"bits",
")",
"return",
"res"
] | Does the given peer have the given zonefile defined?
Check its inventory vector
Return True if present
Return False if not present
Return None if we don't know about the zonefile ourselves, or if we don't know about the peer | [
"Does",
"the",
"given",
"peer",
"have",
"the",
"given",
"zonefile",
"defined?",
"Check",
"its",
"inventory",
"vector"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2269-L2297 |
230,451 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_get_neighbors | def atlas_peer_get_neighbors( my_hostport, peer_hostport, timeout=None, peer_table=None, con=None, path=None ):
"""
Ask the peer server at the given URL for its neighbors.
Update the health info in peer_table
(if not given, the global peer table will be used instead)
Return the list on success
Return None on failure to contact
Raise on invalid URL
"""
if timeout is None:
timeout = atlas_neighbors_timeout()
peer_list = None
host, port = url_to_host_port( peer_hostport )
RPC = get_rpc_client_class()
rpc = RPC( host, port, timeout=timeout, src=my_hostport )
# sane limits
max_neighbors = atlas_max_neighbors()
assert not atlas_peer_table_is_locked_by_me()
try:
peer_list = blockstack_atlas_peer_exchange( peer_hostport, my_hostport, timeout=timeout, proxy=rpc )
if json_is_exception(peer_list):
# fall back to legacy method
peer_list = blockstack_get_atlas_peers(peer_hostport, timeout=timeout, proxy=rpc)
except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
atlas_log_socket_error( "atlas_peer_exchange(%s)" % peer_hostport, peer_hostport, se)
log.error("Socket error in response from '%s'" % peer_hostport)
except Exception, e:
if os.environ.get("BLOCKSTACK_DEBUG") == "1":
log.exception(e)
log.error("Failed to talk to '%s'" % peer_hostport)
if peer_list is None:
log.error("Failed to query remote peer %s" % peer_hostport)
atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
return None
if 'error' in peer_list:
log.debug("Remote peer error: %s" % peer_list['error'])
log.error("Remote peer error on %s" % peer_hostport)
atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
return None
ret = peer_list['peers']
atlas_peer_update_health( peer_hostport, True, peer_table=peer_table )
return ret | python | def atlas_peer_get_neighbors( my_hostport, peer_hostport, timeout=None, peer_table=None, con=None, path=None ):
"""
Ask the peer server at the given URL for its neighbors.
Update the health info in peer_table
(if not given, the global peer table will be used instead)
Return the list on success
Return None on failure to contact
Raise on invalid URL
"""
if timeout is None:
timeout = atlas_neighbors_timeout()
peer_list = None
host, port = url_to_host_port( peer_hostport )
RPC = get_rpc_client_class()
rpc = RPC( host, port, timeout=timeout, src=my_hostport )
# sane limits
max_neighbors = atlas_max_neighbors()
assert not atlas_peer_table_is_locked_by_me()
try:
peer_list = blockstack_atlas_peer_exchange( peer_hostport, my_hostport, timeout=timeout, proxy=rpc )
if json_is_exception(peer_list):
# fall back to legacy method
peer_list = blockstack_get_atlas_peers(peer_hostport, timeout=timeout, proxy=rpc)
except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
atlas_log_socket_error( "atlas_peer_exchange(%s)" % peer_hostport, peer_hostport, se)
log.error("Socket error in response from '%s'" % peer_hostport)
except Exception, e:
if os.environ.get("BLOCKSTACK_DEBUG") == "1":
log.exception(e)
log.error("Failed to talk to '%s'" % peer_hostport)
if peer_list is None:
log.error("Failed to query remote peer %s" % peer_hostport)
atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
return None
if 'error' in peer_list:
log.debug("Remote peer error: %s" % peer_list['error'])
log.error("Remote peer error on %s" % peer_hostport)
atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
return None
ret = peer_list['peers']
atlas_peer_update_health( peer_hostport, True, peer_table=peer_table )
return ret | [
"def",
"atlas_peer_get_neighbors",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"timeout",
"=",
"None",
",",
"peer_table",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"atlas_neighbors_timeout",
"(",
")",
"peer_list",
"=",
"None",
"host",
",",
"port",
"=",
"url_to_host_port",
"(",
"peer_hostport",
")",
"RPC",
"=",
"get_rpc_client_class",
"(",
")",
"rpc",
"=",
"RPC",
"(",
"host",
",",
"port",
",",
"timeout",
"=",
"timeout",
",",
"src",
"=",
"my_hostport",
")",
"# sane limits",
"max_neighbors",
"=",
"atlas_max_neighbors",
"(",
")",
"assert",
"not",
"atlas_peer_table_is_locked_by_me",
"(",
")",
"try",
":",
"peer_list",
"=",
"blockstack_atlas_peer_exchange",
"(",
"peer_hostport",
",",
"my_hostport",
",",
"timeout",
"=",
"timeout",
",",
"proxy",
"=",
"rpc",
")",
"if",
"json_is_exception",
"(",
"peer_list",
")",
":",
"# fall back to legacy method ",
"peer_list",
"=",
"blockstack_get_atlas_peers",
"(",
"peer_hostport",
",",
"timeout",
"=",
"timeout",
",",
"proxy",
"=",
"rpc",
")",
"except",
"(",
"socket",
".",
"timeout",
",",
"socket",
".",
"gaierror",
",",
"socket",
".",
"herror",
",",
"socket",
".",
"error",
")",
",",
"se",
":",
"atlas_log_socket_error",
"(",
"\"atlas_peer_exchange(%s)\"",
"%",
"peer_hostport",
",",
"peer_hostport",
",",
"se",
")",
"log",
".",
"error",
"(",
"\"Socket error in response from '%s'\"",
"%",
"peer_hostport",
")",
"except",
"Exception",
",",
"e",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"BLOCKSTACK_DEBUG\"",
")",
"==",
"\"1\"",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"Failed to talk to '%s'\"",
"%",
"peer_hostport",
")",
"if",
"peer_list",
"is",
"None",
":",
"log",
".",
"error",
"(",
"\"Failed to query remote peer %s\"",
"%",
"peer_hostport",
")",
"atlas_peer_update_health",
"(",
"peer_hostport",
",",
"False",
",",
"peer_table",
"=",
"peer_table",
")",
"return",
"None",
"if",
"'error'",
"in",
"peer_list",
":",
"log",
".",
"debug",
"(",
"\"Remote peer error: %s\"",
"%",
"peer_list",
"[",
"'error'",
"]",
")",
"log",
".",
"error",
"(",
"\"Remote peer error on %s\"",
"%",
"peer_hostport",
")",
"atlas_peer_update_health",
"(",
"peer_hostport",
",",
"False",
",",
"peer_table",
"=",
"peer_table",
")",
"return",
"None",
"ret",
"=",
"peer_list",
"[",
"'peers'",
"]",
"atlas_peer_update_health",
"(",
"peer_hostport",
",",
"True",
",",
"peer_table",
"=",
"peer_table",
")",
"return",
"ret"
] | Ask the peer server at the given URL for its neighbors.
Update the health info in peer_table
(if not given, the global peer table will be used instead)
Return the list on success
Return None on failure to contact
Raise on invalid URL | [
"Ask",
"the",
"peer",
"server",
"at",
"the",
"given",
"URL",
"for",
"its",
"neighbors",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2300-L2354 |
230,452 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_get_zonefiles | def atlas_get_zonefiles( my_hostport, peer_hostport, zonefile_hashes, timeout=None, peer_table=None ):
"""
Given a list of zonefile hashes.
go and get them from the given host.
Update node health
Return the newly-fetched zonefiles on success (as a dict mapping hashes to zonefile data)
Return None on error.
"""
if timeout is None:
timeout = atlas_zonefiles_timeout()
zf_payload = None
zonefile_datas = {}
host, port = url_to_host_port( peer_hostport )
RPC = get_rpc_client_class()
rpc = RPC( host, port, timeout=timeout, src=my_hostport )
assert not atlas_peer_table_is_locked_by_me()
# get in batches of 100 or less
zf_batches = []
for i in xrange(0, len(zonefile_hashes), 100):
zf_batches.append(zonefile_hashes[i:i+100])
for zf_batch in zf_batches:
zf_payload = None
try:
zf_payload = blockstack_get_zonefiles( peer_hostport, zf_batch, timeout=timeout, my_hostport=my_hostport, proxy=rpc )
except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
atlas_log_socket_error( "get_zonefiles(%s)" % peer_hostport, peer_hostport, se)
except Exception, e:
if os.environ.get("BLOCKSTACK_DEBUG") is not None:
log.exception(e)
log.error("Invalid zonefile data from %s" % peer_hostport)
if zf_payload is None:
log.error("Failed to fetch zonefile data from %s" % peer_hostport)
atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
zonefile_datas = None
break
if 'error' in zf_payload.keys():
log.error("Failed to fetch zonefile data from %s: %s" % (peer_hostport, zf_payload['error']))
atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
zonefile_datas = None
break
# success!
zonefile_datas.update( zf_payload['zonefiles'] )
atlas_peer_update_health( peer_hostport, True, peer_table=peer_table )
return zonefile_datas | python | def atlas_get_zonefiles( my_hostport, peer_hostport, zonefile_hashes, timeout=None, peer_table=None ):
"""
Given a list of zonefile hashes.
go and get them from the given host.
Update node health
Return the newly-fetched zonefiles on success (as a dict mapping hashes to zonefile data)
Return None on error.
"""
if timeout is None:
timeout = atlas_zonefiles_timeout()
zf_payload = None
zonefile_datas = {}
host, port = url_to_host_port( peer_hostport )
RPC = get_rpc_client_class()
rpc = RPC( host, port, timeout=timeout, src=my_hostport )
assert not atlas_peer_table_is_locked_by_me()
# get in batches of 100 or less
zf_batches = []
for i in xrange(0, len(zonefile_hashes), 100):
zf_batches.append(zonefile_hashes[i:i+100])
for zf_batch in zf_batches:
zf_payload = None
try:
zf_payload = blockstack_get_zonefiles( peer_hostport, zf_batch, timeout=timeout, my_hostport=my_hostport, proxy=rpc )
except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
atlas_log_socket_error( "get_zonefiles(%s)" % peer_hostport, peer_hostport, se)
except Exception, e:
if os.environ.get("BLOCKSTACK_DEBUG") is not None:
log.exception(e)
log.error("Invalid zonefile data from %s" % peer_hostport)
if zf_payload is None:
log.error("Failed to fetch zonefile data from %s" % peer_hostport)
atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
zonefile_datas = None
break
if 'error' in zf_payload.keys():
log.error("Failed to fetch zonefile data from %s: %s" % (peer_hostport, zf_payload['error']))
atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
zonefile_datas = None
break
# success!
zonefile_datas.update( zf_payload['zonefiles'] )
atlas_peer_update_health( peer_hostport, True, peer_table=peer_table )
return zonefile_datas | [
"def",
"atlas_get_zonefiles",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"zonefile_hashes",
",",
"timeout",
"=",
"None",
",",
"peer_table",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"atlas_zonefiles_timeout",
"(",
")",
"zf_payload",
"=",
"None",
"zonefile_datas",
"=",
"{",
"}",
"host",
",",
"port",
"=",
"url_to_host_port",
"(",
"peer_hostport",
")",
"RPC",
"=",
"get_rpc_client_class",
"(",
")",
"rpc",
"=",
"RPC",
"(",
"host",
",",
"port",
",",
"timeout",
"=",
"timeout",
",",
"src",
"=",
"my_hostport",
")",
"assert",
"not",
"atlas_peer_table_is_locked_by_me",
"(",
")",
"# get in batches of 100 or less ",
"zf_batches",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"zonefile_hashes",
")",
",",
"100",
")",
":",
"zf_batches",
".",
"append",
"(",
"zonefile_hashes",
"[",
"i",
":",
"i",
"+",
"100",
"]",
")",
"for",
"zf_batch",
"in",
"zf_batches",
":",
"zf_payload",
"=",
"None",
"try",
":",
"zf_payload",
"=",
"blockstack_get_zonefiles",
"(",
"peer_hostport",
",",
"zf_batch",
",",
"timeout",
"=",
"timeout",
",",
"my_hostport",
"=",
"my_hostport",
",",
"proxy",
"=",
"rpc",
")",
"except",
"(",
"socket",
".",
"timeout",
",",
"socket",
".",
"gaierror",
",",
"socket",
".",
"herror",
",",
"socket",
".",
"error",
")",
",",
"se",
":",
"atlas_log_socket_error",
"(",
"\"get_zonefiles(%s)\"",
"%",
"peer_hostport",
",",
"peer_hostport",
",",
"se",
")",
"except",
"Exception",
",",
"e",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"BLOCKSTACK_DEBUG\"",
")",
"is",
"not",
"None",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"Invalid zonefile data from %s\"",
"%",
"peer_hostport",
")",
"if",
"zf_payload",
"is",
"None",
":",
"log",
".",
"error",
"(",
"\"Failed to fetch zonefile data from %s\"",
"%",
"peer_hostport",
")",
"atlas_peer_update_health",
"(",
"peer_hostport",
",",
"False",
",",
"peer_table",
"=",
"peer_table",
")",
"zonefile_datas",
"=",
"None",
"break",
"if",
"'error'",
"in",
"zf_payload",
".",
"keys",
"(",
")",
":",
"log",
".",
"error",
"(",
"\"Failed to fetch zonefile data from %s: %s\"",
"%",
"(",
"peer_hostport",
",",
"zf_payload",
"[",
"'error'",
"]",
")",
")",
"atlas_peer_update_health",
"(",
"peer_hostport",
",",
"False",
",",
"peer_table",
"=",
"peer_table",
")",
"zonefile_datas",
"=",
"None",
"break",
"# success!",
"zonefile_datas",
".",
"update",
"(",
"zf_payload",
"[",
"'zonefiles'",
"]",
")",
"atlas_peer_update_health",
"(",
"peer_hostport",
",",
"True",
",",
"peer_table",
"=",
"peer_table",
")",
"return",
"zonefile_datas"
] | Given a list of zonefile hashes.
go and get them from the given host.
Update node health
Return the newly-fetched zonefiles on success (as a dict mapping hashes to zonefile data)
Return None on error. | [
"Given",
"a",
"list",
"of",
"zonefile",
"hashes",
".",
"go",
"and",
"get",
"them",
"from",
"the",
"given",
"host",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2357-L2417 |
230,453 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_rank_peers_by_data_availability | def atlas_rank_peers_by_data_availability( peer_list=None, peer_table=None, local_inv=None, con=None, path=None ):
"""
Get a ranking of peers to contact for a zonefile.
Peers are ranked by the number of zonefiles they have
which we don't have.
This is used to select neighbors.
"""
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_list is None:
peer_list = ptbl.keys()[:]
if local_inv is None:
# what's my inventory?
inv_len = atlasdb_zonefile_inv_length( con=con, path=path )
local_inv = atlas_make_zonefile_inventory( 0, inv_len, con=con, path=path )
peer_availability_ranking = [] # (health score, peer hostport)
for peer_hostport in peer_list:
peer_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
# ignore peers that we don't have an inventory for
if len(peer_inv) == 0:
continue
availability_score = atlas_inventory_count_missing( local_inv, peer_inv )
peer_availability_ranking.append( (availability_score, peer_hostport) )
# sort on availability
peer_availability_ranking.sort()
peer_availability_ranking.reverse()
return [peer_hp for _, peer_hp in peer_availability_ranking] | python | def atlas_rank_peers_by_data_availability( peer_list=None, peer_table=None, local_inv=None, con=None, path=None ):
"""
Get a ranking of peers to contact for a zonefile.
Peers are ranked by the number of zonefiles they have
which we don't have.
This is used to select neighbors.
"""
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_list is None:
peer_list = ptbl.keys()[:]
if local_inv is None:
# what's my inventory?
inv_len = atlasdb_zonefile_inv_length( con=con, path=path )
local_inv = atlas_make_zonefile_inventory( 0, inv_len, con=con, path=path )
peer_availability_ranking = [] # (health score, peer hostport)
for peer_hostport in peer_list:
peer_inv = atlas_peer_get_zonefile_inventory( peer_hostport, peer_table=ptbl )
# ignore peers that we don't have an inventory for
if len(peer_inv) == 0:
continue
availability_score = atlas_inventory_count_missing( local_inv, peer_inv )
peer_availability_ranking.append( (availability_score, peer_hostport) )
# sort on availability
peer_availability_ranking.sort()
peer_availability_ranking.reverse()
return [peer_hp for _, peer_hp in peer_availability_ranking] | [
"def",
"atlas_rank_peers_by_data_availability",
"(",
"peer_list",
"=",
"None",
",",
"peer_table",
"=",
"None",
",",
"local_inv",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"if",
"peer_list",
"is",
"None",
":",
"peer_list",
"=",
"ptbl",
".",
"keys",
"(",
")",
"[",
":",
"]",
"if",
"local_inv",
"is",
"None",
":",
"# what's my inventory?",
"inv_len",
"=",
"atlasdb_zonefile_inv_length",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"local_inv",
"=",
"atlas_make_zonefile_inventory",
"(",
"0",
",",
"inv_len",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"peer_availability_ranking",
"=",
"[",
"]",
"# (health score, peer hostport)",
"for",
"peer_hostport",
"in",
"peer_list",
":",
"peer_inv",
"=",
"atlas_peer_get_zonefile_inventory",
"(",
"peer_hostport",
",",
"peer_table",
"=",
"ptbl",
")",
"# ignore peers that we don't have an inventory for",
"if",
"len",
"(",
"peer_inv",
")",
"==",
"0",
":",
"continue",
"availability_score",
"=",
"atlas_inventory_count_missing",
"(",
"local_inv",
",",
"peer_inv",
")",
"peer_availability_ranking",
".",
"append",
"(",
"(",
"availability_score",
",",
"peer_hostport",
")",
")",
"# sort on availability",
"peer_availability_ranking",
".",
"sort",
"(",
")",
"peer_availability_ranking",
".",
"reverse",
"(",
")",
"return",
"[",
"peer_hp",
"for",
"_",
",",
"peer_hp",
"in",
"peer_availability_ranking",
"]"
] | Get a ranking of peers to contact for a zonefile.
Peers are ranked by the number of zonefiles they have
which we don't have.
This is used to select neighbors. | [
"Get",
"a",
"ranking",
"of",
"peers",
"to",
"contact",
"for",
"a",
"zonefile",
".",
"Peers",
"are",
"ranked",
"by",
"the",
"number",
"of",
"zonefiles",
"they",
"have",
"which",
"we",
"don",
"t",
"have",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2453-L2488 |
230,454 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_peer_dequeue_all | def atlas_peer_dequeue_all( peer_queue=None ):
"""
Get all queued peers
"""
peers = []
with AtlasPeerQueueLocked(peer_queue) as pq:
while len(pq) > 0:
peers.append( pq.pop(0) )
return peers | python | def atlas_peer_dequeue_all( peer_queue=None ):
"""
Get all queued peers
"""
peers = []
with AtlasPeerQueueLocked(peer_queue) as pq:
while len(pq) > 0:
peers.append( pq.pop(0) )
return peers | [
"def",
"atlas_peer_dequeue_all",
"(",
"peer_queue",
"=",
"None",
")",
":",
"peers",
"=",
"[",
"]",
"with",
"AtlasPeerQueueLocked",
"(",
"peer_queue",
")",
"as",
"pq",
":",
"while",
"len",
"(",
"pq",
")",
">",
"0",
":",
"peers",
".",
"append",
"(",
"pq",
".",
"pop",
"(",
"0",
")",
")",
"return",
"peers"
] | Get all queued peers | [
"Get",
"all",
"queued",
"peers"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2524-L2534 |
230,455 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_zonefile_push_enqueue | def atlas_zonefile_push_enqueue( zonefile_hash, name, txid, zonefile_data, zonefile_queue=None, con=None, path=None ):
"""
Enqueue the given zonefile into our "push" queue,
from which it will be replicated to storage and sent
out to other peers who don't have it.
Return True if we enqueued it
Return False if not
"""
res = False
bits = atlasdb_get_zonefile_bits( zonefile_hash, path=path, con=con )
if len(bits) == 0:
# invalid hash
return
with AtlasZonefileQueueLocked(zonefile_queue) as zfq:
if len(zfq) < MAX_QUEUED_ZONEFILES:
zfdata = {
'zonefile_hash': zonefile_hash,
'zonefile': zonefile_data,
'name': name,
'txid': txid
}
zfq.append( zfdata )
res = True
return res | python | def atlas_zonefile_push_enqueue( zonefile_hash, name, txid, zonefile_data, zonefile_queue=None, con=None, path=None ):
"""
Enqueue the given zonefile into our "push" queue,
from which it will be replicated to storage and sent
out to other peers who don't have it.
Return True if we enqueued it
Return False if not
"""
res = False
bits = atlasdb_get_zonefile_bits( zonefile_hash, path=path, con=con )
if len(bits) == 0:
# invalid hash
return
with AtlasZonefileQueueLocked(zonefile_queue) as zfq:
if len(zfq) < MAX_QUEUED_ZONEFILES:
zfdata = {
'zonefile_hash': zonefile_hash,
'zonefile': zonefile_data,
'name': name,
'txid': txid
}
zfq.append( zfdata )
res = True
return res | [
"def",
"atlas_zonefile_push_enqueue",
"(",
"zonefile_hash",
",",
"name",
",",
"txid",
",",
"zonefile_data",
",",
"zonefile_queue",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"res",
"=",
"False",
"bits",
"=",
"atlasdb_get_zonefile_bits",
"(",
"zonefile_hash",
",",
"path",
"=",
"path",
",",
"con",
"=",
"con",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"0",
":",
"# invalid hash",
"return",
"with",
"AtlasZonefileQueueLocked",
"(",
"zonefile_queue",
")",
"as",
"zfq",
":",
"if",
"len",
"(",
"zfq",
")",
"<",
"MAX_QUEUED_ZONEFILES",
":",
"zfdata",
"=",
"{",
"'zonefile_hash'",
":",
"zonefile_hash",
",",
"'zonefile'",
":",
"zonefile_data",
",",
"'name'",
":",
"name",
",",
"'txid'",
":",
"txid",
"}",
"zfq",
".",
"append",
"(",
"zfdata",
")",
"res",
"=",
"True",
"return",
"res"
] | Enqueue the given zonefile into our "push" queue,
from which it will be replicated to storage and sent
out to other peers who don't have it.
Return True if we enqueued it
Return False if not | [
"Enqueue",
"the",
"given",
"zonefile",
"into",
"our",
"push",
"queue",
"from",
"which",
"it",
"will",
"be",
"replicated",
"to",
"storage",
"and",
"sent",
"out",
"to",
"other",
"peers",
"who",
"don",
"t",
"have",
"it",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2560-L2589 |
230,456 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_zonefile_push_dequeue | def atlas_zonefile_push_dequeue( zonefile_queue=None ):
"""
Dequeue a zonefile's information to replicate
Return None if there are none queued
"""
ret = None
with AtlasZonefileQueueLocked(zonefile_queue) as zfq:
if len(zfq) > 0:
ret = zfq.pop(0)
return ret | python | def atlas_zonefile_push_dequeue( zonefile_queue=None ):
"""
Dequeue a zonefile's information to replicate
Return None if there are none queued
"""
ret = None
with AtlasZonefileQueueLocked(zonefile_queue) as zfq:
if len(zfq) > 0:
ret = zfq.pop(0)
return ret | [
"def",
"atlas_zonefile_push_dequeue",
"(",
"zonefile_queue",
"=",
"None",
")",
":",
"ret",
"=",
"None",
"with",
"AtlasZonefileQueueLocked",
"(",
"zonefile_queue",
")",
"as",
"zfq",
":",
"if",
"len",
"(",
"zfq",
")",
">",
"0",
":",
"ret",
"=",
"zfq",
".",
"pop",
"(",
"0",
")",
"return",
"ret"
] | Dequeue a zonefile's information to replicate
Return None if there are none queued | [
"Dequeue",
"a",
"zonefile",
"s",
"information",
"to",
"replicate",
"Return",
"None",
"if",
"there",
"are",
"none",
"queued"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2592-L2602 |
230,457 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_zonefile_push | def atlas_zonefile_push( my_hostport, peer_hostport, zonefile_data, timeout=None, peer_table=None ):
"""
Push the given zonefile to the given peer
Return True on success
Return False on failure
"""
if timeout is None:
timeout = atlas_push_zonefiles_timeout()
zonefile_hash = get_zonefile_data_hash(zonefile_data)
zonefile_data_b64 = base64.b64encode( zonefile_data )
host, port = url_to_host_port( peer_hostport )
RPC = get_rpc_client_class()
rpc = RPC( host, port, timeout=timeout, src=my_hostport )
status = False
assert not atlas_peer_table_is_locked_by_me()
try:
push_info = blockstack_put_zonefiles( peer_hostport, [zonefile_data_b64], timeout=timeout, my_hostport=my_hostport, proxy=rpc )
if 'error' not in push_info:
if push_info['saved'] == 1:
# woo!
saved = True
except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
atlas_log_socket_error( "put_zonefiles(%s)" % peer_hostport, peer_hostport, se)
except AssertionError, ae:
log.exception(ae)
log.error("Invalid server response from %s" % peer_hostport )
except Exception, e:
log.exception(e)
log.error("Failed to push zonefile %s to %s" % (zonefile_hash, peer_hostport))
with AtlasPeerTableLocked(peer_table) as ptbl:
atlas_peer_update_health( peer_hostport, status, peer_table=ptbl )
return status | python | def atlas_zonefile_push( my_hostport, peer_hostport, zonefile_data, timeout=None, peer_table=None ):
"""
Push the given zonefile to the given peer
Return True on success
Return False on failure
"""
if timeout is None:
timeout = atlas_push_zonefiles_timeout()
zonefile_hash = get_zonefile_data_hash(zonefile_data)
zonefile_data_b64 = base64.b64encode( zonefile_data )
host, port = url_to_host_port( peer_hostport )
RPC = get_rpc_client_class()
rpc = RPC( host, port, timeout=timeout, src=my_hostport )
status = False
assert not atlas_peer_table_is_locked_by_me()
try:
push_info = blockstack_put_zonefiles( peer_hostport, [zonefile_data_b64], timeout=timeout, my_hostport=my_hostport, proxy=rpc )
if 'error' not in push_info:
if push_info['saved'] == 1:
# woo!
saved = True
except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
atlas_log_socket_error( "put_zonefiles(%s)" % peer_hostport, peer_hostport, se)
except AssertionError, ae:
log.exception(ae)
log.error("Invalid server response from %s" % peer_hostport )
except Exception, e:
log.exception(e)
log.error("Failed to push zonefile %s to %s" % (zonefile_hash, peer_hostport))
with AtlasPeerTableLocked(peer_table) as ptbl:
atlas_peer_update_health( peer_hostport, status, peer_table=ptbl )
return status | [
"def",
"atlas_zonefile_push",
"(",
"my_hostport",
",",
"peer_hostport",
",",
"zonefile_data",
",",
"timeout",
"=",
"None",
",",
"peer_table",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"atlas_push_zonefiles_timeout",
"(",
")",
"zonefile_hash",
"=",
"get_zonefile_data_hash",
"(",
"zonefile_data",
")",
"zonefile_data_b64",
"=",
"base64",
".",
"b64encode",
"(",
"zonefile_data",
")",
"host",
",",
"port",
"=",
"url_to_host_port",
"(",
"peer_hostport",
")",
"RPC",
"=",
"get_rpc_client_class",
"(",
")",
"rpc",
"=",
"RPC",
"(",
"host",
",",
"port",
",",
"timeout",
"=",
"timeout",
",",
"src",
"=",
"my_hostport",
")",
"status",
"=",
"False",
"assert",
"not",
"atlas_peer_table_is_locked_by_me",
"(",
")",
"try",
":",
"push_info",
"=",
"blockstack_put_zonefiles",
"(",
"peer_hostport",
",",
"[",
"zonefile_data_b64",
"]",
",",
"timeout",
"=",
"timeout",
",",
"my_hostport",
"=",
"my_hostport",
",",
"proxy",
"=",
"rpc",
")",
"if",
"'error'",
"not",
"in",
"push_info",
":",
"if",
"push_info",
"[",
"'saved'",
"]",
"==",
"1",
":",
"# woo!",
"saved",
"=",
"True",
"except",
"(",
"socket",
".",
"timeout",
",",
"socket",
".",
"gaierror",
",",
"socket",
".",
"herror",
",",
"socket",
".",
"error",
")",
",",
"se",
":",
"atlas_log_socket_error",
"(",
"\"put_zonefiles(%s)\"",
"%",
"peer_hostport",
",",
"peer_hostport",
",",
"se",
")",
"except",
"AssertionError",
",",
"ae",
":",
"log",
".",
"exception",
"(",
"ae",
")",
"log",
".",
"error",
"(",
"\"Invalid server response from %s\"",
"%",
"peer_hostport",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"Failed to push zonefile %s to %s\"",
"%",
"(",
"zonefile_hash",
",",
"peer_hostport",
")",
")",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"atlas_peer_update_health",
"(",
"peer_hostport",
",",
"status",
",",
"peer_table",
"=",
"ptbl",
")",
"return",
"status"
] | Push the given zonefile to the given peer
Return True on success
Return False on failure | [
"Push",
"the",
"given",
"zonefile",
"to",
"the",
"given",
"peer",
"Return",
"True",
"on",
"success",
"Return",
"False",
"on",
"failure"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2605-L2646 |
230,458 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_node_init | def atlas_node_init(my_hostname, my_portnum, atlasdb_path, zonefile_dir, working_dir):
"""
Start up the atlas node.
Return a bundle of atlas state
"""
atlas_state = {}
atlas_state['peer_crawler'] = AtlasPeerCrawler(my_hostname, my_portnum, atlasdb_path, working_dir)
atlas_state['health_checker'] = AtlasHealthChecker(my_hostname, my_portnum, atlasdb_path)
atlas_state['zonefile_crawler'] = AtlasZonefileCrawler(my_hostname, my_portnum, atlasdb_path, zonefile_dir)
# atlas_state['zonefile_pusher'] = AtlasZonefilePusher(my_hostname, my_portnum, atlasdb_path, zonefile_dir)
return atlas_state | python | def atlas_node_init(my_hostname, my_portnum, atlasdb_path, zonefile_dir, working_dir):
"""
Start up the atlas node.
Return a bundle of atlas state
"""
atlas_state = {}
atlas_state['peer_crawler'] = AtlasPeerCrawler(my_hostname, my_portnum, atlasdb_path, working_dir)
atlas_state['health_checker'] = AtlasHealthChecker(my_hostname, my_portnum, atlasdb_path)
atlas_state['zonefile_crawler'] = AtlasZonefileCrawler(my_hostname, my_portnum, atlasdb_path, zonefile_dir)
# atlas_state['zonefile_pusher'] = AtlasZonefilePusher(my_hostname, my_portnum, atlasdb_path, zonefile_dir)
return atlas_state | [
"def",
"atlas_node_init",
"(",
"my_hostname",
",",
"my_portnum",
",",
"atlasdb_path",
",",
"zonefile_dir",
",",
"working_dir",
")",
":",
"atlas_state",
"=",
"{",
"}",
"atlas_state",
"[",
"'peer_crawler'",
"]",
"=",
"AtlasPeerCrawler",
"(",
"my_hostname",
",",
"my_portnum",
",",
"atlasdb_path",
",",
"working_dir",
")",
"atlas_state",
"[",
"'health_checker'",
"]",
"=",
"AtlasHealthChecker",
"(",
"my_hostname",
",",
"my_portnum",
",",
"atlasdb_path",
")",
"atlas_state",
"[",
"'zonefile_crawler'",
"]",
"=",
"AtlasZonefileCrawler",
"(",
"my_hostname",
",",
"my_portnum",
",",
"atlasdb_path",
",",
"zonefile_dir",
")",
"# atlas_state['zonefile_pusher'] = AtlasZonefilePusher(my_hostname, my_portnum, atlasdb_path, zonefile_dir)",
"return",
"atlas_state"
] | Start up the atlas node.
Return a bundle of atlas state | [
"Start",
"up",
"the",
"atlas",
"node",
".",
"Return",
"a",
"bundle",
"of",
"atlas",
"state"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L3584-L3595 |
230,459 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_node_start | def atlas_node_start(atlas_state):
"""
Start up atlas threads
"""
for component in atlas_state.keys():
log.debug("Starting Atlas component '%s'" % component)
atlas_state[component].start() | python | def atlas_node_start(atlas_state):
"""
Start up atlas threads
"""
for component in atlas_state.keys():
log.debug("Starting Atlas component '%s'" % component)
atlas_state[component].start() | [
"def",
"atlas_node_start",
"(",
"atlas_state",
")",
":",
"for",
"component",
"in",
"atlas_state",
".",
"keys",
"(",
")",
":",
"log",
".",
"debug",
"(",
"\"Starting Atlas component '%s'\"",
"%",
"component",
")",
"atlas_state",
"[",
"component",
"]",
".",
"start",
"(",
")"
] | Start up atlas threads | [
"Start",
"up",
"atlas",
"threads"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L3597-L3603 |
230,460 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_node_add_callback | def atlas_node_add_callback(atlas_state, callback_name, callback):
"""
Add a callback to the initialized atlas state
"""
if callback_name == 'store_zonefile':
atlas_state['zonefile_crawler'].set_store_zonefile_callback(callback)
else:
raise ValueError("Unrecognized callback {}".format(callback_name)) | python | def atlas_node_add_callback(atlas_state, callback_name, callback):
"""
Add a callback to the initialized atlas state
"""
if callback_name == 'store_zonefile':
atlas_state['zonefile_crawler'].set_store_zonefile_callback(callback)
else:
raise ValueError("Unrecognized callback {}".format(callback_name)) | [
"def",
"atlas_node_add_callback",
"(",
"atlas_state",
",",
"callback_name",
",",
"callback",
")",
":",
"if",
"callback_name",
"==",
"'store_zonefile'",
":",
"atlas_state",
"[",
"'zonefile_crawler'",
"]",
".",
"set_store_zonefile_callback",
"(",
"callback",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unrecognized callback {}\"",
".",
"format",
"(",
"callback_name",
")",
")"
] | Add a callback to the initialized atlas state | [
"Add",
"a",
"callback",
"to",
"the",
"initialized",
"atlas",
"state"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L3606-L3614 |
230,461 | blockstack/blockstack-core | blockstack/lib/atlas.py | atlas_node_stop | def atlas_node_stop( atlas_state ):
"""
Stop the atlas node threads
"""
for component in atlas_state.keys():
log.debug("Stopping Atlas component '%s'" % component)
atlas_state[component].ask_join()
atlas_state[component].join()
return True | python | def atlas_node_stop( atlas_state ):
"""
Stop the atlas node threads
"""
for component in atlas_state.keys():
log.debug("Stopping Atlas component '%s'" % component)
atlas_state[component].ask_join()
atlas_state[component].join()
return True | [
"def",
"atlas_node_stop",
"(",
"atlas_state",
")",
":",
"for",
"component",
"in",
"atlas_state",
".",
"keys",
"(",
")",
":",
"log",
".",
"debug",
"(",
"\"Stopping Atlas component '%s'\"",
"%",
"component",
")",
"atlas_state",
"[",
"component",
"]",
".",
"ask_join",
"(",
")",
"atlas_state",
"[",
"component",
"]",
".",
"join",
"(",
")",
"return",
"True"
] | Stop the atlas node threads | [
"Stop",
"the",
"atlas",
"node",
"threads"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L3617-L3626 |
230,462 | blockstack/blockstack-core | blockstack/lib/atlas.py | AtlasPeerCrawler.canonical_peer | def canonical_peer( self, peer ):
"""
Get the canonical peer name
"""
their_host, their_port = url_to_host_port( peer )
if their_host in ['127.0.0.1', '::1']:
their_host = 'localhost'
return "%s:%s" % (their_host, their_port) | python | def canonical_peer( self, peer ):
"""
Get the canonical peer name
"""
their_host, their_port = url_to_host_port( peer )
if their_host in ['127.0.0.1', '::1']:
their_host = 'localhost'
return "%s:%s" % (their_host, their_port) | [
"def",
"canonical_peer",
"(",
"self",
",",
"peer",
")",
":",
"their_host",
",",
"their_port",
"=",
"url_to_host_port",
"(",
"peer",
")",
"if",
"their_host",
"in",
"[",
"'127.0.0.1'",
",",
"'::1'",
"]",
":",
"their_host",
"=",
"'localhost'",
"return",
"\"%s:%s\"",
"%",
"(",
"their_host",
",",
"their_port",
")"
] | Get the canonical peer name | [
"Get",
"the",
"canonical",
"peer",
"name"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2713-L2722 |
230,463 | blockstack/blockstack-core | blockstack/lib/atlas.py | AtlasPeerCrawler.remove_unhealthy_peers | def remove_unhealthy_peers( self, count, con=None, path=None, peer_table=None, min_request_count=10, min_health=MIN_PEER_HEALTH ):
"""
Remove up to @count unhealthy peers
Return the list of peers we removed
"""
if path is None:
path = self.atlasdb_path
removed = []
rank_peer_list = atlas_rank_peers_by_health( peer_table=peer_table, with_rank=True )
for rank, peer in rank_peer_list:
reqcount = atlas_peer_get_request_count( peer, peer_table=peer_table )
if reqcount >= min_request_count and rank < min_health and not atlas_peer_is_whitelisted( peer, peer_table=peer_table ) and not atlas_peer_is_blacklisted( peer, peer_table=peer_table ):
removed.append( peer )
random.shuffle(removed)
if len(removed) > count:
removed = removed[:count]
for peer in removed:
log.debug("Remove unhealthy peer %s" % (peer))
atlasdb_remove_peer( peer, con=con, path=path, peer_table=peer_table )
return removed | python | def remove_unhealthy_peers( self, count, con=None, path=None, peer_table=None, min_request_count=10, min_health=MIN_PEER_HEALTH ):
"""
Remove up to @count unhealthy peers
Return the list of peers we removed
"""
if path is None:
path = self.atlasdb_path
removed = []
rank_peer_list = atlas_rank_peers_by_health( peer_table=peer_table, with_rank=True )
for rank, peer in rank_peer_list:
reqcount = atlas_peer_get_request_count( peer, peer_table=peer_table )
if reqcount >= min_request_count and rank < min_health and not atlas_peer_is_whitelisted( peer, peer_table=peer_table ) and not atlas_peer_is_blacklisted( peer, peer_table=peer_table ):
removed.append( peer )
random.shuffle(removed)
if len(removed) > count:
removed = removed[:count]
for peer in removed:
log.debug("Remove unhealthy peer %s" % (peer))
atlasdb_remove_peer( peer, con=con, path=path, peer_table=peer_table )
return removed | [
"def",
"remove_unhealthy_peers",
"(",
"self",
",",
"count",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"peer_table",
"=",
"None",
",",
"min_request_count",
"=",
"10",
",",
"min_health",
"=",
"MIN_PEER_HEALTH",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"atlasdb_path",
"removed",
"=",
"[",
"]",
"rank_peer_list",
"=",
"atlas_rank_peers_by_health",
"(",
"peer_table",
"=",
"peer_table",
",",
"with_rank",
"=",
"True",
")",
"for",
"rank",
",",
"peer",
"in",
"rank_peer_list",
":",
"reqcount",
"=",
"atlas_peer_get_request_count",
"(",
"peer",
",",
"peer_table",
"=",
"peer_table",
")",
"if",
"reqcount",
">=",
"min_request_count",
"and",
"rank",
"<",
"min_health",
"and",
"not",
"atlas_peer_is_whitelisted",
"(",
"peer",
",",
"peer_table",
"=",
"peer_table",
")",
"and",
"not",
"atlas_peer_is_blacklisted",
"(",
"peer",
",",
"peer_table",
"=",
"peer_table",
")",
":",
"removed",
".",
"append",
"(",
"peer",
")",
"random",
".",
"shuffle",
"(",
"removed",
")",
"if",
"len",
"(",
"removed",
")",
">",
"count",
":",
"removed",
"=",
"removed",
"[",
":",
"count",
"]",
"for",
"peer",
"in",
"removed",
":",
"log",
".",
"debug",
"(",
"\"Remove unhealthy peer %s\"",
"%",
"(",
"peer",
")",
")",
"atlasdb_remove_peer",
"(",
"peer",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
",",
"peer_table",
"=",
"peer_table",
")",
"return",
"removed"
] | Remove up to @count unhealthy peers
Return the list of peers we removed | [
"Remove",
"up",
"to"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2836-L2860 |
230,464 | blockstack/blockstack-core | blockstack/lib/atlas.py | AtlasPeerCrawler.get_current_peers | def get_current_peers( self, peer_table=None ):
"""
Get the current set of peers
"""
# get current peers
current_peers = None
with AtlasPeerTableLocked(peer_table) as ptbl:
current_peers = ptbl.keys()[:]
return current_peers | python | def get_current_peers( self, peer_table=None ):
"""
Get the current set of peers
"""
# get current peers
current_peers = None
with AtlasPeerTableLocked(peer_table) as ptbl:
current_peers = ptbl.keys()[:]
return current_peers | [
"def",
"get_current_peers",
"(",
"self",
",",
"peer_table",
"=",
"None",
")",
":",
"# get current peers",
"current_peers",
"=",
"None",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"current_peers",
"=",
"ptbl",
".",
"keys",
"(",
")",
"[",
":",
"]",
"return",
"current_peers"
] | Get the current set of peers | [
"Get",
"the",
"current",
"set",
"of",
"peers"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2945-L2955 |
230,465 | blockstack/blockstack-core | blockstack/lib/atlas.py | AtlasPeerCrawler.canonical_new_peer_list | def canonical_new_peer_list( self, peers_to_add ):
"""
Make a list of canonical new peers, using the
self.new_peers and the given peers to add
Return a shuffled list of canonicalized host:port
strings.
"""
new_peers = list(set(self.new_peers + peers_to_add))
random.shuffle( new_peers )
# canonicalize
tmp = []
for peer in new_peers:
tmp.append( self.canonical_peer(peer) )
new_peers = tmp
# don't talk to myself
if self.my_hostport in new_peers:
new_peers.remove(self.my_hostport)
return new_peers | python | def canonical_new_peer_list( self, peers_to_add ):
"""
Make a list of canonical new peers, using the
self.new_peers and the given peers to add
Return a shuffled list of canonicalized host:port
strings.
"""
new_peers = list(set(self.new_peers + peers_to_add))
random.shuffle( new_peers )
# canonicalize
tmp = []
for peer in new_peers:
tmp.append( self.canonical_peer(peer) )
new_peers = tmp
# don't talk to myself
if self.my_hostport in new_peers:
new_peers.remove(self.my_hostport)
return new_peers | [
"def",
"canonical_new_peer_list",
"(",
"self",
",",
"peers_to_add",
")",
":",
"new_peers",
"=",
"list",
"(",
"set",
"(",
"self",
".",
"new_peers",
"+",
"peers_to_add",
")",
")",
"random",
".",
"shuffle",
"(",
"new_peers",
")",
"# canonicalize",
"tmp",
"=",
"[",
"]",
"for",
"peer",
"in",
"new_peers",
":",
"tmp",
".",
"append",
"(",
"self",
".",
"canonical_peer",
"(",
"peer",
")",
")",
"new_peers",
"=",
"tmp",
"# don't talk to myself",
"if",
"self",
".",
"my_hostport",
"in",
"new_peers",
":",
"new_peers",
".",
"remove",
"(",
"self",
".",
"my_hostport",
")",
"return",
"new_peers"
] | Make a list of canonical new peers, using the
self.new_peers and the given peers to add
Return a shuffled list of canonicalized host:port
strings. | [
"Make",
"a",
"list",
"of",
"canonical",
"new",
"peers",
"using",
"the",
"self",
".",
"new_peers",
"and",
"the",
"given",
"peers",
"to",
"add"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2958-L2980 |
230,466 | blockstack/blockstack-core | blockstack/lib/atlas.py | AtlasHealthChecker.step | def step(self, con=None, path=None, peer_table=None, local_inv=None):
"""
Find peers with stale zonefile inventory data,
and refresh them.
Return True on success
Return False on error
"""
if path is None:
path = self.atlasdb_path
peer_hostports = []
stale_peers = []
num_peers = None
peer_hostports = None
with AtlasPeerTableLocked(peer_table) as ptbl:
num_peers = len(ptbl.keys())
peer_hostports = ptbl.keys()[:]
# who are we going to ping?
# someone we haven't pinged in a while, chosen at random
for peer in peer_hostports:
if not atlas_peer_has_fresh_zonefile_inventory( peer, peer_table=ptbl ):
# haven't talked to this peer in a while
stale_peers.append(peer)
log.debug("Peer %s has a stale zonefile inventory" % peer)
if len(stale_peers) > 0:
log.debug("Refresh zonefile inventories for %s peers" % len(stale_peers))
for peer_hostport in stale_peers:
# refresh everyone
log.debug("%s: Refresh zonefile inventory for %s" % (self.hostport, peer_hostport))
res = atlas_peer_refresh_zonefile_inventory( self.hostport, peer_hostport, 0, con=con, path=path, peer_table=peer_table, local_inv=local_inv )
if res is None:
log.warning("Failed to refresh zonefile inventory for %s" % peer_hostport)
return | python | def step(self, con=None, path=None, peer_table=None, local_inv=None):
"""
Find peers with stale zonefile inventory data,
and refresh them.
Return True on success
Return False on error
"""
if path is None:
path = self.atlasdb_path
peer_hostports = []
stale_peers = []
num_peers = None
peer_hostports = None
with AtlasPeerTableLocked(peer_table) as ptbl:
num_peers = len(ptbl.keys())
peer_hostports = ptbl.keys()[:]
# who are we going to ping?
# someone we haven't pinged in a while, chosen at random
for peer in peer_hostports:
if not atlas_peer_has_fresh_zonefile_inventory( peer, peer_table=ptbl ):
# haven't talked to this peer in a while
stale_peers.append(peer)
log.debug("Peer %s has a stale zonefile inventory" % peer)
if len(stale_peers) > 0:
log.debug("Refresh zonefile inventories for %s peers" % len(stale_peers))
for peer_hostport in stale_peers:
# refresh everyone
log.debug("%s: Refresh zonefile inventory for %s" % (self.hostport, peer_hostport))
res = atlas_peer_refresh_zonefile_inventory( self.hostport, peer_hostport, 0, con=con, path=path, peer_table=peer_table, local_inv=local_inv )
if res is None:
log.warning("Failed to refresh zonefile inventory for %s" % peer_hostport)
return | [
"def",
"step",
"(",
"self",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"peer_table",
"=",
"None",
",",
"local_inv",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"atlasdb_path",
"peer_hostports",
"=",
"[",
"]",
"stale_peers",
"=",
"[",
"]",
"num_peers",
"=",
"None",
"peer_hostports",
"=",
"None",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"num_peers",
"=",
"len",
"(",
"ptbl",
".",
"keys",
"(",
")",
")",
"peer_hostports",
"=",
"ptbl",
".",
"keys",
"(",
")",
"[",
":",
"]",
"# who are we going to ping?",
"# someone we haven't pinged in a while, chosen at random",
"for",
"peer",
"in",
"peer_hostports",
":",
"if",
"not",
"atlas_peer_has_fresh_zonefile_inventory",
"(",
"peer",
",",
"peer_table",
"=",
"ptbl",
")",
":",
"# haven't talked to this peer in a while",
"stale_peers",
".",
"append",
"(",
"peer",
")",
"log",
".",
"debug",
"(",
"\"Peer %s has a stale zonefile inventory\"",
"%",
"peer",
")",
"if",
"len",
"(",
"stale_peers",
")",
">",
"0",
":",
"log",
".",
"debug",
"(",
"\"Refresh zonefile inventories for %s peers\"",
"%",
"len",
"(",
"stale_peers",
")",
")",
"for",
"peer_hostport",
"in",
"stale_peers",
":",
"# refresh everyone",
"log",
".",
"debug",
"(",
"\"%s: Refresh zonefile inventory for %s\"",
"%",
"(",
"self",
".",
"hostport",
",",
"peer_hostport",
")",
")",
"res",
"=",
"atlas_peer_refresh_zonefile_inventory",
"(",
"self",
".",
"hostport",
",",
"peer_hostport",
",",
"0",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
",",
"peer_table",
"=",
"peer_table",
",",
"local_inv",
"=",
"local_inv",
")",
"if",
"res",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"Failed to refresh zonefile inventory for %s\"",
"%",
"peer_hostport",
")",
"return"
] | Find peers with stale zonefile inventory data,
and refresh them.
Return True on success
Return False on error | [
"Find",
"peers",
"with",
"stale",
"zonefile",
"inventory",
"data",
"and",
"refresh",
"them",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L3171-L3210 |
230,467 | blockstack/blockstack-core | blockstack/lib/atlas.py | AtlasHealthChecker.run | def run(self, peer_table=None):
"""
Loop forever, pinging someone every pass.
"""
self.running = True
while self.running:
local_inv = atlas_get_zonefile_inventory()
t1 = time_now()
self.step( peer_table=peer_table, local_inv=local_inv, path=self.atlasdb_path )
t2 = time_now()
# don't go too fast
if t2 - t1 < PEER_HEALTH_NEIGHBOR_WORK_INTERVAL:
deadline = time_now() + PEER_HEALTH_NEIGHBOR_WORK_INTERVAL - (t2 - t1)
while time_now() < deadline and self.running:
time_sleep( self.hostport, self.__class__.__name__, 1.0 )
if not self.running:
break | python | def run(self, peer_table=None):
"""
Loop forever, pinging someone every pass.
"""
self.running = True
while self.running:
local_inv = atlas_get_zonefile_inventory()
t1 = time_now()
self.step( peer_table=peer_table, local_inv=local_inv, path=self.atlasdb_path )
t2 = time_now()
# don't go too fast
if t2 - t1 < PEER_HEALTH_NEIGHBOR_WORK_INTERVAL:
deadline = time_now() + PEER_HEALTH_NEIGHBOR_WORK_INTERVAL - (t2 - t1)
while time_now() < deadline and self.running:
time_sleep( self.hostport, self.__class__.__name__, 1.0 )
if not self.running:
break | [
"def",
"run",
"(",
"self",
",",
"peer_table",
"=",
"None",
")",
":",
"self",
".",
"running",
"=",
"True",
"while",
"self",
".",
"running",
":",
"local_inv",
"=",
"atlas_get_zonefile_inventory",
"(",
")",
"t1",
"=",
"time_now",
"(",
")",
"self",
".",
"step",
"(",
"peer_table",
"=",
"peer_table",
",",
"local_inv",
"=",
"local_inv",
",",
"path",
"=",
"self",
".",
"atlasdb_path",
")",
"t2",
"=",
"time_now",
"(",
")",
"# don't go too fast ",
"if",
"t2",
"-",
"t1",
"<",
"PEER_HEALTH_NEIGHBOR_WORK_INTERVAL",
":",
"deadline",
"=",
"time_now",
"(",
")",
"+",
"PEER_HEALTH_NEIGHBOR_WORK_INTERVAL",
"-",
"(",
"t2",
"-",
"t1",
")",
"while",
"time_now",
"(",
")",
"<",
"deadline",
"and",
"self",
".",
"running",
":",
"time_sleep",
"(",
"self",
".",
"hostport",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"1.0",
")",
"if",
"not",
"self",
".",
"running",
":",
"break"
] | Loop forever, pinging someone every pass. | [
"Loop",
"forever",
"pinging",
"someone",
"every",
"pass",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L3213-L3231 |
230,468 | blockstack/blockstack-core | blockstack/lib/atlas.py | AtlasZonefileCrawler.set_zonefile_present | def set_zonefile_present(self, zfhash, block_height, con=None, path=None):
"""
Set a zonefile as present, and if it was previously absent, inform the storage listener
"""
was_present = atlasdb_set_zonefile_present( zfhash, True, con=con, path=path )
# tell anyone who cares that we got this zone file, if it was new
if not was_present and self.store_zonefile_cb:
log.debug('{} was new, so passing it along to zonefile storage watchers...'.format(zfhash))
self.store_zonefile_cb(zfhash, block_height)
else:
log.debug('{} was seen before, so not passing it along to zonefile storage watchers'.format(zfhash)) | python | def set_zonefile_present(self, zfhash, block_height, con=None, path=None):
"""
Set a zonefile as present, and if it was previously absent, inform the storage listener
"""
was_present = atlasdb_set_zonefile_present( zfhash, True, con=con, path=path )
# tell anyone who cares that we got this zone file, if it was new
if not was_present and self.store_zonefile_cb:
log.debug('{} was new, so passing it along to zonefile storage watchers...'.format(zfhash))
self.store_zonefile_cb(zfhash, block_height)
else:
log.debug('{} was seen before, so not passing it along to zonefile storage watchers'.format(zfhash)) | [
"def",
"set_zonefile_present",
"(",
"self",
",",
"zfhash",
",",
"block_height",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"was_present",
"=",
"atlasdb_set_zonefile_present",
"(",
"zfhash",
",",
"True",
",",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"# tell anyone who cares that we got this zone file, if it was new ",
"if",
"not",
"was_present",
"and",
"self",
".",
"store_zonefile_cb",
":",
"log",
".",
"debug",
"(",
"'{} was new, so passing it along to zonefile storage watchers...'",
".",
"format",
"(",
"zfhash",
")",
")",
"self",
".",
"store_zonefile_cb",
"(",
"zfhash",
",",
"block_height",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'{} was seen before, so not passing it along to zonefile storage watchers'",
".",
"format",
"(",
"zfhash",
")",
")"
] | Set a zonefile as present, and if it was previously absent, inform the storage listener | [
"Set",
"a",
"zonefile",
"as",
"present",
"and",
"if",
"it",
"was",
"previously",
"absent",
"inform",
"the",
"storage",
"listener"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L3257-L3268 |
230,469 | blockstack/blockstack-core | blockstack/lib/atlas.py | AtlasZonefileCrawler.find_zonefile_origins | def find_zonefile_origins( self, missing_zfinfo, peer_hostports ):
"""
Find out which peers can serve which zonefiles
"""
zonefile_origins = {} # map peer hostport to list of zonefile hashes
# which peers can serve each zonefile?
for zfhash in missing_zfinfo.keys():
for peer_hostport in peer_hostports:
if not zonefile_origins.has_key(peer_hostport):
zonefile_origins[peer_hostport] = []
if peer_hostport in missing_zfinfo[zfhash]['peers']:
zonefile_origins[peer_hostport].append( zfhash )
return zonefile_origins | python | def find_zonefile_origins( self, missing_zfinfo, peer_hostports ):
"""
Find out which peers can serve which zonefiles
"""
zonefile_origins = {} # map peer hostport to list of zonefile hashes
# which peers can serve each zonefile?
for zfhash in missing_zfinfo.keys():
for peer_hostport in peer_hostports:
if not zonefile_origins.has_key(peer_hostport):
zonefile_origins[peer_hostport] = []
if peer_hostport in missing_zfinfo[zfhash]['peers']:
zonefile_origins[peer_hostport].append( zfhash )
return zonefile_origins | [
"def",
"find_zonefile_origins",
"(",
"self",
",",
"missing_zfinfo",
",",
"peer_hostports",
")",
":",
"zonefile_origins",
"=",
"{",
"}",
"# map peer hostport to list of zonefile hashes",
"# which peers can serve each zonefile?",
"for",
"zfhash",
"in",
"missing_zfinfo",
".",
"keys",
"(",
")",
":",
"for",
"peer_hostport",
"in",
"peer_hostports",
":",
"if",
"not",
"zonefile_origins",
".",
"has_key",
"(",
"peer_hostport",
")",
":",
"zonefile_origins",
"[",
"peer_hostport",
"]",
"=",
"[",
"]",
"if",
"peer_hostport",
"in",
"missing_zfinfo",
"[",
"zfhash",
"]",
"[",
"'peers'",
"]",
":",
"zonefile_origins",
"[",
"peer_hostport",
"]",
".",
"append",
"(",
"zfhash",
")",
"return",
"zonefile_origins"
] | Find out which peers can serve which zonefiles | [
"Find",
"out",
"which",
"peers",
"can",
"serve",
"which",
"zonefiles"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L3316-L3331 |
230,470 | blockstack/blockstack-core | blockstack/lib/atlas.py | AtlasZonefilePusher.step | def step( self, peer_table=None, zonefile_queue=None, path=None ):
"""
Run one step of this algorithm.
Push the zonefile to all the peers that need it.
Return the number of peers we sent to
"""
if path is None:
path = self.atlasdb_path
if BLOCKSTACK_TEST:
log.debug("%s: %s step" % (self.hostport, self.__class__.__name__))
if self.push_timeout is None:
self.push_timeout = atlas_push_zonefiles_timeout()
zfinfo = atlas_zonefile_push_dequeue( zonefile_queue=zonefile_queue )
if zfinfo is None:
return 0
zfhash = zfinfo['zonefile_hash']
zfdata_txt = zfinfo['zonefile']
name = zfinfo['name']
txid = zfinfo['txid']
zfbits = atlasdb_get_zonefile_bits( zfhash, path=path )
if len(zfbits) == 0:
# not recognized
return 0
# it's a valid zonefile. store it.
rc = add_atlas_zonefile_data( str(zfdata_txt), self.zonefile_dir )
if not rc:
log.error("Failed to replicate zonefile %s to external storage" % zfhash)
peers = None
# see if we can send this somewhere
with AtlasPeerTableLocked(peer_table) as ptbl:
peers = atlas_zonefile_find_push_peers( zfhash, peer_table=ptbl, zonefile_bits=zfbits )
if len(peers) == 0:
# everyone has it
log.debug("%s: All peers have zonefile %s" % (self.hostport, zfhash))
return 0
# push it off
ret = 0
for peer in peers:
log.debug("%s: Push to %s" % (self.hostport, peer))
atlas_zonefile_push( self.hostport, peer, zfdata_txt, timeout=self.push_timeout )
ret += 1
return ret | python | def step( self, peer_table=None, zonefile_queue=None, path=None ):
"""
Run one step of this algorithm.
Push the zonefile to all the peers that need it.
Return the number of peers we sent to
"""
if path is None:
path = self.atlasdb_path
if BLOCKSTACK_TEST:
log.debug("%s: %s step" % (self.hostport, self.__class__.__name__))
if self.push_timeout is None:
self.push_timeout = atlas_push_zonefiles_timeout()
zfinfo = atlas_zonefile_push_dequeue( zonefile_queue=zonefile_queue )
if zfinfo is None:
return 0
zfhash = zfinfo['zonefile_hash']
zfdata_txt = zfinfo['zonefile']
name = zfinfo['name']
txid = zfinfo['txid']
zfbits = atlasdb_get_zonefile_bits( zfhash, path=path )
if len(zfbits) == 0:
# not recognized
return 0
# it's a valid zonefile. store it.
rc = add_atlas_zonefile_data( str(zfdata_txt), self.zonefile_dir )
if not rc:
log.error("Failed to replicate zonefile %s to external storage" % zfhash)
peers = None
# see if we can send this somewhere
with AtlasPeerTableLocked(peer_table) as ptbl:
peers = atlas_zonefile_find_push_peers( zfhash, peer_table=ptbl, zonefile_bits=zfbits )
if len(peers) == 0:
# everyone has it
log.debug("%s: All peers have zonefile %s" % (self.hostport, zfhash))
return 0
# push it off
ret = 0
for peer in peers:
log.debug("%s: Push to %s" % (self.hostport, peer))
atlas_zonefile_push( self.hostport, peer, zfdata_txt, timeout=self.push_timeout )
ret += 1
return ret | [
"def",
"step",
"(",
"self",
",",
"peer_table",
"=",
"None",
",",
"zonefile_queue",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"atlasdb_path",
"if",
"BLOCKSTACK_TEST",
":",
"log",
".",
"debug",
"(",
"\"%s: %s step\"",
"%",
"(",
"self",
".",
"hostport",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"if",
"self",
".",
"push_timeout",
"is",
"None",
":",
"self",
".",
"push_timeout",
"=",
"atlas_push_zonefiles_timeout",
"(",
")",
"zfinfo",
"=",
"atlas_zonefile_push_dequeue",
"(",
"zonefile_queue",
"=",
"zonefile_queue",
")",
"if",
"zfinfo",
"is",
"None",
":",
"return",
"0",
"zfhash",
"=",
"zfinfo",
"[",
"'zonefile_hash'",
"]",
"zfdata_txt",
"=",
"zfinfo",
"[",
"'zonefile'",
"]",
"name",
"=",
"zfinfo",
"[",
"'name'",
"]",
"txid",
"=",
"zfinfo",
"[",
"'txid'",
"]",
"zfbits",
"=",
"atlasdb_get_zonefile_bits",
"(",
"zfhash",
",",
"path",
"=",
"path",
")",
"if",
"len",
"(",
"zfbits",
")",
"==",
"0",
":",
"# not recognized ",
"return",
"0",
"# it's a valid zonefile. store it.",
"rc",
"=",
"add_atlas_zonefile_data",
"(",
"str",
"(",
"zfdata_txt",
")",
",",
"self",
".",
"zonefile_dir",
")",
"if",
"not",
"rc",
":",
"log",
".",
"error",
"(",
"\"Failed to replicate zonefile %s to external storage\"",
"%",
"zfhash",
")",
"peers",
"=",
"None",
"# see if we can send this somewhere",
"with",
"AtlasPeerTableLocked",
"(",
"peer_table",
")",
"as",
"ptbl",
":",
"peers",
"=",
"atlas_zonefile_find_push_peers",
"(",
"zfhash",
",",
"peer_table",
"=",
"ptbl",
",",
"zonefile_bits",
"=",
"zfbits",
")",
"if",
"len",
"(",
"peers",
")",
"==",
"0",
":",
"# everyone has it",
"log",
".",
"debug",
"(",
"\"%s: All peers have zonefile %s\"",
"%",
"(",
"self",
".",
"hostport",
",",
"zfhash",
")",
")",
"return",
"0",
"# push it off",
"ret",
"=",
"0",
"for",
"peer",
"in",
"peers",
":",
"log",
".",
"debug",
"(",
"\"%s: Push to %s\"",
"%",
"(",
"self",
".",
"hostport",
",",
"peer",
")",
")",
"atlas_zonefile_push",
"(",
"self",
".",
"hostport",
",",
"peer",
",",
"zfdata_txt",
",",
"timeout",
"=",
"self",
".",
"push_timeout",
")",
"ret",
"+=",
"1",
"return",
"ret"
] | Run one step of this algorithm.
Push the zonefile to all the peers that need it.
Return the number of peers we sent to | [
"Run",
"one",
"step",
"of",
"this",
"algorithm",
".",
"Push",
"the",
"zonefile",
"to",
"all",
"the",
"peers",
"that",
"need",
"it",
".",
"Return",
"the",
"number",
"of",
"peers",
"we",
"sent",
"to"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L3509-L3561 |
230,471 | blockstack/blockstack-core | blockstack/lib/queue.py | queuedb_create | def queuedb_create(path):
"""
Create a sqlite3 db at the given path.
Create all the tables and indexes we need.
Raises if the table already exists
"""
global QUEUE_SQL, ERROR_SQL
lines = [l + ";" for l in QUEUE_SQL.split(";")]
con = sqlite3.connect( path, isolation_level=None )
db_query_execute(con, 'pragma mmap_size=536870912', ())
for line in lines:
db_query_execute(con, line, ())
con.commit()
con.row_factory = queuedb_row_factory
return con | python | def queuedb_create(path):
"""
Create a sqlite3 db at the given path.
Create all the tables and indexes we need.
Raises if the table already exists
"""
global QUEUE_SQL, ERROR_SQL
lines = [l + ";" for l in QUEUE_SQL.split(";")]
con = sqlite3.connect( path, isolation_level=None )
db_query_execute(con, 'pragma mmap_size=536870912', ())
for line in lines:
db_query_execute(con, line, ())
con.commit()
con.row_factory = queuedb_row_factory
return con | [
"def",
"queuedb_create",
"(",
"path",
")",
":",
"global",
"QUEUE_SQL",
",",
"ERROR_SQL",
"lines",
"=",
"[",
"l",
"+",
"\";\"",
"for",
"l",
"in",
"QUEUE_SQL",
".",
"split",
"(",
"\";\"",
")",
"]",
"con",
"=",
"sqlite3",
".",
"connect",
"(",
"path",
",",
"isolation_level",
"=",
"None",
")",
"db_query_execute",
"(",
"con",
",",
"'pragma mmap_size=536870912'",
",",
"(",
")",
")",
"for",
"line",
"in",
"lines",
":",
"db_query_execute",
"(",
"con",
",",
"line",
",",
"(",
")",
")",
"con",
".",
"commit",
"(",
")",
"con",
".",
"row_factory",
"=",
"queuedb_row_factory",
"return",
"con"
] | Create a sqlite3 db at the given path.
Create all the tables and indexes we need.
Raises if the table already exists | [
"Create",
"a",
"sqlite3",
"db",
"at",
"the",
"given",
"path",
".",
"Create",
"all",
"the",
"tables",
"and",
"indexes",
"we",
"need",
".",
"Raises",
"if",
"the",
"table",
"already",
"exists"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/queue.py#L46-L63 |
230,472 | blockstack/blockstack-core | blockstack/lib/queue.py | queuedb_row_factory | def queuedb_row_factory(cursor, row):
"""
Dict row factory
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | python | def queuedb_row_factory(cursor, row):
"""
Dict row factory
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | [
"def",
"queuedb_row_factory",
"(",
"cursor",
",",
"row",
")",
":",
"d",
"=",
"{",
"}",
"for",
"idx",
",",
"col",
"in",
"enumerate",
"(",
"cursor",
".",
"description",
")",
":",
"d",
"[",
"col",
"[",
"0",
"]",
"]",
"=",
"row",
"[",
"idx",
"]",
"return",
"d"
] | Dict row factory | [
"Dict",
"row",
"factory"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/queue.py#L75-L83 |
230,473 | blockstack/blockstack-core | blockstack/lib/queue.py | queuedb_findall | def queuedb_findall(path, queue_id, name=None, offset=None, limit=None):
"""
Get all queued entries for a queue and a name.
If name is None, then find all queue entries
Return the rows on success (empty list if not found)
Raise on error
"""
sql = "SELECT * FROM queue WHERE queue_id = ? ORDER BY rowid ASC"
args = (queue_id,)
if name:
sql += ' AND name = ?'
args += (name,)
if limit:
sql += ' LIMIT ?'
args += (limit,)
if offset:
sql += ' OFFSET ?'
args += (offset,)
sql += ';'
db = queuedb_open(path)
if db is None:
raise Exception("Failed to open %s" % path)
cur = db.cursor()
rows = queuedb_query_execute(cur, sql, args)
count = 0
ret = []
for row in rows:
dat = {}
dat.update(row)
ret.append(dat)
db.close()
return ret | python | def queuedb_findall(path, queue_id, name=None, offset=None, limit=None):
"""
Get all queued entries for a queue and a name.
If name is None, then find all queue entries
Return the rows on success (empty list if not found)
Raise on error
"""
sql = "SELECT * FROM queue WHERE queue_id = ? ORDER BY rowid ASC"
args = (queue_id,)
if name:
sql += ' AND name = ?'
args += (name,)
if limit:
sql += ' LIMIT ?'
args += (limit,)
if offset:
sql += ' OFFSET ?'
args += (offset,)
sql += ';'
db = queuedb_open(path)
if db is None:
raise Exception("Failed to open %s" % path)
cur = db.cursor()
rows = queuedb_query_execute(cur, sql, args)
count = 0
ret = []
for row in rows:
dat = {}
dat.update(row)
ret.append(dat)
db.close()
return ret | [
"def",
"queuedb_findall",
"(",
"path",
",",
"queue_id",
",",
"name",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"sql",
"=",
"\"SELECT * FROM queue WHERE queue_id = ? ORDER BY rowid ASC\"",
"args",
"=",
"(",
"queue_id",
",",
")",
"if",
"name",
":",
"sql",
"+=",
"' AND name = ?'",
"args",
"+=",
"(",
"name",
",",
")",
"if",
"limit",
":",
"sql",
"+=",
"' LIMIT ?'",
"args",
"+=",
"(",
"limit",
",",
")",
"if",
"offset",
":",
"sql",
"+=",
"' OFFSET ?'",
"args",
"+=",
"(",
"offset",
",",
")",
"sql",
"+=",
"';'",
"db",
"=",
"queuedb_open",
"(",
"path",
")",
"if",
"db",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Failed to open %s\"",
"%",
"path",
")",
"cur",
"=",
"db",
".",
"cursor",
"(",
")",
"rows",
"=",
"queuedb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"count",
"=",
"0",
"ret",
"=",
"[",
"]",
"for",
"row",
"in",
"rows",
":",
"dat",
"=",
"{",
"}",
"dat",
".",
"update",
"(",
"row",
")",
"ret",
".",
"append",
"(",
"dat",
")",
"db",
".",
"close",
"(",
")",
"return",
"ret"
] | Get all queued entries for a queue and a name.
If name is None, then find all queue entries
Return the rows on success (empty list if not found)
Raise on error | [
"Get",
"all",
"queued",
"entries",
"for",
"a",
"queue",
"and",
"a",
"name",
".",
"If",
"name",
"is",
"None",
"then",
"find",
"all",
"queue",
"entries"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/queue.py#L103-L143 |
230,474 | blockstack/blockstack-core | blockstack/lib/queue.py | queuedb_append | def queuedb_append(path, queue_id, name, data):
"""
Append an element to the back of the queue.
Return True on success
Raise on error
"""
sql = "INSERT INTO queue VALUES (?,?,?);"
args = (name, queue_id, data)
db = queuedb_open(path)
if db is None:
raise Exception("Failed to open %s" % path)
cur = db.cursor()
res = queuedb_query_execute(cur, sql, args)
db.commit()
db.close()
return True | python | def queuedb_append(path, queue_id, name, data):
"""
Append an element to the back of the queue.
Return True on success
Raise on error
"""
sql = "INSERT INTO queue VALUES (?,?,?);"
args = (name, queue_id, data)
db = queuedb_open(path)
if db is None:
raise Exception("Failed to open %s" % path)
cur = db.cursor()
res = queuedb_query_execute(cur, sql, args)
db.commit()
db.close()
return True | [
"def",
"queuedb_append",
"(",
"path",
",",
"queue_id",
",",
"name",
",",
"data",
")",
":",
"sql",
"=",
"\"INSERT INTO queue VALUES (?,?,?);\"",
"args",
"=",
"(",
"name",
",",
"queue_id",
",",
"data",
")",
"db",
"=",
"queuedb_open",
"(",
"path",
")",
"if",
"db",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Failed to open %s\"",
"%",
"path",
")",
"cur",
"=",
"db",
".",
"cursor",
"(",
")",
"res",
"=",
"queuedb_query_execute",
"(",
"cur",
",",
"sql",
",",
"args",
")",
"db",
".",
"commit",
"(",
")",
"db",
".",
"close",
"(",
")",
"return",
"True"
] | Append an element to the back of the queue.
Return True on success
Raise on error | [
"Append",
"an",
"element",
"to",
"the",
"back",
"of",
"the",
"queue",
".",
"Return",
"True",
"on",
"success",
"Raise",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/queue.py#L146-L164 |
230,475 | blockstack/blockstack-core | blockstack/lib/queue.py | queuedb_remove | def queuedb_remove(path, entry, cur=None):
"""
Remove an element from a queue.
Return True on success
Raise on error
"""
sql = "DELETE FROM queue WHERE queue_id = ? AND name = ?;"
args = (entry['queue_id'], entry['name'])
cursor = None
if cur:
cursor = cur
else:
db = queuedb_open(path)
if db is None:
raise Exception("Failed to open %s" % path)
cursor = db.cursor()
res = queuedb_query_execute(cursor, sql, args)
if cur is None:
db.commit()
db.close()
return True | python | def queuedb_remove(path, entry, cur=None):
"""
Remove an element from a queue.
Return True on success
Raise on error
"""
sql = "DELETE FROM queue WHERE queue_id = ? AND name = ?;"
args = (entry['queue_id'], entry['name'])
cursor = None
if cur:
cursor = cur
else:
db = queuedb_open(path)
if db is None:
raise Exception("Failed to open %s" % path)
cursor = db.cursor()
res = queuedb_query_execute(cursor, sql, args)
if cur is None:
db.commit()
db.close()
return True | [
"def",
"queuedb_remove",
"(",
"path",
",",
"entry",
",",
"cur",
"=",
"None",
")",
":",
"sql",
"=",
"\"DELETE FROM queue WHERE queue_id = ? AND name = ?;\"",
"args",
"=",
"(",
"entry",
"[",
"'queue_id'",
"]",
",",
"entry",
"[",
"'name'",
"]",
")",
"cursor",
"=",
"None",
"if",
"cur",
":",
"cursor",
"=",
"cur",
"else",
":",
"db",
"=",
"queuedb_open",
"(",
"path",
")",
"if",
"db",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Failed to open %s\"",
"%",
"path",
")",
"cursor",
"=",
"db",
".",
"cursor",
"(",
")",
"res",
"=",
"queuedb_query_execute",
"(",
"cursor",
",",
"sql",
",",
"args",
")",
"if",
"cur",
"is",
"None",
":",
"db",
".",
"commit",
"(",
")",
"db",
".",
"close",
"(",
")",
"return",
"True"
] | Remove an element from a queue.
Return True on success
Raise on error | [
"Remove",
"an",
"element",
"from",
"a",
"queue",
".",
"Return",
"True",
"on",
"success",
"Raise",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/queue.py#L167-L192 |
230,476 | blockstack/blockstack-core | blockstack/lib/queue.py | queuedb_removeall | def queuedb_removeall(path, entries):
"""
Remove all entries from a queue
"""
db = queuedb_open(path)
if db is None:
raise Exception("Failed to open %s" % path)
cursor = db.cursor()
queuedb_query_execute(cursor, 'BEGIN', ())
for entry in entries:
queuedb_remove(path, entry, cur=cursor)
queuedb_query_execute(cursor, 'END', ())
db.commit()
db.close()
return True | python | def queuedb_removeall(path, entries):
"""
Remove all entries from a queue
"""
db = queuedb_open(path)
if db is None:
raise Exception("Failed to open %s" % path)
cursor = db.cursor()
queuedb_query_execute(cursor, 'BEGIN', ())
for entry in entries:
queuedb_remove(path, entry, cur=cursor)
queuedb_query_execute(cursor, 'END', ())
db.commit()
db.close()
return True | [
"def",
"queuedb_removeall",
"(",
"path",
",",
"entries",
")",
":",
"db",
"=",
"queuedb_open",
"(",
"path",
")",
"if",
"db",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Failed to open %s\"",
"%",
"path",
")",
"cursor",
"=",
"db",
".",
"cursor",
"(",
")",
"queuedb_query_execute",
"(",
"cursor",
",",
"'BEGIN'",
",",
"(",
")",
")",
"for",
"entry",
"in",
"entries",
":",
"queuedb_remove",
"(",
"path",
",",
"entry",
",",
"cur",
"=",
"cursor",
")",
"queuedb_query_execute",
"(",
"cursor",
",",
"'END'",
",",
"(",
")",
")",
"db",
".",
"commit",
"(",
")",
"db",
".",
"close",
"(",
")",
"return",
"True"
] | Remove all entries from a queue | [
"Remove",
"all",
"entries",
"from",
"a",
"queue"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/queue.py#L195-L213 |
230,477 | blockstack/blockstack-core | blockstack/lib/operations/register.py | check_payment_in_stacks | def check_payment_in_stacks(state_engine, nameop, state_op_type, fee_block_id):
"""
Verify that if tokens were paid for a name priced in BTC, that enough were paid.
Does not check account balances or namespace types; it only inspects the transaction data.
Returns {'status': True, 'tokens_paid': ..., 'token_units': ...} on success
Returns {'status': False} on error
"""
name = nameop['name']
namespace_id = get_namespace_from_name(name)
name_without_namespace = get_name_from_fq_name(name)
namespace = state_engine.get_namespace( namespace_id )
stacks_payment_info = get_stacks_payment(state_engine, nameop, state_op_type)
if stacks_payment_info['status']:
# got a stacks payment! check price and make sure we paid the right amount
tokens_paid = stacks_payment_info['tokens_paid']
token_units = stacks_payment_info['token_units']
log.debug('Transaction pays {} units of {} for {}, even though its namespace was priced in BTC'.format(tokens_paid, token_units, name))
stacks_price = price_name_stacks(name_without_namespace, namespace, fee_block_id) # price in Stacks, but following the BTC-given price curve
res = check_token_payment(name, stacks_price, stacks_payment_info)
if res['status']:
# success
return {'status': True, 'tokens_paid': tokens_paid, 'token_units': token_units}
return {'status': False} | python | def check_payment_in_stacks(state_engine, nameop, state_op_type, fee_block_id):
"""
Verify that if tokens were paid for a name priced in BTC, that enough were paid.
Does not check account balances or namespace types; it only inspects the transaction data.
Returns {'status': True, 'tokens_paid': ..., 'token_units': ...} on success
Returns {'status': False} on error
"""
name = nameop['name']
namespace_id = get_namespace_from_name(name)
name_without_namespace = get_name_from_fq_name(name)
namespace = state_engine.get_namespace( namespace_id )
stacks_payment_info = get_stacks_payment(state_engine, nameop, state_op_type)
if stacks_payment_info['status']:
# got a stacks payment! check price and make sure we paid the right amount
tokens_paid = stacks_payment_info['tokens_paid']
token_units = stacks_payment_info['token_units']
log.debug('Transaction pays {} units of {} for {}, even though its namespace was priced in BTC'.format(tokens_paid, token_units, name))
stacks_price = price_name_stacks(name_without_namespace, namespace, fee_block_id) # price in Stacks, but following the BTC-given price curve
res = check_token_payment(name, stacks_price, stacks_payment_info)
if res['status']:
# success
return {'status': True, 'tokens_paid': tokens_paid, 'token_units': token_units}
return {'status': False} | [
"def",
"check_payment_in_stacks",
"(",
"state_engine",
",",
"nameop",
",",
"state_op_type",
",",
"fee_block_id",
")",
":",
"name",
"=",
"nameop",
"[",
"'name'",
"]",
"namespace_id",
"=",
"get_namespace_from_name",
"(",
"name",
")",
"name_without_namespace",
"=",
"get_name_from_fq_name",
"(",
"name",
")",
"namespace",
"=",
"state_engine",
".",
"get_namespace",
"(",
"namespace_id",
")",
"stacks_payment_info",
"=",
"get_stacks_payment",
"(",
"state_engine",
",",
"nameop",
",",
"state_op_type",
")",
"if",
"stacks_payment_info",
"[",
"'status'",
"]",
":",
"# got a stacks payment! check price and make sure we paid the right amount",
"tokens_paid",
"=",
"stacks_payment_info",
"[",
"'tokens_paid'",
"]",
"token_units",
"=",
"stacks_payment_info",
"[",
"'token_units'",
"]",
"log",
".",
"debug",
"(",
"'Transaction pays {} units of {} for {}, even though its namespace was priced in BTC'",
".",
"format",
"(",
"tokens_paid",
",",
"token_units",
",",
"name",
")",
")",
"stacks_price",
"=",
"price_name_stacks",
"(",
"name_without_namespace",
",",
"namespace",
",",
"fee_block_id",
")",
"# price in Stacks, but following the BTC-given price curve",
"res",
"=",
"check_token_payment",
"(",
"name",
",",
"stacks_price",
",",
"stacks_payment_info",
")",
"if",
"res",
"[",
"'status'",
"]",
":",
"# success",
"return",
"{",
"'status'",
":",
"True",
",",
"'tokens_paid'",
":",
"tokens_paid",
",",
"'token_units'",
":",
"token_units",
"}",
"return",
"{",
"'status'",
":",
"False",
"}"
] | Verify that if tokens were paid for a name priced in BTC, that enough were paid.
Does not check account balances or namespace types; it only inspects the transaction data.
Returns {'status': True, 'tokens_paid': ..., 'token_units': ...} on success
Returns {'status': False} on error | [
"Verify",
"that",
"if",
"tokens",
"were",
"paid",
"for",
"a",
"name",
"priced",
"in",
"BTC",
"that",
"enough",
"were",
"paid",
".",
"Does",
"not",
"check",
"account",
"balances",
"or",
"namespace",
"types",
";",
"it",
"only",
"inspects",
"the",
"transaction",
"data",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/register.py#L201-L228 |
230,478 | blockstack/blockstack-core | blockstack/lib/operations/register.py | check_payment | def check_payment(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id):
"""
Verify that the right payment was made, in the right cryptocurrency units.
Does not check any accounts or modify the nameop in any way; it only checks that the name was paid for by the transaction.
NOTE: if state_op_type is NAME_REGISTRATION, you will need to have called state_create_put_preorder() before calling this method!
Returns {'status': True, 'tokens_paid': tokens_paid, 'token_units': ...} if the payment information is correct.
Returns {'status': False} if not
"""
assert state_op_type in ['NAME_REGISTRATION', 'NAME_RENEWAL'], 'Invalid op type {}'.format(state_op_type)
assert name_fee is not None
assert isinstance(name_fee, (int,long))
name = nameop['name']
namespace_id = get_namespace_from_name(name)
namespace = state_engine.get_namespace( namespace_id )
res = None
log.debug('{} is a version-0x{} namespace'.format(namespace['namespace_id'], namespace['version']))
# check name fee, depending on which version.
if namespace['version'] == NAMESPACE_VERSION_PAY_TO_BURN:
res = check_payment_v1(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id)
elif namespace['version'] == NAMESPACE_VERSION_PAY_TO_CREATOR:
res = check_payment_v2(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id)
elif namespace['version'] == NAMESPACE_VERSION_PAY_WITH_STACKS:
res = check_payment_v3(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id)
else:
# unrecognized namespace rules
log.warning("Namespace {} has version bits 0x{:x}, which has unknown registration rules".format(namespace['namespace_id'], namespace['version']))
return {'status': False}
if not res['status']:
return res
tokens_paid = res['tokens_paid']
token_units = res['token_units']
return {'status': True, 'tokens_paid': tokens_paid, 'token_units': token_units} | python | def check_payment(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id):
"""
Verify that the right payment was made, in the right cryptocurrency units.
Does not check any accounts or modify the nameop in any way; it only checks that the name was paid for by the transaction.
NOTE: if state_op_type is NAME_REGISTRATION, you will need to have called state_create_put_preorder() before calling this method!
Returns {'status': True, 'tokens_paid': tokens_paid, 'token_units': ...} if the payment information is correct.
Returns {'status': False} if not
"""
assert state_op_type in ['NAME_REGISTRATION', 'NAME_RENEWAL'], 'Invalid op type {}'.format(state_op_type)
assert name_fee is not None
assert isinstance(name_fee, (int,long))
name = nameop['name']
namespace_id = get_namespace_from_name(name)
namespace = state_engine.get_namespace( namespace_id )
res = None
log.debug('{} is a version-0x{} namespace'.format(namespace['namespace_id'], namespace['version']))
# check name fee, depending on which version.
if namespace['version'] == NAMESPACE_VERSION_PAY_TO_BURN:
res = check_payment_v1(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id)
elif namespace['version'] == NAMESPACE_VERSION_PAY_TO_CREATOR:
res = check_payment_v2(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id)
elif namespace['version'] == NAMESPACE_VERSION_PAY_WITH_STACKS:
res = check_payment_v3(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id)
else:
# unrecognized namespace rules
log.warning("Namespace {} has version bits 0x{:x}, which has unknown registration rules".format(namespace['namespace_id'], namespace['version']))
return {'status': False}
if not res['status']:
return res
tokens_paid = res['tokens_paid']
token_units = res['token_units']
return {'status': True, 'tokens_paid': tokens_paid, 'token_units': token_units} | [
"def",
"check_payment",
"(",
"state_engine",
",",
"state_op_type",
",",
"nameop",
",",
"fee_block_id",
",",
"token_address",
",",
"burn_address",
",",
"name_fee",
",",
"block_id",
")",
":",
"assert",
"state_op_type",
"in",
"[",
"'NAME_REGISTRATION'",
",",
"'NAME_RENEWAL'",
"]",
",",
"'Invalid op type {}'",
".",
"format",
"(",
"state_op_type",
")",
"assert",
"name_fee",
"is",
"not",
"None",
"assert",
"isinstance",
"(",
"name_fee",
",",
"(",
"int",
",",
"long",
")",
")",
"name",
"=",
"nameop",
"[",
"'name'",
"]",
"namespace_id",
"=",
"get_namespace_from_name",
"(",
"name",
")",
"namespace",
"=",
"state_engine",
".",
"get_namespace",
"(",
"namespace_id",
")",
"res",
"=",
"None",
"log",
".",
"debug",
"(",
"'{} is a version-0x{} namespace'",
".",
"format",
"(",
"namespace",
"[",
"'namespace_id'",
"]",
",",
"namespace",
"[",
"'version'",
"]",
")",
")",
"# check name fee, depending on which version.",
"if",
"namespace",
"[",
"'version'",
"]",
"==",
"NAMESPACE_VERSION_PAY_TO_BURN",
":",
"res",
"=",
"check_payment_v1",
"(",
"state_engine",
",",
"state_op_type",
",",
"nameop",
",",
"fee_block_id",
",",
"token_address",
",",
"burn_address",
",",
"name_fee",
",",
"block_id",
")",
"elif",
"namespace",
"[",
"'version'",
"]",
"==",
"NAMESPACE_VERSION_PAY_TO_CREATOR",
":",
"res",
"=",
"check_payment_v2",
"(",
"state_engine",
",",
"state_op_type",
",",
"nameop",
",",
"fee_block_id",
",",
"token_address",
",",
"burn_address",
",",
"name_fee",
",",
"block_id",
")",
"elif",
"namespace",
"[",
"'version'",
"]",
"==",
"NAMESPACE_VERSION_PAY_WITH_STACKS",
":",
"res",
"=",
"check_payment_v3",
"(",
"state_engine",
",",
"state_op_type",
",",
"nameop",
",",
"fee_block_id",
",",
"token_address",
",",
"burn_address",
",",
"name_fee",
",",
"block_id",
")",
"else",
":",
"# unrecognized namespace rules",
"log",
".",
"warning",
"(",
"\"Namespace {} has version bits 0x{:x}, which has unknown registration rules\"",
".",
"format",
"(",
"namespace",
"[",
"'namespace_id'",
"]",
",",
"namespace",
"[",
"'version'",
"]",
")",
")",
"return",
"{",
"'status'",
":",
"False",
"}",
"if",
"not",
"res",
"[",
"'status'",
"]",
":",
"return",
"res",
"tokens_paid",
"=",
"res",
"[",
"'tokens_paid'",
"]",
"token_units",
"=",
"res",
"[",
"'token_units'",
"]",
"return",
"{",
"'status'",
":",
"True",
",",
"'tokens_paid'",
":",
"tokens_paid",
",",
"'token_units'",
":",
"token_units",
"}"
] | Verify that the right payment was made, in the right cryptocurrency units.
Does not check any accounts or modify the nameop in any way; it only checks that the name was paid for by the transaction.
NOTE: if state_op_type is NAME_REGISTRATION, you will need to have called state_create_put_preorder() before calling this method!
Returns {'status': True, 'tokens_paid': tokens_paid, 'token_units': ...} if the payment information is correct.
Returns {'status': False} if not | [
"Verify",
"that",
"the",
"right",
"payment",
"was",
"made",
"in",
"the",
"right",
"cryptocurrency",
"units",
".",
"Does",
"not",
"check",
"any",
"accounts",
"or",
"modify",
"the",
"nameop",
"in",
"any",
"way",
";",
"it",
"only",
"checks",
"that",
"the",
"name",
"was",
"paid",
"for",
"by",
"the",
"transaction",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/register.py#L405-L448 |
230,479 | blockstack/blockstack-core | blockstack/lib/operations/namespacepreorder.py | check | def check( state_engine, nameop, block_id, checked_ops ):
"""
Given a NAMESPACE_PREORDER nameop, see if we can preorder it.
It must be unqiue.
Return True if accepted.
Return False if not.
"""
namespace_id_hash = nameop['preorder_hash']
consensus_hash = nameop['consensus_hash']
token_fee = nameop['token_fee']
# cannot be preordered already
if not state_engine.is_new_namespace_preorder( namespace_id_hash ):
log.warning("Namespace preorder '%s' already in use" % namespace_id_hash)
return False
# has to have a reasonable consensus hash
if not state_engine.is_consensus_hash_valid( block_id, consensus_hash ):
valid_consensus_hashes = state_engine.get_valid_consensus_hashes( block_id )
log.warning("Invalid consensus hash '%s': expected any of %s" % (consensus_hash, ",".join( valid_consensus_hashes )) )
return False
# has to have paid a fee
if not 'op_fee' in nameop:
log.warning("Missing namespace preorder fee")
return False
# paid to the right burn address
if nameop['burn_address'] != BLOCKSTACK_BURN_ADDRESS:
log.warning("Invalid burn address: expected {}, got {}".format(BLOCKSTACK_BURN_ADDRESS, nameop['burn_address']))
return False
# token burn fee must be present, if we're in the right epoch for it
epoch_features = get_epoch_features(block_id)
if EPOCH_FEATURE_STACKS_BUY_NAMESPACES in epoch_features:
# must pay in STACKs
if 'token_fee' not in nameop:
log.warning("Missing token fee")
return False
token_fee = nameop['token_fee']
token_address = nameop['address']
token_type = TOKEN_TYPE_STACKS
# was a token fee paid?
if token_fee is None:
log.warning("No tokens paid by this NAMESPACE_PREORDER")
return False
# does this account have enough balance?
account_info = state_engine.get_account(token_address, token_type)
if account_info is None:
log.warning("No account for {} ({})".format(token_address, token_type))
return False
account_balance = state_engine.get_account_balance(account_info)
assert isinstance(account_balance, (int,long)), 'BUG: account_balance of {} is {} (type {})'.format(token_address, account_balance, type(account_balance))
assert isinstance(token_fee, (int,long)), 'BUG: token_fee is {} (type {})'.format(token_fee, type(token_fee))
if account_balance < token_fee:
# can't afford
log.warning("Account {} has balance {} {}, but needs to pay {} {}".format(token_address, account_balance, token_type, token_fee, token_type))
return False
# debit this account when we commit
state_preorder_put_account_payment_info(nameop, token_address, token_type, token_fee)
# NOTE: must be a string, to avoid overflow
nameop['token_fee'] = '{}'.format(token_fee)
nameop['token_units'] = TOKEN_TYPE_STACKS
else:
# must pay in BTC
# not paying in tokens, but say so!
state_preorder_put_account_payment_info(nameop, None, None, None)
nameop['token_fee'] = '0'
nameop['token_units'] = 'BTC'
return True | python | def check( state_engine, nameop, block_id, checked_ops ):
"""
Given a NAMESPACE_PREORDER nameop, see if we can preorder it.
It must be unqiue.
Return True if accepted.
Return False if not.
"""
namespace_id_hash = nameop['preorder_hash']
consensus_hash = nameop['consensus_hash']
token_fee = nameop['token_fee']
# cannot be preordered already
if not state_engine.is_new_namespace_preorder( namespace_id_hash ):
log.warning("Namespace preorder '%s' already in use" % namespace_id_hash)
return False
# has to have a reasonable consensus hash
if not state_engine.is_consensus_hash_valid( block_id, consensus_hash ):
valid_consensus_hashes = state_engine.get_valid_consensus_hashes( block_id )
log.warning("Invalid consensus hash '%s': expected any of %s" % (consensus_hash, ",".join( valid_consensus_hashes )) )
return False
# has to have paid a fee
if not 'op_fee' in nameop:
log.warning("Missing namespace preorder fee")
return False
# paid to the right burn address
if nameop['burn_address'] != BLOCKSTACK_BURN_ADDRESS:
log.warning("Invalid burn address: expected {}, got {}".format(BLOCKSTACK_BURN_ADDRESS, nameop['burn_address']))
return False
# token burn fee must be present, if we're in the right epoch for it
epoch_features = get_epoch_features(block_id)
if EPOCH_FEATURE_STACKS_BUY_NAMESPACES in epoch_features:
# must pay in STACKs
if 'token_fee' not in nameop:
log.warning("Missing token fee")
return False
token_fee = nameop['token_fee']
token_address = nameop['address']
token_type = TOKEN_TYPE_STACKS
# was a token fee paid?
if token_fee is None:
log.warning("No tokens paid by this NAMESPACE_PREORDER")
return False
# does this account have enough balance?
account_info = state_engine.get_account(token_address, token_type)
if account_info is None:
log.warning("No account for {} ({})".format(token_address, token_type))
return False
account_balance = state_engine.get_account_balance(account_info)
assert isinstance(account_balance, (int,long)), 'BUG: account_balance of {} is {} (type {})'.format(token_address, account_balance, type(account_balance))
assert isinstance(token_fee, (int,long)), 'BUG: token_fee is {} (type {})'.format(token_fee, type(token_fee))
if account_balance < token_fee:
# can't afford
log.warning("Account {} has balance {} {}, but needs to pay {} {}".format(token_address, account_balance, token_type, token_fee, token_type))
return False
# debit this account when we commit
state_preorder_put_account_payment_info(nameop, token_address, token_type, token_fee)
# NOTE: must be a string, to avoid overflow
nameop['token_fee'] = '{}'.format(token_fee)
nameop['token_units'] = TOKEN_TYPE_STACKS
else:
# must pay in BTC
# not paying in tokens, but say so!
state_preorder_put_account_payment_info(nameop, None, None, None)
nameop['token_fee'] = '0'
nameop['token_units'] = 'BTC'
return True | [
"def",
"check",
"(",
"state_engine",
",",
"nameop",
",",
"block_id",
",",
"checked_ops",
")",
":",
"namespace_id_hash",
"=",
"nameop",
"[",
"'preorder_hash'",
"]",
"consensus_hash",
"=",
"nameop",
"[",
"'consensus_hash'",
"]",
"token_fee",
"=",
"nameop",
"[",
"'token_fee'",
"]",
"# cannot be preordered already",
"if",
"not",
"state_engine",
".",
"is_new_namespace_preorder",
"(",
"namespace_id_hash",
")",
":",
"log",
".",
"warning",
"(",
"\"Namespace preorder '%s' already in use\"",
"%",
"namespace_id_hash",
")",
"return",
"False",
"# has to have a reasonable consensus hash",
"if",
"not",
"state_engine",
".",
"is_consensus_hash_valid",
"(",
"block_id",
",",
"consensus_hash",
")",
":",
"valid_consensus_hashes",
"=",
"state_engine",
".",
"get_valid_consensus_hashes",
"(",
"block_id",
")",
"log",
".",
"warning",
"(",
"\"Invalid consensus hash '%s': expected any of %s\"",
"%",
"(",
"consensus_hash",
",",
"\",\"",
".",
"join",
"(",
"valid_consensus_hashes",
")",
")",
")",
"return",
"False",
"# has to have paid a fee",
"if",
"not",
"'op_fee'",
"in",
"nameop",
":",
"log",
".",
"warning",
"(",
"\"Missing namespace preorder fee\"",
")",
"return",
"False",
"# paid to the right burn address",
"if",
"nameop",
"[",
"'burn_address'",
"]",
"!=",
"BLOCKSTACK_BURN_ADDRESS",
":",
"log",
".",
"warning",
"(",
"\"Invalid burn address: expected {}, got {}\"",
".",
"format",
"(",
"BLOCKSTACK_BURN_ADDRESS",
",",
"nameop",
"[",
"'burn_address'",
"]",
")",
")",
"return",
"False",
"# token burn fee must be present, if we're in the right epoch for it",
"epoch_features",
"=",
"get_epoch_features",
"(",
"block_id",
")",
"if",
"EPOCH_FEATURE_STACKS_BUY_NAMESPACES",
"in",
"epoch_features",
":",
"# must pay in STACKs",
"if",
"'token_fee'",
"not",
"in",
"nameop",
":",
"log",
".",
"warning",
"(",
"\"Missing token fee\"",
")",
"return",
"False",
"token_fee",
"=",
"nameop",
"[",
"'token_fee'",
"]",
"token_address",
"=",
"nameop",
"[",
"'address'",
"]",
"token_type",
"=",
"TOKEN_TYPE_STACKS",
"# was a token fee paid?",
"if",
"token_fee",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"No tokens paid by this NAMESPACE_PREORDER\"",
")",
"return",
"False",
"# does this account have enough balance?",
"account_info",
"=",
"state_engine",
".",
"get_account",
"(",
"token_address",
",",
"token_type",
")",
"if",
"account_info",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"No account for {} ({})\"",
".",
"format",
"(",
"token_address",
",",
"token_type",
")",
")",
"return",
"False",
"account_balance",
"=",
"state_engine",
".",
"get_account_balance",
"(",
"account_info",
")",
"assert",
"isinstance",
"(",
"account_balance",
",",
"(",
"int",
",",
"long",
")",
")",
",",
"'BUG: account_balance of {} is {} (type {})'",
".",
"format",
"(",
"token_address",
",",
"account_balance",
",",
"type",
"(",
"account_balance",
")",
")",
"assert",
"isinstance",
"(",
"token_fee",
",",
"(",
"int",
",",
"long",
")",
")",
",",
"'BUG: token_fee is {} (type {})'",
".",
"format",
"(",
"token_fee",
",",
"type",
"(",
"token_fee",
")",
")",
"if",
"account_balance",
"<",
"token_fee",
":",
"# can't afford ",
"log",
".",
"warning",
"(",
"\"Account {} has balance {} {}, but needs to pay {} {}\"",
".",
"format",
"(",
"token_address",
",",
"account_balance",
",",
"token_type",
",",
"token_fee",
",",
"token_type",
")",
")",
"return",
"False",
"# debit this account when we commit",
"state_preorder_put_account_payment_info",
"(",
"nameop",
",",
"token_address",
",",
"token_type",
",",
"token_fee",
")",
"# NOTE: must be a string, to avoid overflow",
"nameop",
"[",
"'token_fee'",
"]",
"=",
"'{}'",
".",
"format",
"(",
"token_fee",
")",
"nameop",
"[",
"'token_units'",
"]",
"=",
"TOKEN_TYPE_STACKS",
"else",
":",
"# must pay in BTC",
"# not paying in tokens, but say so!",
"state_preorder_put_account_payment_info",
"(",
"nameop",
",",
"None",
",",
"None",
",",
"None",
")",
"nameop",
"[",
"'token_fee'",
"]",
"=",
"'0'",
"nameop",
"[",
"'token_units'",
"]",
"=",
"'BTC'",
"return",
"True"
] | Given a NAMESPACE_PREORDER nameop, see if we can preorder it.
It must be unqiue.
Return True if accepted.
Return False if not. | [
"Given",
"a",
"NAMESPACE_PREORDER",
"nameop",
"see",
"if",
"we",
"can",
"preorder",
"it",
".",
"It",
"must",
"be",
"unqiue",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/namespacepreorder.py#L53-L134 |
230,480 | blockstack/blockstack-core | blockstack/lib/fast_sync.py | snapshot_peek_number | def snapshot_peek_number( fd, off ):
"""
Read the last 8 bytes of fd
and interpret it as an int.
"""
# read number of 8 bytes
fd.seek( off - 8, os.SEEK_SET )
value_hex = fd.read(8)
if len(value_hex) != 8:
return None
try:
value = int(value_hex, 16)
except ValueError:
return None
return value | python | def snapshot_peek_number( fd, off ):
"""
Read the last 8 bytes of fd
and interpret it as an int.
"""
# read number of 8 bytes
fd.seek( off - 8, os.SEEK_SET )
value_hex = fd.read(8)
if len(value_hex) != 8:
return None
try:
value = int(value_hex, 16)
except ValueError:
return None
return value | [
"def",
"snapshot_peek_number",
"(",
"fd",
",",
"off",
")",
":",
"# read number of 8 bytes ",
"fd",
".",
"seek",
"(",
"off",
"-",
"8",
",",
"os",
".",
"SEEK_SET",
")",
"value_hex",
"=",
"fd",
".",
"read",
"(",
"8",
")",
"if",
"len",
"(",
"value_hex",
")",
"!=",
"8",
":",
"return",
"None",
"try",
":",
"value",
"=",
"int",
"(",
"value_hex",
",",
"16",
")",
"except",
"ValueError",
":",
"return",
"None",
"return",
"value"
] | Read the last 8 bytes of fd
and interpret it as an int. | [
"Read",
"the",
"last",
"8",
"bytes",
"of",
"fd",
"and",
"interpret",
"it",
"as",
"an",
"int",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/fast_sync.py#L52-L67 |
230,481 | blockstack/blockstack-core | blockstack/lib/fast_sync.py | get_file_hash | def get_file_hash( fd, hashfunc, fd_len=None ):
"""
Get the hex-encoded hash of the fd's data
"""
h = hashfunc()
fd.seek(0, os.SEEK_SET)
count = 0
while True:
buf = fd.read(65536)
if len(buf) == 0:
break
if fd_len is not None:
if count + len(buf) > fd_len:
buf = buf[:fd_len - count]
h.update(buf)
count += len(buf)
hashed = h.hexdigest()
return hashed | python | def get_file_hash( fd, hashfunc, fd_len=None ):
"""
Get the hex-encoded hash of the fd's data
"""
h = hashfunc()
fd.seek(0, os.SEEK_SET)
count = 0
while True:
buf = fd.read(65536)
if len(buf) == 0:
break
if fd_len is not None:
if count + len(buf) > fd_len:
buf = buf[:fd_len - count]
h.update(buf)
count += len(buf)
hashed = h.hexdigest()
return hashed | [
"def",
"get_file_hash",
"(",
"fd",
",",
"hashfunc",
",",
"fd_len",
"=",
"None",
")",
":",
"h",
"=",
"hashfunc",
"(",
")",
"fd",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"count",
"=",
"0",
"while",
"True",
":",
"buf",
"=",
"fd",
".",
"read",
"(",
"65536",
")",
"if",
"len",
"(",
"buf",
")",
"==",
"0",
":",
"break",
"if",
"fd_len",
"is",
"not",
"None",
":",
"if",
"count",
"+",
"len",
"(",
"buf",
")",
">",
"fd_len",
":",
"buf",
"=",
"buf",
"[",
":",
"fd_len",
"-",
"count",
"]",
"h",
".",
"update",
"(",
"buf",
")",
"count",
"+=",
"len",
"(",
"buf",
")",
"hashed",
"=",
"h",
".",
"hexdigest",
"(",
")",
"return",
"hashed"
] | Get the hex-encoded hash of the fd's data | [
"Get",
"the",
"hex",
"-",
"encoded",
"hash",
"of",
"the",
"fd",
"s",
"data"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/fast_sync.py#L89-L111 |
230,482 | blockstack/blockstack-core | blockstack/lib/fast_sync.py | fast_sync_sign_snapshot | def fast_sync_sign_snapshot( snapshot_path, private_key, first=False ):
"""
Append a signature to the end of a snapshot path
with the given private key.
If first is True, then don't expect the signature trailer.
Return True on success
Return False on error
"""
if not os.path.exists(snapshot_path):
log.error("No such file or directory: {}".format(snapshot_path))
return False
file_size = 0
payload_size = 0
write_offset = 0
try:
sb = os.stat(snapshot_path)
file_size = sb.st_size
assert file_size > 8
except Exception as e:
log.exception(e)
return False
num_sigs = 0
snapshot_hash = None
with open(snapshot_path, 'r+') as f:
if not first:
info = fast_sync_inspect(f)
if 'error' in info:
log.error("Failed to inspect {}: {}".format(snapshot_path, info['error']))
return False
num_sigs = len(info['signatures'])
write_offset = info['sig_append_offset']
payload_size = info['payload_size']
else:
# no one has signed yet.
write_offset = file_size
num_sigs = 0
payload_size = file_size
# hash the file and sign the (bin-encoded) hash
privkey_hex = keylib.ECPrivateKey(private_key).to_hex()
hash_hex = get_file_hash( f, hashlib.sha256, fd_len=payload_size )
sigb64 = sign_digest( hash_hex, privkey_hex, hashfunc=hashlib.sha256 )
if BLOCKSTACK_TEST:
log.debug("Signed {} with {} to make {}".format(hash_hex, keylib.ECPrivateKey(private_key).public_key().to_hex(), sigb64))
# append
f.seek(write_offset, os.SEEK_SET)
f.write(sigb64)
f.write('{:08x}'.format(len(sigb64)))
# append number of signatures
num_sigs += 1
f.write('{:08x}'.format(num_sigs))
f.flush()
os.fsync(f.fileno())
return True | python | def fast_sync_sign_snapshot( snapshot_path, private_key, first=False ):
"""
Append a signature to the end of a snapshot path
with the given private key.
If first is True, then don't expect the signature trailer.
Return True on success
Return False on error
"""
if not os.path.exists(snapshot_path):
log.error("No such file or directory: {}".format(snapshot_path))
return False
file_size = 0
payload_size = 0
write_offset = 0
try:
sb = os.stat(snapshot_path)
file_size = sb.st_size
assert file_size > 8
except Exception as e:
log.exception(e)
return False
num_sigs = 0
snapshot_hash = None
with open(snapshot_path, 'r+') as f:
if not first:
info = fast_sync_inspect(f)
if 'error' in info:
log.error("Failed to inspect {}: {}".format(snapshot_path, info['error']))
return False
num_sigs = len(info['signatures'])
write_offset = info['sig_append_offset']
payload_size = info['payload_size']
else:
# no one has signed yet.
write_offset = file_size
num_sigs = 0
payload_size = file_size
# hash the file and sign the (bin-encoded) hash
privkey_hex = keylib.ECPrivateKey(private_key).to_hex()
hash_hex = get_file_hash( f, hashlib.sha256, fd_len=payload_size )
sigb64 = sign_digest( hash_hex, privkey_hex, hashfunc=hashlib.sha256 )
if BLOCKSTACK_TEST:
log.debug("Signed {} with {} to make {}".format(hash_hex, keylib.ECPrivateKey(private_key).public_key().to_hex(), sigb64))
# append
f.seek(write_offset, os.SEEK_SET)
f.write(sigb64)
f.write('{:08x}'.format(len(sigb64)))
# append number of signatures
num_sigs += 1
f.write('{:08x}'.format(num_sigs))
f.flush()
os.fsync(f.fileno())
return True | [
"def",
"fast_sync_sign_snapshot",
"(",
"snapshot_path",
",",
"private_key",
",",
"first",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"snapshot_path",
")",
":",
"log",
".",
"error",
"(",
"\"No such file or directory: {}\"",
".",
"format",
"(",
"snapshot_path",
")",
")",
"return",
"False",
"file_size",
"=",
"0",
"payload_size",
"=",
"0",
"write_offset",
"=",
"0",
"try",
":",
"sb",
"=",
"os",
".",
"stat",
"(",
"snapshot_path",
")",
"file_size",
"=",
"sb",
".",
"st_size",
"assert",
"file_size",
">",
"8",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"return",
"False",
"num_sigs",
"=",
"0",
"snapshot_hash",
"=",
"None",
"with",
"open",
"(",
"snapshot_path",
",",
"'r+'",
")",
"as",
"f",
":",
"if",
"not",
"first",
":",
"info",
"=",
"fast_sync_inspect",
"(",
"f",
")",
"if",
"'error'",
"in",
"info",
":",
"log",
".",
"error",
"(",
"\"Failed to inspect {}: {}\"",
".",
"format",
"(",
"snapshot_path",
",",
"info",
"[",
"'error'",
"]",
")",
")",
"return",
"False",
"num_sigs",
"=",
"len",
"(",
"info",
"[",
"'signatures'",
"]",
")",
"write_offset",
"=",
"info",
"[",
"'sig_append_offset'",
"]",
"payload_size",
"=",
"info",
"[",
"'payload_size'",
"]",
"else",
":",
"# no one has signed yet.",
"write_offset",
"=",
"file_size",
"num_sigs",
"=",
"0",
"payload_size",
"=",
"file_size",
"# hash the file and sign the (bin-encoded) hash",
"privkey_hex",
"=",
"keylib",
".",
"ECPrivateKey",
"(",
"private_key",
")",
".",
"to_hex",
"(",
")",
"hash_hex",
"=",
"get_file_hash",
"(",
"f",
",",
"hashlib",
".",
"sha256",
",",
"fd_len",
"=",
"payload_size",
")",
"sigb64",
"=",
"sign_digest",
"(",
"hash_hex",
",",
"privkey_hex",
",",
"hashfunc",
"=",
"hashlib",
".",
"sha256",
")",
"if",
"BLOCKSTACK_TEST",
":",
"log",
".",
"debug",
"(",
"\"Signed {} with {} to make {}\"",
".",
"format",
"(",
"hash_hex",
",",
"keylib",
".",
"ECPrivateKey",
"(",
"private_key",
")",
".",
"public_key",
"(",
")",
".",
"to_hex",
"(",
")",
",",
"sigb64",
")",
")",
"# append",
"f",
".",
"seek",
"(",
"write_offset",
",",
"os",
".",
"SEEK_SET",
")",
"f",
".",
"write",
"(",
"sigb64",
")",
"f",
".",
"write",
"(",
"'{:08x}'",
".",
"format",
"(",
"len",
"(",
"sigb64",
")",
")",
")",
"# append number of signatures",
"num_sigs",
"+=",
"1",
"f",
".",
"write",
"(",
"'{:08x}'",
".",
"format",
"(",
"num_sigs",
")",
")",
"f",
".",
"flush",
"(",
")",
"os",
".",
"fsync",
"(",
"f",
".",
"fileno",
"(",
")",
")",
"return",
"True"
] | Append a signature to the end of a snapshot path
with the given private key.
If first is True, then don't expect the signature trailer.
Return True on success
Return False on error | [
"Append",
"a",
"signature",
"to",
"the",
"end",
"of",
"a",
"snapshot",
"path",
"with",
"the",
"given",
"private",
"key",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/fast_sync.py#L114-L180 |
230,483 | blockstack/blockstack-core | blockstack/lib/fast_sync.py | fast_sync_snapshot_compress | def fast_sync_snapshot_compress( snapshot_dir, export_path ):
"""
Given the path to a directory, compress it and export it to the
given path.
Return {'status': True} on success
Return {'error': ...} on failure
"""
snapshot_dir = os.path.abspath(snapshot_dir)
export_path = os.path.abspath(export_path)
if os.path.exists(export_path):
return {'error': 'Snapshot path exists: {}'.format(export_path)}
old_dir = os.getcwd()
count_ref = [0]
def print_progress(tarinfo):
count_ref[0] += 1
if count_ref[0] % 100 == 0:
log.debug("{} files compressed...".format(count_ref[0]))
return tarinfo
try:
os.chdir(snapshot_dir)
with tarfile.TarFile.bz2open(export_path, "w") as f:
f.add(".", filter=print_progress)
except:
os.chdir(old_dir)
raise
finally:
os.chdir(old_dir)
return {'status': True} | python | def fast_sync_snapshot_compress( snapshot_dir, export_path ):
"""
Given the path to a directory, compress it and export it to the
given path.
Return {'status': True} on success
Return {'error': ...} on failure
"""
snapshot_dir = os.path.abspath(snapshot_dir)
export_path = os.path.abspath(export_path)
if os.path.exists(export_path):
return {'error': 'Snapshot path exists: {}'.format(export_path)}
old_dir = os.getcwd()
count_ref = [0]
def print_progress(tarinfo):
count_ref[0] += 1
if count_ref[0] % 100 == 0:
log.debug("{} files compressed...".format(count_ref[0]))
return tarinfo
try:
os.chdir(snapshot_dir)
with tarfile.TarFile.bz2open(export_path, "w") as f:
f.add(".", filter=print_progress)
except:
os.chdir(old_dir)
raise
finally:
os.chdir(old_dir)
return {'status': True} | [
"def",
"fast_sync_snapshot_compress",
"(",
"snapshot_dir",
",",
"export_path",
")",
":",
"snapshot_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"snapshot_dir",
")",
"export_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"export_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"export_path",
")",
":",
"return",
"{",
"'error'",
":",
"'Snapshot path exists: {}'",
".",
"format",
"(",
"export_path",
")",
"}",
"old_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"count_ref",
"=",
"[",
"0",
"]",
"def",
"print_progress",
"(",
"tarinfo",
")",
":",
"count_ref",
"[",
"0",
"]",
"+=",
"1",
"if",
"count_ref",
"[",
"0",
"]",
"%",
"100",
"==",
"0",
":",
"log",
".",
"debug",
"(",
"\"{} files compressed...\"",
".",
"format",
"(",
"count_ref",
"[",
"0",
"]",
")",
")",
"return",
"tarinfo",
"try",
":",
"os",
".",
"chdir",
"(",
"snapshot_dir",
")",
"with",
"tarfile",
".",
"TarFile",
".",
"bz2open",
"(",
"export_path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"add",
"(",
"\".\"",
",",
"filter",
"=",
"print_progress",
")",
"except",
":",
"os",
".",
"chdir",
"(",
"old_dir",
")",
"raise",
"finally",
":",
"os",
".",
"chdir",
"(",
"old_dir",
")",
"return",
"{",
"'status'",
":",
"True",
"}"
] | Given the path to a directory, compress it and export it to the
given path.
Return {'status': True} on success
Return {'error': ...} on failure | [
"Given",
"the",
"path",
"to",
"a",
"directory",
"compress",
"it",
"and",
"export",
"it",
"to",
"the",
"given",
"path",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/fast_sync.py#L183-L220 |
230,484 | blockstack/blockstack-core | blockstack/lib/fast_sync.py | fast_sync_snapshot_decompress | def fast_sync_snapshot_decompress( snapshot_path, output_dir ):
"""
Given the path to a snapshot file, decompress it and
write its contents to the given output directory
Return {'status': True} on success
Return {'error': ...} on failure
"""
if not tarfile.is_tarfile(snapshot_path):
return {'error': 'Not a tarfile-compatible archive: {}'.format(snapshot_path)}
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with tarfile.TarFile.bz2open(snapshot_path, 'r') as f:
tarfile.TarFile.extractall(f, path=output_dir)
return {'status': True} | python | def fast_sync_snapshot_decompress( snapshot_path, output_dir ):
"""
Given the path to a snapshot file, decompress it and
write its contents to the given output directory
Return {'status': True} on success
Return {'error': ...} on failure
"""
if not tarfile.is_tarfile(snapshot_path):
return {'error': 'Not a tarfile-compatible archive: {}'.format(snapshot_path)}
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with tarfile.TarFile.bz2open(snapshot_path, 'r') as f:
tarfile.TarFile.extractall(f, path=output_dir)
return {'status': True} | [
"def",
"fast_sync_snapshot_decompress",
"(",
"snapshot_path",
",",
"output_dir",
")",
":",
"if",
"not",
"tarfile",
".",
"is_tarfile",
"(",
"snapshot_path",
")",
":",
"return",
"{",
"'error'",
":",
"'Not a tarfile-compatible archive: {}'",
".",
"format",
"(",
"snapshot_path",
")",
"}",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"output_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"output_dir",
")",
"with",
"tarfile",
".",
"TarFile",
".",
"bz2open",
"(",
"snapshot_path",
",",
"'r'",
")",
"as",
"f",
":",
"tarfile",
".",
"TarFile",
".",
"extractall",
"(",
"f",
",",
"path",
"=",
"output_dir",
")",
"return",
"{",
"'status'",
":",
"True",
"}"
] | Given the path to a snapshot file, decompress it and
write its contents to the given output directory
Return {'status': True} on success
Return {'error': ...} on failure | [
"Given",
"the",
"path",
"to",
"a",
"snapshot",
"file",
"decompress",
"it",
"and",
"write",
"its",
"contents",
"to",
"the",
"given",
"output",
"directory"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/fast_sync.py#L223-L240 |
230,485 | blockstack/blockstack-core | blockstack/lib/fast_sync.py | fast_sync_fetch | def fast_sync_fetch(working_dir, import_url):
"""
Get the data for an import snapshot.
Store it to a temporary path
Return the path on success
Return None on error
"""
try:
fd, tmppath = tempfile.mkstemp(prefix='.blockstack-fast-sync-', dir=working_dir)
except Exception, e:
log.exception(e)
return None
log.debug("Fetch {} to {}...".format(import_url, tmppath))
try:
path, headers = urllib.urlretrieve(import_url, tmppath)
except Exception, e:
os.close(fd)
log.exception(e)
return None
os.close(fd)
return tmppath | python | def fast_sync_fetch(working_dir, import_url):
"""
Get the data for an import snapshot.
Store it to a temporary path
Return the path on success
Return None on error
"""
try:
fd, tmppath = tempfile.mkstemp(prefix='.blockstack-fast-sync-', dir=working_dir)
except Exception, e:
log.exception(e)
return None
log.debug("Fetch {} to {}...".format(import_url, tmppath))
try:
path, headers = urllib.urlretrieve(import_url, tmppath)
except Exception, e:
os.close(fd)
log.exception(e)
return None
os.close(fd)
return tmppath | [
"def",
"fast_sync_fetch",
"(",
"working_dir",
",",
"import_url",
")",
":",
"try",
":",
"fd",
",",
"tmppath",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"'.blockstack-fast-sync-'",
",",
"dir",
"=",
"working_dir",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"return",
"None",
"log",
".",
"debug",
"(",
"\"Fetch {} to {}...\"",
".",
"format",
"(",
"import_url",
",",
"tmppath",
")",
")",
"try",
":",
"path",
",",
"headers",
"=",
"urllib",
".",
"urlretrieve",
"(",
"import_url",
",",
"tmppath",
")",
"except",
"Exception",
",",
"e",
":",
"os",
".",
"close",
"(",
"fd",
")",
"log",
".",
"exception",
"(",
"e",
")",
"return",
"None",
"os",
".",
"close",
"(",
"fd",
")",
"return",
"tmppath"
] | Get the data for an import snapshot.
Store it to a temporary path
Return the path on success
Return None on error | [
"Get",
"the",
"data",
"for",
"an",
"import",
"snapshot",
".",
"Store",
"it",
"to",
"a",
"temporary",
"path",
"Return",
"the",
"path",
"on",
"success",
"Return",
"None",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/fast_sync.py#L410-L433 |
230,486 | blockstack/blockstack-core | blockstack/lib/nameset/__init__.py | state_check_collisions | def state_check_collisions( state_engine, nameop, history_id_key, block_id, checked_ops, collision_checker ):
"""
See that there are no state-creating or state-preordering collisions at this block, for this history ID.
Return True if collided; False if not
"""
# verify no collisions against already-accepted names
collision_check = getattr( state_engine, collision_checker, None )
try:
assert collision_check is not None, "Collision-checker '%s' not defined" % collision_checker
assert hasattr( collision_check, "__call__" ), "Collision-checker '%s' is not callable" % collision_checker
assert history_id_key in nameop.keys(), "History ID key '%s' not in name operation" % (history_id_key)
assert 'op' in nameop.keys(), "BUG: no op in nameop"
except Exception, e:
log.exception(e)
log.error("FATAL: incorrect state_create() decorator")
sys.exit(1)
rc = collision_check( nameop[history_id_key], block_id, checked_ops )
return rc | python | def state_check_collisions( state_engine, nameop, history_id_key, block_id, checked_ops, collision_checker ):
"""
See that there are no state-creating or state-preordering collisions at this block, for this history ID.
Return True if collided; False if not
"""
# verify no collisions against already-accepted names
collision_check = getattr( state_engine, collision_checker, None )
try:
assert collision_check is not None, "Collision-checker '%s' not defined" % collision_checker
assert hasattr( collision_check, "__call__" ), "Collision-checker '%s' is not callable" % collision_checker
assert history_id_key in nameop.keys(), "History ID key '%s' not in name operation" % (history_id_key)
assert 'op' in nameop.keys(), "BUG: no op in nameop"
except Exception, e:
log.exception(e)
log.error("FATAL: incorrect state_create() decorator")
sys.exit(1)
rc = collision_check( nameop[history_id_key], block_id, checked_ops )
return rc | [
"def",
"state_check_collisions",
"(",
"state_engine",
",",
"nameop",
",",
"history_id_key",
",",
"block_id",
",",
"checked_ops",
",",
"collision_checker",
")",
":",
"# verify no collisions against already-accepted names",
"collision_check",
"=",
"getattr",
"(",
"state_engine",
",",
"collision_checker",
",",
"None",
")",
"try",
":",
"assert",
"collision_check",
"is",
"not",
"None",
",",
"\"Collision-checker '%s' not defined\"",
"%",
"collision_checker",
"assert",
"hasattr",
"(",
"collision_check",
",",
"\"__call__\"",
")",
",",
"\"Collision-checker '%s' is not callable\"",
"%",
"collision_checker",
"assert",
"history_id_key",
"in",
"nameop",
".",
"keys",
"(",
")",
",",
"\"History ID key '%s' not in name operation\"",
"%",
"(",
"history_id_key",
")",
"assert",
"'op'",
"in",
"nameop",
".",
"keys",
"(",
")",
",",
"\"BUG: no op in nameop\"",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"log",
".",
"error",
"(",
"\"FATAL: incorrect state_create() decorator\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"rc",
"=",
"collision_check",
"(",
"nameop",
"[",
"history_id_key",
"]",
",",
"block_id",
",",
"checked_ops",
")",
"return",
"rc"
] | See that there are no state-creating or state-preordering collisions at this block, for this history ID.
Return True if collided; False if not | [
"See",
"that",
"there",
"are",
"no",
"state",
"-",
"creating",
"or",
"state",
"-",
"preordering",
"collisions",
"at",
"this",
"block",
"for",
"this",
"history",
"ID",
".",
"Return",
"True",
"if",
"collided",
";",
"False",
"if",
"not"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/__init__.py#L100-L119 |
230,487 | blockstack/blockstack-core | blockstack/lib/nameset/__init__.py | state_create_is_valid | def state_create_is_valid( nameop ):
"""
Is a nameop a valid state-preorder operation?
"""
assert '__state_create__' in nameop, "Not tagged with @state_create"
assert nameop['__state_create__'], "BUG: tagged False by @state_create"
assert '__preorder__' in nameop, "No preorder"
assert '__table__' in nameop, "No table given"
assert '__history_id_key__' in nameop, "No history ID key given"
assert nameop['__history_id_key__'] in nameop, "No history ID given"
assert '__always_set__' in nameop, "No always-set fields given"
return True | python | def state_create_is_valid( nameop ):
"""
Is a nameop a valid state-preorder operation?
"""
assert '__state_create__' in nameop, "Not tagged with @state_create"
assert nameop['__state_create__'], "BUG: tagged False by @state_create"
assert '__preorder__' in nameop, "No preorder"
assert '__table__' in nameop, "No table given"
assert '__history_id_key__' in nameop, "No history ID key given"
assert nameop['__history_id_key__'] in nameop, "No history ID given"
assert '__always_set__' in nameop, "No always-set fields given"
return True | [
"def",
"state_create_is_valid",
"(",
"nameop",
")",
":",
"assert",
"'__state_create__'",
"in",
"nameop",
",",
"\"Not tagged with @state_create\"",
"assert",
"nameop",
"[",
"'__state_create__'",
"]",
",",
"\"BUG: tagged False by @state_create\"",
"assert",
"'__preorder__'",
"in",
"nameop",
",",
"\"No preorder\"",
"assert",
"'__table__'",
"in",
"nameop",
",",
"\"No table given\"",
"assert",
"'__history_id_key__'",
"in",
"nameop",
",",
"\"No history ID key given\"",
"assert",
"nameop",
"[",
"'__history_id_key__'",
"]",
"in",
"nameop",
",",
"\"No history ID given\"",
"assert",
"'__always_set__'",
"in",
"nameop",
",",
"\"No always-set fields given\"",
"return",
"True"
] | Is a nameop a valid state-preorder operation? | [
"Is",
"a",
"nameop",
"a",
"valid",
"state",
"-",
"preorder",
"operation?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/__init__.py#L348-L360 |
230,488 | blockstack/blockstack-core | blockstack/lib/nameset/__init__.py | state_transition_is_valid | def state_transition_is_valid( nameop ):
"""
Is this a valid state transition?
"""
assert '__state_transition__' in nameop, "Not tagged with @state_transition"
assert nameop['__state_transition__'], "BUG: @state_transition tagged False"
assert '__history_id_key__' in nameop, "Missing __history_id_key__"
history_id_key = nameop['__history_id_key__']
assert history_id_key in ["name", "namespace_id"], "Invalid history ID key '%s'" % history_id_key
assert '__table__' in nameop, "Missing __table__"
assert '__always_set__' in nameop, "No always-set fields given"
assert '__account_payment_info__' in nameop, 'No account payment information present'
return True | python | def state_transition_is_valid( nameop ):
"""
Is this a valid state transition?
"""
assert '__state_transition__' in nameop, "Not tagged with @state_transition"
assert nameop['__state_transition__'], "BUG: @state_transition tagged False"
assert '__history_id_key__' in nameop, "Missing __history_id_key__"
history_id_key = nameop['__history_id_key__']
assert history_id_key in ["name", "namespace_id"], "Invalid history ID key '%s'" % history_id_key
assert '__table__' in nameop, "Missing __table__"
assert '__always_set__' in nameop, "No always-set fields given"
assert '__account_payment_info__' in nameop, 'No account payment information present'
return True | [
"def",
"state_transition_is_valid",
"(",
"nameop",
")",
":",
"assert",
"'__state_transition__'",
"in",
"nameop",
",",
"\"Not tagged with @state_transition\"",
"assert",
"nameop",
"[",
"'__state_transition__'",
"]",
",",
"\"BUG: @state_transition tagged False\"",
"assert",
"'__history_id_key__'",
"in",
"nameop",
",",
"\"Missing __history_id_key__\"",
"history_id_key",
"=",
"nameop",
"[",
"'__history_id_key__'",
"]",
"assert",
"history_id_key",
"in",
"[",
"\"name\"",
",",
"\"namespace_id\"",
"]",
",",
"\"Invalid history ID key '%s'\"",
"%",
"history_id_key",
"assert",
"'__table__'",
"in",
"nameop",
",",
"\"Missing __table__\"",
"assert",
"'__always_set__'",
"in",
"nameop",
",",
"\"No always-set fields given\"",
"assert",
"'__account_payment_info__'",
"in",
"nameop",
",",
"'No account payment information present'",
"return",
"True"
] | Is this a valid state transition? | [
"Is",
"this",
"a",
"valid",
"state",
"transition?"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/__init__.py#L391-L404 |
230,489 | blockstack/blockstack-core | blockstack/lib/storage/crawl.py | _read_atlas_zonefile | def _read_atlas_zonefile( zonefile_path, zonefile_hash ):
"""
Read and verify an atlas zone file
"""
with open(zonefile_path, "rb") as f:
data = f.read()
# sanity check
if zonefile_hash is not None:
if not verify_zonefile( data, zonefile_hash ):
log.debug("Corrupt zonefile '%s'" % zonefile_hash)
return None
return data | python | def _read_atlas_zonefile( zonefile_path, zonefile_hash ):
"""
Read and verify an atlas zone file
"""
with open(zonefile_path, "rb") as f:
data = f.read()
# sanity check
if zonefile_hash is not None:
if not verify_zonefile( data, zonefile_hash ):
log.debug("Corrupt zonefile '%s'" % zonefile_hash)
return None
return data | [
"def",
"_read_atlas_zonefile",
"(",
"zonefile_path",
",",
"zonefile_hash",
")",
":",
"with",
"open",
"(",
"zonefile_path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"# sanity check ",
"if",
"zonefile_hash",
"is",
"not",
"None",
":",
"if",
"not",
"verify_zonefile",
"(",
"data",
",",
"zonefile_hash",
")",
":",
"log",
".",
"debug",
"(",
"\"Corrupt zonefile '%s'\"",
"%",
"zonefile_hash",
")",
"return",
"None",
"return",
"data"
] | Read and verify an atlas zone file | [
"Read",
"and",
"verify",
"an",
"atlas",
"zone",
"file"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/storage/crawl.py#L37-L51 |
230,490 | blockstack/blockstack-core | blockstack/lib/storage/crawl.py | get_atlas_zonefile_data | def get_atlas_zonefile_data( zonefile_hash, zonefile_dir, check=True ):
"""
Get a serialized cached zonefile from local disk
Return None if not found
"""
zonefile_path = atlas_zonefile_path(zonefile_dir, zonefile_hash)
zonefile_path_legacy = atlas_zonefile_path_legacy(zonefile_dir, zonefile_hash)
for zfp in [zonefile_path, zonefile_path_legacy]:
if not os.path.exists( zfp ):
continue
if check:
res = _read_atlas_zonefile(zfp, zonefile_hash)
else:
res = _read_atlas_zonefile(zfp, None)
if res:
return res
return None | python | def get_atlas_zonefile_data( zonefile_hash, zonefile_dir, check=True ):
"""
Get a serialized cached zonefile from local disk
Return None if not found
"""
zonefile_path = atlas_zonefile_path(zonefile_dir, zonefile_hash)
zonefile_path_legacy = atlas_zonefile_path_legacy(zonefile_dir, zonefile_hash)
for zfp in [zonefile_path, zonefile_path_legacy]:
if not os.path.exists( zfp ):
continue
if check:
res = _read_atlas_zonefile(zfp, zonefile_hash)
else:
res = _read_atlas_zonefile(zfp, None)
if res:
return res
return None | [
"def",
"get_atlas_zonefile_data",
"(",
"zonefile_hash",
",",
"zonefile_dir",
",",
"check",
"=",
"True",
")",
":",
"zonefile_path",
"=",
"atlas_zonefile_path",
"(",
"zonefile_dir",
",",
"zonefile_hash",
")",
"zonefile_path_legacy",
"=",
"atlas_zonefile_path_legacy",
"(",
"zonefile_dir",
",",
"zonefile_hash",
")",
"for",
"zfp",
"in",
"[",
"zonefile_path",
",",
"zonefile_path_legacy",
"]",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"zfp",
")",
":",
"continue",
"if",
"check",
":",
"res",
"=",
"_read_atlas_zonefile",
"(",
"zfp",
",",
"zonefile_hash",
")",
"else",
":",
"res",
"=",
"_read_atlas_zonefile",
"(",
"zfp",
",",
"None",
")",
"if",
"res",
":",
"return",
"res",
"return",
"None"
] | Get a serialized cached zonefile from local disk
Return None if not found | [
"Get",
"a",
"serialized",
"cached",
"zonefile",
"from",
"local",
"disk",
"Return",
"None",
"if",
"not",
"found"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/storage/crawl.py#L54-L75 |
230,491 | blockstack/blockstack-core | blockstack/lib/storage/crawl.py | store_atlas_zonefile_data | def store_atlas_zonefile_data(zonefile_data, zonefile_dir, fsync=True):
"""
Store a validated zonefile.
zonefile_data should be a dict.
The caller should first authenticate the zonefile.
Return True on success
Return False on error
"""
if not os.path.exists(zonefile_dir):
os.makedirs(zonefile_dir, 0700 )
zonefile_hash = get_zonefile_data_hash( zonefile_data )
# only store to the latest supported directory
zonefile_path = atlas_zonefile_path( zonefile_dir, zonefile_hash )
zonefile_dir_path = os.path.dirname(zonefile_path)
if os.path.exists(zonefile_path):
# already exists
return True
if not os.path.exists(zonefile_dir_path):
os.makedirs(zonefile_dir_path)
try:
with open( zonefile_path, "wb" ) as f:
f.write(zonefile_data)
f.flush()
if fsync:
os.fsync(f.fileno())
except Exception, e:
log.exception(e)
return False
return True | python | def store_atlas_zonefile_data(zonefile_data, zonefile_dir, fsync=True):
"""
Store a validated zonefile.
zonefile_data should be a dict.
The caller should first authenticate the zonefile.
Return True on success
Return False on error
"""
if not os.path.exists(zonefile_dir):
os.makedirs(zonefile_dir, 0700 )
zonefile_hash = get_zonefile_data_hash( zonefile_data )
# only store to the latest supported directory
zonefile_path = atlas_zonefile_path( zonefile_dir, zonefile_hash )
zonefile_dir_path = os.path.dirname(zonefile_path)
if os.path.exists(zonefile_path):
# already exists
return True
if not os.path.exists(zonefile_dir_path):
os.makedirs(zonefile_dir_path)
try:
with open( zonefile_path, "wb" ) as f:
f.write(zonefile_data)
f.flush()
if fsync:
os.fsync(f.fileno())
except Exception, e:
log.exception(e)
return False
return True | [
"def",
"store_atlas_zonefile_data",
"(",
"zonefile_data",
",",
"zonefile_dir",
",",
"fsync",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"zonefile_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"zonefile_dir",
",",
"0700",
")",
"zonefile_hash",
"=",
"get_zonefile_data_hash",
"(",
"zonefile_data",
")",
"# only store to the latest supported directory",
"zonefile_path",
"=",
"atlas_zonefile_path",
"(",
"zonefile_dir",
",",
"zonefile_hash",
")",
"zonefile_dir_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"zonefile_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"zonefile_path",
")",
":",
"# already exists ",
"return",
"True",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"zonefile_dir_path",
")",
":",
"os",
".",
"makedirs",
"(",
"zonefile_dir_path",
")",
"try",
":",
"with",
"open",
"(",
"zonefile_path",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"zonefile_data",
")",
"f",
".",
"flush",
"(",
")",
"if",
"fsync",
":",
"os",
".",
"fsync",
"(",
"f",
".",
"fileno",
"(",
")",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"return",
"False",
"return",
"True"
] | Store a validated zonefile.
zonefile_data should be a dict.
The caller should first authenticate the zonefile.
Return True on success
Return False on error | [
"Store",
"a",
"validated",
"zonefile",
".",
"zonefile_data",
"should",
"be",
"a",
"dict",
".",
"The",
"caller",
"should",
"first",
"authenticate",
"the",
"zonefile",
".",
"Return",
"True",
"on",
"success",
"Return",
"False",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/storage/crawl.py#L146-L181 |
230,492 | blockstack/blockstack-core | blockstack/lib/storage/crawl.py | remove_atlas_zonefile_data | def remove_atlas_zonefile_data( zonefile_hash, zonefile_dir ):
"""
Remove a cached zonefile.
Idempotent; returns True if deleted or it didn't exist.
Returns False on error
"""
if not os.path.exists(zonefile_dir):
return True
zonefile_path = atlas_zonefile_path( zonefile_dir, zonefile_hash )
zonefile_path_legacy = atlas_zonefile_path_legacy( zonefile_dir, zonefile_hash )
for zfp in [zonefile_path, zonefile_path_legacy]:
if not os.path.exists(zonefile_path):
continue
try:
os.unlink(zonefile_path)
except:
log.error("Failed to unlink zonefile %s (%s)" % (zonefile_hash, zonefile_path))
return True | python | def remove_atlas_zonefile_data( zonefile_hash, zonefile_dir ):
"""
Remove a cached zonefile.
Idempotent; returns True if deleted or it didn't exist.
Returns False on error
"""
if not os.path.exists(zonefile_dir):
return True
zonefile_path = atlas_zonefile_path( zonefile_dir, zonefile_hash )
zonefile_path_legacy = atlas_zonefile_path_legacy( zonefile_dir, zonefile_hash )
for zfp in [zonefile_path, zonefile_path_legacy]:
if not os.path.exists(zonefile_path):
continue
try:
os.unlink(zonefile_path)
except:
log.error("Failed to unlink zonefile %s (%s)" % (zonefile_hash, zonefile_path))
return True | [
"def",
"remove_atlas_zonefile_data",
"(",
"zonefile_hash",
",",
"zonefile_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"zonefile_dir",
")",
":",
"return",
"True",
"zonefile_path",
"=",
"atlas_zonefile_path",
"(",
"zonefile_dir",
",",
"zonefile_hash",
")",
"zonefile_path_legacy",
"=",
"atlas_zonefile_path_legacy",
"(",
"zonefile_dir",
",",
"zonefile_hash",
")",
"for",
"zfp",
"in",
"[",
"zonefile_path",
",",
"zonefile_path_legacy",
"]",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"zonefile_path",
")",
":",
"continue",
"try",
":",
"os",
".",
"unlink",
"(",
"zonefile_path",
")",
"except",
":",
"log",
".",
"error",
"(",
"\"Failed to unlink zonefile %s (%s)\"",
"%",
"(",
"zonefile_hash",
",",
"zonefile_path",
")",
")",
"return",
"True"
] | Remove a cached zonefile.
Idempotent; returns True if deleted or it didn't exist.
Returns False on error | [
"Remove",
"a",
"cached",
"zonefile",
".",
"Idempotent",
";",
"returns",
"True",
"if",
"deleted",
"or",
"it",
"didn",
"t",
"exist",
".",
"Returns",
"False",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/storage/crawl.py#L184-L205 |
230,493 | blockstack/blockstack-core | blockstack/lib/storage/crawl.py | add_atlas_zonefile_data | def add_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=True):
"""
Add a zone file to the atlas zonefiles
Return True on success
Return False on error
"""
rc = store_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=fsync)
if not rc:
zonefile_hash = get_zonefile_data_hash( zonefile_text )
log.error("Failed to save zonefile {}".format(zonefile_hash))
rc = False
return rc | python | def add_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=True):
"""
Add a zone file to the atlas zonefiles
Return True on success
Return False on error
"""
rc = store_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=fsync)
if not rc:
zonefile_hash = get_zonefile_data_hash( zonefile_text )
log.error("Failed to save zonefile {}".format(zonefile_hash))
rc = False
return rc | [
"def",
"add_atlas_zonefile_data",
"(",
"zonefile_text",
",",
"zonefile_dir",
",",
"fsync",
"=",
"True",
")",
":",
"rc",
"=",
"store_atlas_zonefile_data",
"(",
"zonefile_text",
",",
"zonefile_dir",
",",
"fsync",
"=",
"fsync",
")",
"if",
"not",
"rc",
":",
"zonefile_hash",
"=",
"get_zonefile_data_hash",
"(",
"zonefile_text",
")",
"log",
".",
"error",
"(",
"\"Failed to save zonefile {}\"",
".",
"format",
"(",
"zonefile_hash",
")",
")",
"rc",
"=",
"False",
"return",
"rc"
] | Add a zone file to the atlas zonefiles
Return True on success
Return False on error | [
"Add",
"a",
"zone",
"file",
"to",
"the",
"atlas",
"zonefiles",
"Return",
"True",
"on",
"success",
"Return",
"False",
"on",
"error"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/storage/crawl.py#L208-L221 |
230,494 | blockstack/blockstack-core | blockstack/lib/operations/transfer.py | transfer_sanity_check | def transfer_sanity_check( name, consensus_hash ):
"""
Verify that data for a transfer is valid.
Return True on success
Raise Exception on error
"""
if name is not None and (not is_b40( name ) or "+" in name or name.count(".") > 1):
raise Exception("Name '%s' has non-base-38 characters" % name)
# without the scheme, name must be 37 bytes
if name is not None and (len(name) > LENGTHS['blockchain_id_name']):
raise Exception("Name '%s' is too long; expected %s bytes" % (name, LENGTHS['blockchain_id_name']))
return True | python | def transfer_sanity_check( name, consensus_hash ):
"""
Verify that data for a transfer is valid.
Return True on success
Raise Exception on error
"""
if name is not None and (not is_b40( name ) or "+" in name or name.count(".") > 1):
raise Exception("Name '%s' has non-base-38 characters" % name)
# without the scheme, name must be 37 bytes
if name is not None and (len(name) > LENGTHS['blockchain_id_name']):
raise Exception("Name '%s' is too long; expected %s bytes" % (name, LENGTHS['blockchain_id_name']))
return True | [
"def",
"transfer_sanity_check",
"(",
"name",
",",
"consensus_hash",
")",
":",
"if",
"name",
"is",
"not",
"None",
"and",
"(",
"not",
"is_b40",
"(",
"name",
")",
"or",
"\"+\"",
"in",
"name",
"or",
"name",
".",
"count",
"(",
"\".\"",
")",
">",
"1",
")",
":",
"raise",
"Exception",
"(",
"\"Name '%s' has non-base-38 characters\"",
"%",
"name",
")",
"# without the scheme, name must be 37 bytes ",
"if",
"name",
"is",
"not",
"None",
"and",
"(",
"len",
"(",
"name",
")",
">",
"LENGTHS",
"[",
"'blockchain_id_name'",
"]",
")",
":",
"raise",
"Exception",
"(",
"\"Name '%s' is too long; expected %s bytes\"",
"%",
"(",
"name",
",",
"LENGTHS",
"[",
"'blockchain_id_name'",
"]",
")",
")",
"return",
"True"
] | Verify that data for a transfer is valid.
Return True on success
Raise Exception on error | [
"Verify",
"that",
"data",
"for",
"a",
"transfer",
"is",
"valid",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/transfer.py#L70-L84 |
230,495 | blockstack/blockstack-core | blockstack/lib/operations/transfer.py | find_transfer_consensus_hash | def find_transfer_consensus_hash( name_rec, block_id, vtxindex, nameop_consensus_hash ):
"""
Given a name record, find the last consensus hash set by a non-NAME_TRANSFER operation.
@name_rec is the current name record, before this NAME_TRANSFER.
@block_id is the current block height.
@vtxindex is the relative index of this transaction in this block.
@nameop_consensus_hash is the consensus hash given in the NAME_TRANSFER.
This preserves compatibility from a bug prior to 0.14.x where the consensus hash from a NAME_TRANSFER
is ignored in favor of the last consensus hash (if any) supplied by an operation to the affected name.
This method finds that consensus hash (if present).
The behavior emulated comes from the fact that in the original release of this software, the fields from
a name operation fed into the block's consensus hash included the consensus hashes given in each of the
a name operations' transactions. However, a quirk in the behavior of the NAME_TRANSFER-handling code
prevented this from happening consistently for NAME_TRANSFERs. Specifically, the only time a NAME_TRANSFER's
consensus hash was used to calculate the block's new consensus hash was if the name it affected had never
been affected by a prior state transition other than a NAME_TRANSFER. If the name was affected by
a prior state transition that set a consensus hash, then that prior state transition's consensus hash
(not the NAME_TRANSFER's) would be used in the block consensus hash calculation. If the name was NOT
affected by a prior state transition that set a consensus hash (back to the point of its last NAME_REGISTRATION),
then the consensus hash fed into the block would be that from the NAME_TRANSFER itself.
In practice, the only name operation that consistently sets a consensus hash is NAME_UPDATE. As for the others:
* NAME_REGISTRATION sets it to None
* NAME_IMPORT sets it to None
* NAME_RENEWAL doesn't set it at all; it just takes what was already there
* NAME_TRANSFER only sets it if there were no prior NAME_UPDATEs between now and the last NAME_REGISTRATION or NAME_IMPORT.
Here are some example name histories, and the consensus hash that should be used to calculate this block's consensus hash:
NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER: nameop_consensus_hash
NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER, NAME_TRANSFER: nameop_consensus_hash
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_TRANSFER: whatever it was from the last NAME_UPDATE
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_TRANSFER, NAME_UPDATE, NAME_TRANSFER: whatever it was from the last NAME_UPDATE
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_RENEWAL, NAME_TRANSFER: whatever it was from the last NAME_UPDATE
NAME_PREORDER, NAME_REGISTRATION, NAME_RENEWAL, NAME_TRANSFER: nameop_consensus_hash
NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER, NAME_RENEWAL, NAME_TRANSFER: nameop_consensus_hash
NAME_IMPORT, NAME_TRANSFER: nameop_consensus_hash
NAME_IMPORT, NAME_UPDATE, NAME_TRANSFER whatever it was from the last NAME_UPDATE
NAME_IMPORT, NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER: nameop_consensus_hash
NAME_IMPORT, NAME_TRANSFER, NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER: nameop_consensus_hash
"""
# work backwards from the last block
for historic_block_number in reversed(sorted(name_rec['history'].keys())):
for historic_state in reversed(name_rec['history'][historic_block_number]):
if historic_state['block_number'] > block_id or (historic_state['block_number'] == block_id and historic_state['vtxindex'] > vtxindex):
# from the future
continue
if historic_state['op'] in [NAME_REGISTRATION, NAME_IMPORT]:
# out of history without finding a NAME_UPDATE
return nameop_consensus_hash
if historic_state['op'] == NAME_UPDATE:
# reuse this consensus hash
assert historic_state['consensus_hash'] is not None, 'BUG: NAME_UPDATE did not set "consensus_hash": {}'.format(historic_state)
return historic_state['consensus_hash']
return nameop_consensus_hash | python | def find_transfer_consensus_hash( name_rec, block_id, vtxindex, nameop_consensus_hash ):
"""
Given a name record, find the last consensus hash set by a non-NAME_TRANSFER operation.
@name_rec is the current name record, before this NAME_TRANSFER.
@block_id is the current block height.
@vtxindex is the relative index of this transaction in this block.
@nameop_consensus_hash is the consensus hash given in the NAME_TRANSFER.
This preserves compatibility from a bug prior to 0.14.x where the consensus hash from a NAME_TRANSFER
is ignored in favor of the last consensus hash (if any) supplied by an operation to the affected name.
This method finds that consensus hash (if present).
The behavior emulated comes from the fact that in the original release of this software, the fields from
a name operation fed into the block's consensus hash included the consensus hashes given in each of the
a name operations' transactions. However, a quirk in the behavior of the NAME_TRANSFER-handling code
prevented this from happening consistently for NAME_TRANSFERs. Specifically, the only time a NAME_TRANSFER's
consensus hash was used to calculate the block's new consensus hash was if the name it affected had never
been affected by a prior state transition other than a NAME_TRANSFER. If the name was affected by
a prior state transition that set a consensus hash, then that prior state transition's consensus hash
(not the NAME_TRANSFER's) would be used in the block consensus hash calculation. If the name was NOT
affected by a prior state transition that set a consensus hash (back to the point of its last NAME_REGISTRATION),
then the consensus hash fed into the block would be that from the NAME_TRANSFER itself.
In practice, the only name operation that consistently sets a consensus hash is NAME_UPDATE. As for the others:
* NAME_REGISTRATION sets it to None
* NAME_IMPORT sets it to None
* NAME_RENEWAL doesn't set it at all; it just takes what was already there
* NAME_TRANSFER only sets it if there were no prior NAME_UPDATEs between now and the last NAME_REGISTRATION or NAME_IMPORT.
Here are some example name histories, and the consensus hash that should be used to calculate this block's consensus hash:
NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER: nameop_consensus_hash
NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER, NAME_TRANSFER: nameop_consensus_hash
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_TRANSFER: whatever it was from the last NAME_UPDATE
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_TRANSFER, NAME_UPDATE, NAME_TRANSFER: whatever it was from the last NAME_UPDATE
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_RENEWAL, NAME_TRANSFER: whatever it was from the last NAME_UPDATE
NAME_PREORDER, NAME_REGISTRATION, NAME_RENEWAL, NAME_TRANSFER: nameop_consensus_hash
NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER, NAME_RENEWAL, NAME_TRANSFER: nameop_consensus_hash
NAME_IMPORT, NAME_TRANSFER: nameop_consensus_hash
NAME_IMPORT, NAME_UPDATE, NAME_TRANSFER whatever it was from the last NAME_UPDATE
NAME_IMPORT, NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER: nameop_consensus_hash
NAME_IMPORT, NAME_TRANSFER, NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER: nameop_consensus_hash
"""
# work backwards from the last block
for historic_block_number in reversed(sorted(name_rec['history'].keys())):
for historic_state in reversed(name_rec['history'][historic_block_number]):
if historic_state['block_number'] > block_id or (historic_state['block_number'] == block_id and historic_state['vtxindex'] > vtxindex):
# from the future
continue
if historic_state['op'] in [NAME_REGISTRATION, NAME_IMPORT]:
# out of history without finding a NAME_UPDATE
return nameop_consensus_hash
if historic_state['op'] == NAME_UPDATE:
# reuse this consensus hash
assert historic_state['consensus_hash'] is not None, 'BUG: NAME_UPDATE did not set "consensus_hash": {}'.format(historic_state)
return historic_state['consensus_hash']
return nameop_consensus_hash | [
"def",
"find_transfer_consensus_hash",
"(",
"name_rec",
",",
"block_id",
",",
"vtxindex",
",",
"nameop_consensus_hash",
")",
":",
"# work backwards from the last block",
"for",
"historic_block_number",
"in",
"reversed",
"(",
"sorted",
"(",
"name_rec",
"[",
"'history'",
"]",
".",
"keys",
"(",
")",
")",
")",
":",
"for",
"historic_state",
"in",
"reversed",
"(",
"name_rec",
"[",
"'history'",
"]",
"[",
"historic_block_number",
"]",
")",
":",
"if",
"historic_state",
"[",
"'block_number'",
"]",
">",
"block_id",
"or",
"(",
"historic_state",
"[",
"'block_number'",
"]",
"==",
"block_id",
"and",
"historic_state",
"[",
"'vtxindex'",
"]",
">",
"vtxindex",
")",
":",
"# from the future",
"continue",
"if",
"historic_state",
"[",
"'op'",
"]",
"in",
"[",
"NAME_REGISTRATION",
",",
"NAME_IMPORT",
"]",
":",
"# out of history without finding a NAME_UPDATE",
"return",
"nameop_consensus_hash",
"if",
"historic_state",
"[",
"'op'",
"]",
"==",
"NAME_UPDATE",
":",
"# reuse this consensus hash ",
"assert",
"historic_state",
"[",
"'consensus_hash'",
"]",
"is",
"not",
"None",
",",
"'BUG: NAME_UPDATE did not set \"consensus_hash\": {}'",
".",
"format",
"(",
"historic_state",
")",
"return",
"historic_state",
"[",
"'consensus_hash'",
"]",
"return",
"nameop_consensus_hash"
] | Given a name record, find the last consensus hash set by a non-NAME_TRANSFER operation.
@name_rec is the current name record, before this NAME_TRANSFER.
@block_id is the current block height.
@vtxindex is the relative index of this transaction in this block.
@nameop_consensus_hash is the consensus hash given in the NAME_TRANSFER.
This preserves compatibility from a bug prior to 0.14.x where the consensus hash from a NAME_TRANSFER
is ignored in favor of the last consensus hash (if any) supplied by an operation to the affected name.
This method finds that consensus hash (if present).
The behavior emulated comes from the fact that in the original release of this software, the fields from
a name operation fed into the block's consensus hash included the consensus hashes given in each of the
a name operations' transactions. However, a quirk in the behavior of the NAME_TRANSFER-handling code
prevented this from happening consistently for NAME_TRANSFERs. Specifically, the only time a NAME_TRANSFER's
consensus hash was used to calculate the block's new consensus hash was if the name it affected had never
been affected by a prior state transition other than a NAME_TRANSFER. If the name was affected by
a prior state transition that set a consensus hash, then that prior state transition's consensus hash
(not the NAME_TRANSFER's) would be used in the block consensus hash calculation. If the name was NOT
affected by a prior state transition that set a consensus hash (back to the point of its last NAME_REGISTRATION),
then the consensus hash fed into the block would be that from the NAME_TRANSFER itself.
In practice, the only name operation that consistently sets a consensus hash is NAME_UPDATE. As for the others:
* NAME_REGISTRATION sets it to None
* NAME_IMPORT sets it to None
* NAME_RENEWAL doesn't set it at all; it just takes what was already there
* NAME_TRANSFER only sets it if there were no prior NAME_UPDATEs between now and the last NAME_REGISTRATION or NAME_IMPORT.
Here are some example name histories, and the consensus hash that should be used to calculate this block's consensus hash:
NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER: nameop_consensus_hash
NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER, NAME_TRANSFER: nameop_consensus_hash
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_TRANSFER: whatever it was from the last NAME_UPDATE
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_TRANSFER, NAME_UPDATE, NAME_TRANSFER: whatever it was from the last NAME_UPDATE
NAME_PREORDER, NAME_REGISTRATION, NAME_UPDATE, NAME_RENEWAL, NAME_TRANSFER: whatever it was from the last NAME_UPDATE
NAME_PREORDER, NAME_REGISTRATION, NAME_RENEWAL, NAME_TRANSFER: nameop_consensus_hash
NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER, NAME_RENEWAL, NAME_TRANSFER: nameop_consensus_hash
NAME_IMPORT, NAME_TRANSFER: nameop_consensus_hash
NAME_IMPORT, NAME_UPDATE, NAME_TRANSFER whatever it was from the last NAME_UPDATE
NAME_IMPORT, NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER: nameop_consensus_hash
NAME_IMPORT, NAME_TRANSFER, NAME_PREORDER, NAME_REGISTRATION, NAME_TRANSFER: nameop_consensus_hash | [
"Given",
"a",
"name",
"record",
"find",
"the",
"last",
"consensus",
"hash",
"set",
"by",
"a",
"non",
"-",
"NAME_TRANSFER",
"operation",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/transfer.py#L87-L146 |
230,496 | blockstack/blockstack-core | blockstack/lib/operations/transfer.py | canonicalize | def canonicalize(parsed_op):
"""
Get the "canonical form" of this operation, putting it into a form where it can be serialized
to form a consensus hash. This method is meant to preserve compatibility across blockstackd releases.
For NAME_TRANSFER, this means:
* add 'keep_data' flag
"""
assert 'op' in parsed_op
assert len(parsed_op['op']) == 2
if parsed_op['op'][1] == TRANSFER_KEEP_DATA:
parsed_op['keep_data'] = True
elif parsed_op['op'][1] == TRANSFER_REMOVE_DATA:
parsed_op['keep_data'] = False
else:
raise ValueError("Invalid op '{}'".format(parsed_op['op']))
return parsed_op | python | def canonicalize(parsed_op):
"""
Get the "canonical form" of this operation, putting it into a form where it can be serialized
to form a consensus hash. This method is meant to preserve compatibility across blockstackd releases.
For NAME_TRANSFER, this means:
* add 'keep_data' flag
"""
assert 'op' in parsed_op
assert len(parsed_op['op']) == 2
if parsed_op['op'][1] == TRANSFER_KEEP_DATA:
parsed_op['keep_data'] = True
elif parsed_op['op'][1] == TRANSFER_REMOVE_DATA:
parsed_op['keep_data'] = False
else:
raise ValueError("Invalid op '{}'".format(parsed_op['op']))
return parsed_op | [
"def",
"canonicalize",
"(",
"parsed_op",
")",
":",
"assert",
"'op'",
"in",
"parsed_op",
"assert",
"len",
"(",
"parsed_op",
"[",
"'op'",
"]",
")",
"==",
"2",
"if",
"parsed_op",
"[",
"'op'",
"]",
"[",
"1",
"]",
"==",
"TRANSFER_KEEP_DATA",
":",
"parsed_op",
"[",
"'keep_data'",
"]",
"=",
"True",
"elif",
"parsed_op",
"[",
"'op'",
"]",
"[",
"1",
"]",
"==",
"TRANSFER_REMOVE_DATA",
":",
"parsed_op",
"[",
"'keep_data'",
"]",
"=",
"False",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid op '{}'\"",
".",
"format",
"(",
"parsed_op",
"[",
"'op'",
"]",
")",
")",
"return",
"parsed_op"
] | Get the "canonical form" of this operation, putting it into a form where it can be serialized
to form a consensus hash. This method is meant to preserve compatibility across blockstackd releases.
For NAME_TRANSFER, this means:
* add 'keep_data' flag | [
"Get",
"the",
"canonical",
"form",
"of",
"this",
"operation",
"putting",
"it",
"into",
"a",
"form",
"where",
"it",
"can",
"be",
"serialized",
"to",
"form",
"a",
"consensus",
"hash",
".",
"This",
"method",
"is",
"meant",
"to",
"preserve",
"compatibility",
"across",
"blockstackd",
"releases",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/transfer.py#L405-L423 |
230,497 | blockstack/blockstack-core | blockstack/blockstackd.py | get_bitcoind | def get_bitcoind( new_bitcoind_opts=None, reset=False, new=False ):
"""
Get or instantiate our bitcoind client.
Optionally re-set the bitcoind options.
"""
global bitcoind
if reset:
bitcoind = None
elif not new and bitcoind is not None:
return bitcoind
if new or bitcoind is None:
if new_bitcoind_opts is not None:
set_bitcoin_opts( new_bitcoind_opts )
bitcoin_opts = get_bitcoin_opts()
new_bitcoind = None
try:
try:
new_bitcoind = virtualchain.connect_bitcoind( bitcoin_opts )
except KeyError, ke:
log.exception(ke)
log.error("Invalid configuration: %s" % bitcoin_opts)
return None
if new:
return new_bitcoind
else:
# save for subsequent reuse
bitcoind = new_bitcoind
return bitcoind
except Exception, e:
log.exception( e )
return None | python | def get_bitcoind( new_bitcoind_opts=None, reset=False, new=False ):
"""
Get or instantiate our bitcoind client.
Optionally re-set the bitcoind options.
"""
global bitcoind
if reset:
bitcoind = None
elif not new and bitcoind is not None:
return bitcoind
if new or bitcoind is None:
if new_bitcoind_opts is not None:
set_bitcoin_opts( new_bitcoind_opts )
bitcoin_opts = get_bitcoin_opts()
new_bitcoind = None
try:
try:
new_bitcoind = virtualchain.connect_bitcoind( bitcoin_opts )
except KeyError, ke:
log.exception(ke)
log.error("Invalid configuration: %s" % bitcoin_opts)
return None
if new:
return new_bitcoind
else:
# save for subsequent reuse
bitcoind = new_bitcoind
return bitcoind
except Exception, e:
log.exception( e )
return None | [
"def",
"get_bitcoind",
"(",
"new_bitcoind_opts",
"=",
"None",
",",
"reset",
"=",
"False",
",",
"new",
"=",
"False",
")",
":",
"global",
"bitcoind",
"if",
"reset",
":",
"bitcoind",
"=",
"None",
"elif",
"not",
"new",
"and",
"bitcoind",
"is",
"not",
"None",
":",
"return",
"bitcoind",
"if",
"new",
"or",
"bitcoind",
"is",
"None",
":",
"if",
"new_bitcoind_opts",
"is",
"not",
"None",
":",
"set_bitcoin_opts",
"(",
"new_bitcoind_opts",
")",
"bitcoin_opts",
"=",
"get_bitcoin_opts",
"(",
")",
"new_bitcoind",
"=",
"None",
"try",
":",
"try",
":",
"new_bitcoind",
"=",
"virtualchain",
".",
"connect_bitcoind",
"(",
"bitcoin_opts",
")",
"except",
"KeyError",
",",
"ke",
":",
"log",
".",
"exception",
"(",
"ke",
")",
"log",
".",
"error",
"(",
"\"Invalid configuration: %s\"",
"%",
"bitcoin_opts",
")",
"return",
"None",
"if",
"new",
":",
"return",
"new_bitcoind",
"else",
":",
"# save for subsequent reuse",
"bitcoind",
"=",
"new_bitcoind",
"return",
"bitcoind",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"return",
"None"
] | Get or instantiate our bitcoind client.
Optionally re-set the bitcoind options. | [
"Get",
"or",
"instantiate",
"our",
"bitcoind",
"client",
".",
"Optionally",
"re",
"-",
"set",
"the",
"bitcoind",
"options",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L95-L133 |
230,498 | blockstack/blockstack-core | blockstack/blockstackd.py | get_pidfile_path | def get_pidfile_path(working_dir):
"""
Get the PID file path.
"""
pid_filename = virtualchain_hooks.get_virtual_chain_name() + ".pid"
return os.path.join( working_dir, pid_filename ) | python | def get_pidfile_path(working_dir):
"""
Get the PID file path.
"""
pid_filename = virtualchain_hooks.get_virtual_chain_name() + ".pid"
return os.path.join( working_dir, pid_filename ) | [
"def",
"get_pidfile_path",
"(",
"working_dir",
")",
":",
"pid_filename",
"=",
"virtualchain_hooks",
".",
"get_virtual_chain_name",
"(",
")",
"+",
"\".pid\"",
"return",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"pid_filename",
")"
] | Get the PID file path. | [
"Get",
"the",
"PID",
"file",
"path",
"."
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L136-L141 |
230,499 | blockstack/blockstack-core | blockstack/blockstackd.py | put_pidfile | def put_pidfile( pidfile_path, pid ):
"""
Put a PID into a pidfile
"""
with open( pidfile_path, "w" ) as f:
f.write("%s" % pid)
os.fsync(f.fileno())
return | python | def put_pidfile( pidfile_path, pid ):
"""
Put a PID into a pidfile
"""
with open( pidfile_path, "w" ) as f:
f.write("%s" % pid)
os.fsync(f.fileno())
return | [
"def",
"put_pidfile",
"(",
"pidfile_path",
",",
"pid",
")",
":",
"with",
"open",
"(",
"pidfile_path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"%s\"",
"%",
"pid",
")",
"os",
".",
"fsync",
"(",
"f",
".",
"fileno",
"(",
")",
")",
"return"
] | Put a PID into a pidfile | [
"Put",
"a",
"PID",
"into",
"a",
"pidfile"
] | 1dcfdd39b152d29ce13e736a6a1a0981401a0505 | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L144-L152 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.