MiNode/minode/i2p/util.py

54 lines
1.5 KiB
Python
Raw Normal View History

2017-06-09 20:41:33 +02:00
# -*- coding: utf-8 -*-
2024-07-24 17:54:14 +02:00
"""Common reusable code for all the I2P entities"""
2017-06-09 20:41:33 +02:00
import base64
import hashlib
import threading
2017-06-09 20:41:33 +02:00
def receive_line(s):
2024-07-24 17:54:14 +02:00
"""Receive a line from the socket *s*"""
2017-06-09 20:41:33 +02:00
data = b''
while b'\n' not in data:
d = s.recv(4096)
if not d:
raise ConnectionResetError
data += d
data = data.splitlines()
return data[0]
class I2PThread(threading.Thread):
"""
Abstract I2P thread with _receive_line() and _send() methods,
reused in I2PDialer, I2PListener and I2PController
"""
2023-07-30 00:05:08 +02:00
def __init__(self, state, name=''):
super().__init__(name=name)
self.state = state
self.s = None
def _receive_line(self):
line = receive_line(self.s)
# logging.debug('I2PListener <- %s', line)
return line
def _send(self, command):
# logging.debug('I2PListener -> %s', command)
self.s.sendall(command)
2017-06-09 20:41:33 +02:00
def pub_from_priv(priv):
2024-07-24 17:54:14 +02:00
"""Returns the public key for the private key *priv*"""
2017-06-09 20:41:33 +02:00
priv = base64.b64decode(priv, altchars=b'-~')
2021-03-08 16:06:07 +01:00
# 256 for public key + 128 for signing key + 3 for certificate header
# + value of bytes priv[385:387]
2017-06-09 20:41:33 +02:00
pub = priv[:387 + int.from_bytes(priv[385:387], byteorder='big')]
return base64.b64encode(pub, altchars=b'-~')
2017-06-09 20:41:33 +02:00
def b32_from_pub(pub):
2024-07-24 17:54:14 +02:00
"""Converts the public key *pub* to base32 host name"""
2021-03-08 16:06:07 +01:00
return base64.b32encode(
hashlib.sha256(base64.b64decode(pub, b'-~')).digest()
).replace(b'=', b'').lower() + b'.b32.i2p'