Skip to content
Snippets Groups Projects
Commit 87fcbb86 authored by Pascal Engélibert's avatar Pascal Engélibert :bicyclist:
Browse files

Standardize function names

parent bb015a71
No related branches found
No related tags found
No related merge requests found
Pipeline #5634 passed
...@@ -253,17 +253,17 @@ def mix(db_txs, amount, base, sender, path, host, proxy=None, proxy_onion_only=F ...@@ -253,17 +253,17 @@ def mix(db_txs, amount, base, sender, path, host, proxy=None, proxy_onion_only=F
if send_tx: if send_tx:
try: try:
sendTransaction(sender, path[0], amount, gen_comment(comment_seeds[0])) send_transaction(sender, path[0], amount, gen_comment(comment_seeds[0]))
message["sent"] = True message["sent"] = True
db_txs.put(comment_seeds[0][1], PublicKey(sender.pubkey).encrypt_seal(ubjson.dumpb(message))) db_txs.put(comment_seeds[0][1], PublicKey(sender.pubkey).encrypt_seal(ubjson.dumpb(message)))
except socket.timeout: except socket.timeout:
logPrint("Error when sending tx: timeout", LOG_ERROR) logprint("Error when sending tx: timeout", LOG_ERROR)
except Exception as e: except Exception as e:
logPrint("Error when sending tx: " + str(e), LOG_ERROR) logprint("Error when sending tx: " + str(e), LOG_ERROR)
return return
async def test1(db_txs, host, receiver, amount=1000, layers=3, proxy=None, proxy_onion_only=False, send_tx=True): async def main(db_txs, host, receiver, amount=1000, layers=3, proxy=None, proxy_onion_only=False, send_tx=True):
if amount < 100: if amount < 100:
print("!! Warning !!\nYou are going to send less than 1.00, all this money will be destroyed by Duniter.\nPlease always send 1.00 or more.") print("!! Warning !!\nYou are going to send less than 1.00, all this money will be destroyed by Duniter.\nPlease always send 1.00 or more.")
if input("Do it anyway? [yn]: ").lower() != "y": if input("Do it anyway? [yn]: ").lower() != "y":
...@@ -337,4 +337,4 @@ python3 client.py -h svetsae7j3usrycn.onion 10951 -r 78ZwwgpgdH5uLZLbThUQH7LKwPg ...@@ -337,4 +337,4 @@ python3 client.py -h svetsae7j3usrycn.onion 10951 -r 78ZwwgpgdH5uLZLbThUQH7LKwPg
db_txs = plyvel.DB(DIR+"/client_db_txs", create_if_missing=True) db_txs = plyvel.DB(DIR+"/client_db_txs", create_if_missing=True)
asyncio.get_event_loop().run_until_complete(test1(db_txs, (host, port), receiver, amount, layers, proxy, proxy_onion_only, send_tx)) asyncio.get_event_loop().run_until_complete(main(db_txs, (host, port), receiver, amount, layers, proxy, proxy_onion_only, send_tx))
...@@ -55,7 +55,7 @@ MIX_INTERVAL = 60 ...@@ -55,7 +55,7 @@ MIX_INTERVAL = 60
MIX_MIN_TXS = 5 # minimum amount of txs to mix MIX_MIN_TXS = 5 # minimum amount of txs to mix
MIX_REQ_AGE_MAX = 604800 # maximum mix request age before return to sender MIX_REQ_AGE_MAX = 604800 # maximum mix request age before return to sender
def sendResponse(client, code, resp, dataformat="ubjson"): def send_response(client, code, resp, dataformat="ubjson"):
if dataformat == "ubjson": if dataformat == "ubjson":
content_raw = ubjson.dumpb(resp) content_raw = ubjson.dumpb(resp)
mime = "application/ubjson" mime = "application/ubjson"
...@@ -90,7 +90,7 @@ class TX: ...@@ -90,7 +90,7 @@ class TX:
self.confirms = b"" self.confirms = b""
self.tx_sent = False self.tx_sent = False
def genMixConfirm(self, keys): def gen_mix_confirm(self, keys):
message = { message = {
"document": "gmixer-mixconfirm1", "document": "gmixer-mixconfirm1",
"sender_pubkey": self.sender_pubkey, "sender_pubkey": self.sender_pubkey,
...@@ -152,14 +152,14 @@ def load_txs(db_txs, pool, tx_in_index, tx_out_index): ...@@ -152,14 +152,14 @@ def load_txs(db_txs, pool, tx_in_index, tx_out_index):
tx_in_index[tx.in_seeds[1]] = tx tx_in_index[tx.in_seeds[1]] = tx
tx_out_index[tx.out_seeds[1]] = tx tx_out_index[tx.out_seeds[1]] = tx
utils.logPrint("Loaded "+str(len(pool))+" txs", utils.LOG_TRACE) utils.logprint("Loaded "+str(len(pool))+" txs", utils.LOG_TRACE)
def save_txs(db_txs, pool): def save_txs(db_txs, pool):
for tx in pool: for tx in pool:
tx.export_ubjson(db_txs) tx.export_ubjson(db_txs)
# Read ini config file # Read ini config file
def readConfig(cdir, conf_overwrite={}): def read_config(cdir, conf_overwrite={}):
if not os.path.isfile(cdir+"/config.json"): if not os.path.isfile(cdir+"/config.json"):
configfile = open(cdir+"/config.json", "w") configfile = open(cdir+"/config.json", "w")
configfile.write("{}") configfile.write("{}")
...@@ -169,7 +169,7 @@ def readConfig(cdir, conf_overwrite={}): ...@@ -169,7 +169,7 @@ def readConfig(cdir, conf_overwrite={}):
try: try:
conf = json.load(configfile) conf = json.load(configfile)
except json.JSONDecodeError: except json.JSONDecodeError:
utils.logPrint("Config: bad JSON => abort", utils.LOG_ERROR) utils.logprint("Config: bad JSON => abort", utils.LOG_ERROR)
exit(1) exit(1)
conf.setdefault("server", {}) conf.setdefault("server", {})
...@@ -227,7 +227,7 @@ class ServerThread(Thread): ...@@ -227,7 +227,7 @@ class ServerThread(Thread):
self.sock.settimeout(5) self.sock.settimeout(5)
self.sock.bind(server_addr) self.sock.bind(server_addr)
self.sock.listen(1) self.sock.listen(1)
utils.logPrint("Server started at "+str(server_addr), utils.LOG_INFO) utils.logprint("Server started at "+str(server_addr), utils.LOG_INFO)
while self.work: while self.work:
try: try:
...@@ -275,7 +275,7 @@ class ServerThread(Thread): ...@@ -275,7 +275,7 @@ class ServerThread(Thread):
try: try:
url = httpreq[0].split(b" ")[1].decode().split("/") url = httpreq[0].split(b" ")[1].decode().split("/")
except IndexError: except IndexError:
sendResponse(client, "400 Bad Request", {"error": "bad_http"}) send_response(client, "400 Bad Request", {"error": "bad_http"})
continue continue
while "" in url: while "" in url:
url.remove("") url.remove("")
...@@ -297,26 +297,26 @@ class ServerThread(Thread): ...@@ -297,26 +297,26 @@ class ServerThread(Thread):
in_amount = int(utils.getargv("mix", "", 2, url)) in_amount = int(utils.getargv("mix", "", 2, url))
in_base = int(utils.getargv("mix", "", 3, url)) in_base = int(utils.getargv("mix", "", 3, url))
except ValueError: except ValueError:
sendResponse(client, "401 Unauthorized", {"error": "bad_amount_base"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_amount_base"}, resp_format)
continue continue
send_confirm = not "client" in url send_confirm = not "client" in url
try: try:
sender_keys = PublicKey(sender_pubkey) sender_keys = PublicKey(sender_pubkey)
except ValueError: except ValueError:
sendResponse(client, "401 Unauthorized", {"error": "bad_sender_pubkey"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_sender_pubkey"}, resp_format)
continue continue
try: try:
raw = libnacl.sign.Verifier(sender_keys.hex_pk()).verify(content) # Verify raw = libnacl.sign.Verifier(sender_keys.hex_pk()).verify(content) # Verify
except ValueError: except ValueError:
sendResponse(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format)
continue continue
try: try:
data = self.keys.decrypt_seal(raw[32:]) # Decrypt data = self.keys.decrypt_seal(raw[32:]) # Decrypt
except libnacl.CryptError: except libnacl.CryptError:
sendResponse(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format) send_response(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format)
continue continue
try: try:
...@@ -328,7 +328,7 @@ class ServerThread(Thread): ...@@ -328,7 +328,7 @@ class ServerThread(Thread):
assert "message" in data and type(data["message"]) == bytes assert "message" in data and type(data["message"]) == bytes
assert (data["message"] == b"" and type(data["out_seeds"][2]) == bytes and len(data["out_seeds"][2]) == 32) or (data["message"] != b"" and data["out_seeds"][2] == None) assert (data["message"] == b"" and type(data["out_seeds"][2]) == bytes and len(data["out_seeds"][2]) == 32) or (data["message"] != b"" and data["out_seeds"][2] == None)
except (ubjson.decoder.DecoderException, AssertionError): except (ubjson.decoder.DecoderException, AssertionError):
sendResponse(client, "403 Forbidden", {"error": "bad_ubjson"}, resp_format) send_response(client, "403 Forbidden", {"error": "bad_ubjson"}, resp_format)
continue continue
receiver_pubkey = data["receiver"] # receiver pubkey receiver_pubkey = data["receiver"] # receiver pubkey
...@@ -344,13 +344,13 @@ class ServerThread(Thread): ...@@ -344,13 +344,13 @@ class ServerThread(Thread):
try: try:
PublicKey(receiver_pubkey) PublicKey(receiver_pubkey)
except ValueError: except ValueError:
sendResponse(client, "403 Forbidden", {"error": "bad_rec_pubkey"}, resp_format) send_response(client, "403 Forbidden", {"error": "bad_rec_pubkey"}, resp_format)
continue continue
try: try:
PublicKey(onetime_pubkey) PublicKey(onetime_pubkey)
except ValueError: except ValueError:
sendResponse(client, "403 Forbidden", {"error": "bad_onetime_pubkey"}, resp_format) send_response(client, "403 Forbidden", {"error": "bad_onetime_pubkey"}, resp_format)
continue continue
# Save tx in pool # Save tx in pool
...@@ -359,7 +359,7 @@ class ServerThread(Thread): ...@@ -359,7 +359,7 @@ class ServerThread(Thread):
last_node = len(message) == 0 last_node = len(message) == 0
tx.need_send = not last_node tx.need_send = not last_node
tx.can_confirm = last_node tx.can_confirm = last_node
utils.logPrint("TX "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE) utils.logprint("TX "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE)
self.tx_out_index[out_seeds[1]] = tx self.tx_out_index[out_seeds[1]] = tx
self.tx_in_index[in_seeds[1]] = tx self.tx_in_index[in_seeds[1]] = tx
self.pool.append(tx) self.pool.append(tx)
...@@ -372,21 +372,21 @@ class ServerThread(Thread): ...@@ -372,21 +372,21 @@ class ServerThread(Thread):
try: try:
out_seed1 = bytes.fromhex(utils.getargv("confirm", "", 2, url)) out_seed1 = bytes.fromhex(utils.getargv("confirm", "", 2, url))
except ValueError: except ValueError:
sendResponse(client, "401 Unauthorized", {"error": "bad_url"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_url"}, resp_format)
continue continue
if not out_seed1 in self.tx_out_index: if not out_seed1 in self.tx_out_index:
sendResponse(client, "404 Not Found", {"error": "unknown_tx"}, resp_format) send_response(client, "404 Not Found", {"error": "unknown_tx"}, resp_format)
continue continue
tx = self.tx_out_index[out_seed1] tx = self.tx_out_index[out_seed1]
if len(tx.confirms) > 0 or tx.can_confirm or not tx.need_confirm or tx.need_send: if len(tx.confirms) > 0 or tx.can_confirm or not tx.need_confirm or tx.need_send:
sendResponse(client, "403 Forbidden", {"error": "cannot_confirm"}, resp_format) send_response(client, "403 Forbidden", {"error": "cannot_confirm"}, resp_format)
continue continue
if receiver_pubkey != tx.receiver_pubkey: if receiver_pubkey != tx.receiver_pubkey:
sendResponse(client, "401 Unauthorized", {"error": "bad_rec_pubkey"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_rec_pubkey"}, resp_format)
continue continue
receiver_keys = PublicKey(tx.receiver_pubkey) receiver_keys = PublicKey(tx.receiver_pubkey)
...@@ -394,23 +394,23 @@ class ServerThread(Thread): ...@@ -394,23 +394,23 @@ class ServerThread(Thread):
try: try:
data = libnacl.sign.Verifier(receiver_keys.hex_pk()).verify(content) # Verify data = libnacl.sign.Verifier(receiver_keys.hex_pk()).verify(content) # Verify
except ValueError: except ValueError:
sendResponse(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format)
continue continue
try: try:
data = self.keys.decrypt_seal(data) # Decrypt data = self.keys.decrypt_seal(data) # Decrypt
except libnacl.CryptError: except libnacl.CryptError:
sendResponse(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format) send_response(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format)
continue continue
if data[:32] != tx.out_seeds[1] or len(data) < 64: if data[:32] != tx.out_seeds[1] or len(data) < 64:
sendResponse(client, "401 Unauthorized", {"error": "bad_seed"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_seed"}, resp_format)
continue continue
tx.confirms = data[64:]# TODO check size tx.confirms = data[64:]# TODO check size
tx.out_seeds[2] = data[32:64] tx.out_seeds[2] = data[32:64]
utils.logPrint("Rec confirm "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE) utils.logprint("Rec confirm "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE)
tx.can_confirm = True tx.can_confirm = True
resp["confirm_ok"] = tx.out_seeds[2] resp["confirm_ok"] = tx.out_seeds[2]
...@@ -420,28 +420,28 @@ class ServerThread(Thread): ...@@ -420,28 +420,28 @@ class ServerThread(Thread):
try: try:
in_seed1 = bytes.fromhex(utils.getargv("getconfirm", "", 2, url)) in_seed1 = bytes.fromhex(utils.getargv("getconfirm", "", 2, url))
except ValueError: except ValueError:
sendResponse(client, "401 Unauthorized", {"error": "bad_url"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_url"}, resp_format)
continue continue
if not in_seed1 in self.tx_in_index: if not in_seed1 in self.tx_in_index:
sendResponse(client, "404 Not Found", {"error": "unknown_tx"}, resp_format) send_response(client, "404 Not Found", {"error": "unknown_tx"}, resp_format)
continue continue
tx = self.tx_in_index[in_seed1] tx = self.tx_in_index[in_seed1]
if not tx.can_confirm or not tx.need_confirm or tx.need_send: if not tx.can_confirm or not tx.need_confirm or tx.need_send:
sendResponse(client, "403 Forbidden", {"error": "cannot_confirm"}, resp_format) send_response(client, "403 Forbidden", {"error": "cannot_confirm"}, resp_format)
continue continue
if sender_pubkey != tx.sender_pubkey: if sender_pubkey != tx.sender_pubkey:
sendResponse(client, "401 Unauthorized", {"error": "bad_rec_pubkey"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_rec_pubkey"}, resp_format)
continue continue
message = tx.genMixConfirm(self.keys) message = tx.gen_mix_confirm(self.keys)
resp["confirm"] = message resp["confirm"] = message
tx.need_confirm = False tx.need_confirm = False
tx.export_ubjson(self.db_txs) tx.export_ubjson(self.db_txs)
utils.logPrint("Confirmed "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE) utils.logprint("Confirmed "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE)
if "list" in url: if "list" in url:
peers_list = [] peers_list = []
...@@ -454,22 +454,22 @@ class ServerThread(Thread): ...@@ -454,22 +454,22 @@ class ServerThread(Thread):
try: try:
new_keys = PublicKey(new_pubkey) new_keys = PublicKey(new_pubkey)
except ValueError: except ValueError:
sendResponse(client, "401 Unauthorized", {"error": "bad_pubkey"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_pubkey"}, resp_format)
continue continue
try: try:
message = libnacl.sign.Verifier(new_keys.hex_pk()).verify(content) # Verify message = libnacl.sign.Verifier(new_keys.hex_pk()).verify(content) # Verify
except ValueError: except ValueError:
sendResponse(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format) send_response(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format)
continue continue
try: try:
message = self.keys.decrypt_seal(message) # Decrypt message = self.keys.decrypt_seal(message) # Decrypt
except libnacl.CryptError: except libnacl.CryptError:
sendResponse(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format) send_response(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format)
continue continue
try: try:
message = ubjson.loadb(message) message = ubjson.loadb(message)
except ubjson.decoder.DecoderException: except ubjson.decoder.DecoderException:
sendResponse(client, "400 Bad Request", {"error": "bad_ubjson"}, resp_format) send_response(client, "400 Bad Request", {"error": "bad_ubjson"}, resp_format)
continue continue
if new_pubkey == message["pubkey"]: if new_pubkey == message["pubkey"]:
...@@ -477,13 +477,13 @@ class ServerThread(Thread): ...@@ -477,13 +477,13 @@ class ServerThread(Thread):
peer = utils.Peer(new_pubkey, message["host"], message["port"], True) peer = utils.Peer(new_pubkey, message["host"], message["port"], True)
self.peers.append(peer) self.peers.append(peer)
self.peers_index[new_pubkey] = peer self.peers_index[new_pubkey] = peer
utils.logPrint("Add "+str(peer), utils.LOG_TRACE) utils.logprint("Add "+str(peer), utils.LOG_TRACE)
else: else:
self.peers_index[new_pubkey].up = True self.peers_index[new_pubkey].up = True
utils.logPrint("Up "+str(peer), utils.LOG_TRACE) utils.logprint("Up "+str(peer), utils.LOG_TRACE)
# Send response # Send response
sendResponse(client, "200 OK", resp, resp_format) send_response(client, "200 OK", resp, resp_format)
self.sock.close() self.sock.close()
def stop(self): def stop(self):
...@@ -506,8 +506,8 @@ class ClientThread(Thread): ...@@ -506,8 +506,8 @@ class ClientThread(Thread):
self.bma_endpoints = ["BMAS "+host for host in conf["client"]["bma_hosts"]] self.bma_endpoints = ["BMAS "+host for host in conf["client"]["bma_hosts"]]
self.work = True self.work = True
def detectPeers(self):# Check known peers and ask them for their known peer list def detect_peers(self):# Check known peers and ask them for their known peer list
utils.logPrint("Start peers detection", utils.LOG_TRACE) utils.logprint("Start peers detection", utils.LOG_TRACE)
modified = True modified = True
asked = [] asked = []
...@@ -527,42 +527,42 @@ class ClientThread(Thread): ...@@ -527,42 +527,42 @@ class ClientThread(Thread):
}) })
message = peer.keys.encrypt_seal(message) # Encrypt message = peer.keys.encrypt_seal(message) # Encrypt
message = self.keys.sign(message) # Sign message = self.keys.sign(message) # Sign
utils.logPrint("Ask "+str(peer), utils.LOG_TRACE) utils.logprint("Ask "+str(peer), utils.LOG_TRACE)
try: try:
header, content = utils.sdata((peer.host, peer.port), "POST", "/list/new/"+self.keys.pubkey, message, proxy=self.conf["client"]["proxy"], proxy_onion_only=self.conf["client"]["proxy_onion_only"]) # Send header, content = utils.sdata((peer.host, peer.port), "POST", "/list/new/"+self.keys.pubkey, message, proxy=self.conf["client"]["proxy"], proxy_onion_only=self.conf["client"]["proxy_onion_only"]) # Send
except (ConnectionRefusedError, socks.GeneralProxyError, socket.gaierror, socket.timeout): except (ConnectionRefusedError, socks.GeneralProxyError, socket.gaierror, socket.timeout):
peer.up = False peer.up = False
utils.logPrint("Down "+str(peer), utils.LOG_TRACE) utils.logprint("Down "+str(peer), utils.LOG_TRACE)
continue continue
peer.up = True peer.up = True
utils.logPrint("Up "+str(peer), utils.LOG_TRACE) utils.logprint("Up "+str(peer), utils.LOG_TRACE)
try: try:
message = ubjson.loadb(content) message = ubjson.loadb(content)
assert "peers" in message assert "peers" in message
assert type(message["peers"]) == list assert type(message["peers"]) == list
except (ubjson.decoder.DecoderException, AssertionError): except (ubjson.decoder.DecoderException, AssertionError):
utils.logPrint("Bad json from "+str(peer), utils.LOG_ERROR) utils.logprint("Bad json from "+str(peer), utils.LOG_ERROR)
continue continue
for i_peer in message["peers"]: for i_peer in message["peers"]:
try: try:
assert "pubkey" in i_peer and "host" in i_peer and "port" in i_peer assert "pubkey" in i_peer and "host" in i_peer and "port" in i_peer
int(i_peer["port"]) int(i_peer["port"])
except (AssertionError, ValueError): except (AssertionError, ValueError):
utils.logPrint("Bad json from "+str(peer), utils.LOG_ERROR) utils.logprint("Bad json from "+str(peer), utils.LOG_ERROR)
continue continue
if i_peer["pubkey"] in self.peers_index or i_peer["pubkey"] == self.keys.pubkey: if i_peer["pubkey"] in self.peers_index or i_peer["pubkey"] == self.keys.pubkey:
continue continue
try: try:
new_peer = utils.Peer(i_peer["pubkey"], i_peer["host"], i_peer["port"], None) new_peer = utils.Peer(i_peer["pubkey"], i_peer["host"], i_peer["port"], None)
except ValueError: except ValueError:
utils.logPrint("Bad pubkey from "+str(peer), utils.LOG_ERROR) utils.logprint("Bad pubkey from "+str(peer), utils.LOG_ERROR)
continue continue
self.peers.append(new_peer) self.peers.append(new_peer)
self.peers_index[new_peer.pubkey] = new_peer self.peers_index[new_peer.pubkey] = new_peer
modified = True modified = True
utils.logPrint("Add "+str(new_peer), utils.LOG_TRACE) utils.logprint("Add "+str(new_peer), utils.LOG_TRACE)
utils.logPrint("Finished peers detection", utils.LOG_TRACE) utils.logprint("Finished peers detection", utils.LOG_TRACE)
async def mix(self): async def mix(self):
can_mix = False can_mix = False
...@@ -573,7 +573,7 @@ class ClientThread(Thread): ...@@ -573,7 +573,7 @@ class ClientThread(Thread):
if not can_mix: if not can_mix:
return return
utils.logPrint("Starting mix", utils.LOG_TRACE) utils.logprint("Starting mix", utils.LOG_TRACE)
t = time.time() t = time.time()
client = None client = None
for bma_endpoint in self.bma_endpoints: for bma_endpoint in self.bma_endpoints:
...@@ -582,11 +582,11 @@ class ClientThread(Thread): ...@@ -582,11 +582,11 @@ class ClientThread(Thread):
await client(bma.node.summary) await client(bma.node.summary)
break break
except: except:
utils.logPrint("BMA down: "+bma_endpoint, utils.LOG_WARN) utils.logprint("BMA down: "+bma_endpoint, utils.LOG_WARN)
await client.close() await client.close()
client = None client = None
if client: if client:
utils.logPrint("BMA up: "+bma_endpoint, utils.LOG_TRACE) utils.logprint("BMA up: "+bma_endpoint, utils.LOG_TRACE)
ready_txs = [] ready_txs = []
# Get txs history # Get txs history
...@@ -624,24 +624,24 @@ class ClientThread(Thread): ...@@ -624,24 +624,24 @@ class ClientThread(Thread):
random.shuffle(txs) random.shuffle(txs)
for tx in txs: for tx in txs:
try: try:
utils.sendTransaction(self.keys, tx.receiver_pubkey, tx.out_amount, utils.gen_comment(tx.out_seeds)) utils.send_transaction(self.keys, tx.receiver_pubkey, tx.out_amount, utils.gen_comment(tx.out_seeds))
tx.tx_sent = True tx.tx_sent = True
tx.export_ubjson(self.db_txs) tx.export_ubjson(self.db_txs)
except socket.timeout: except socket.timeout:
utils.logPrint("Error when sending tx: timeout", utils.LOG_ERROR) utils.logprint("Error when sending tx: timeout", utils.LOG_ERROR)
except Exception as e: except Exception as e:
utils.logPrint("Error when sending tx: " + str(e), utils.LOG_ERROR) utils.logprint("Error when sending tx: " + str(e), utils.LOG_ERROR)
else: else:
utils.logPrint("Not enough ready txs to mix ("+str(amount)+"u) (only "+str(len(txs))+")", utils.LOG_TRACE) utils.logprint("Not enough ready txs to mix ("+str(amount)+"u) (only "+str(len(txs))+")", utils.LOG_TRACE)
utils.logPrint("Mix finished", utils.LOG_TRACE) utils.logprint("Mix finished", utils.LOG_TRACE)
else: else:
utils.logPrint("All BMA endpoints down: cannot mix!", utils.LOG_ERROR) utils.logprint("All BMA endpoints down: cannot mix!", utils.LOG_ERROR)
def run(self): def run(self):
asyncio.new_event_loop().run_until_complete(self.startClient()) asyncio.new_event_loop().run_until_complete(self.start_client())
async def startClient(self): async def start_client(self):
next_peers_detection = 0 next_peers_detection = 0
next_mix = time.time() + self.conf["mix"]["mix_interval"] next_mix = time.time() + self.conf["mix"]["mix_interval"]
...@@ -650,7 +650,7 @@ class ClientThread(Thread): ...@@ -650,7 +650,7 @@ class ClientThread(Thread):
# Detect peers # Detect peers
if t > next_peers_detection: if t > next_peers_detection:
self.detectPeers() self.detect_peers()
next_peers_detection = time.time()+120 next_peers_detection = time.time()+120
# Mix # Mix
...@@ -661,7 +661,7 @@ class ClientThread(Thread): ...@@ -661,7 +661,7 @@ class ClientThread(Thread):
for tx in self.pool: for tx in self.pool:
if tx.need_send: if tx.need_send:
utils.logPrint("Send "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE) utils.logprint("Send "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE)
if tx.receiver_pubkey in self.peers_index: if tx.receiver_pubkey in self.peers_index:
peer = self.peers_index[tx.receiver_pubkey] peer = self.peers_index[tx.receiver_pubkey]
message = self.keys.sign(tx.out_seeds[1] + tx.message) # Sign message = self.keys.sign(tx.out_seeds[1] + tx.message) # Sign
...@@ -673,22 +673,22 @@ class ClientThread(Thread): ...@@ -673,22 +673,22 @@ class ClientThread(Thread):
tx.need_send = False tx.need_send = False
tx.export_ubjson(self.db_txs) tx.export_ubjson(self.db_txs)
peer.up = True peer.up = True
utils.logPrint("Sent "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE) utils.logprint("Sent "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE)
utils.logPrint("Up "+str(peer), utils.LOG_TRACE) utils.logprint("Up "+str(peer), utils.LOG_TRACE)
except (ConnectionRefusedError, socks.GeneralProxyError, socket.gaierror, socket.timeout): except (ConnectionRefusedError, socks.GeneralProxyError, socket.gaierror, socket.timeout):
peer.up = False peer.up = False
utils.logPrint("Down "+str(peer), utils.LOG_TRACE) utils.logprint("Down "+str(peer), utils.LOG_TRACE)
except (ubjson.decoder.DecoderException, KeyError, AssertionError): except (ubjson.decoder.DecoderException, KeyError, AssertionError):
utils.logPrint("Error: bad response from "+str(peer), utils.LOG_WARN) utils.logprint("Error: bad response from "+str(peer), utils.LOG_WARN)
else: else:
utils.logPrint("Unknown peer: "+tx.receiver_pubkey, utils.LOG_WARN) utils.logprint("Unknown peer: "+tx.receiver_pubkey, utils.LOG_WARN)
elif tx.can_confirm and tx.need_confirm and tx.send_confirm: elif tx.can_confirm and tx.need_confirm and tx.send_confirm:
utils.logPrint("Confirm "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE) utils.logprint("Confirm "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE)
if tx.sender_pubkey in self.peers_index: if tx.sender_pubkey in self.peers_index:
peer = self.peers_index[tx.sender_pubkey] peer = self.peers_index[tx.sender_pubkey]
message = tx.genMixConfirm(self.keys) message = tx.gen_mix_confirm(self.keys)
try: try:
header, content = utils.sdata((peer.host, peer.port), "POST", "/confirm/"+self.keys.pubkey+"/"+tx.in_seeds[1].hex(), message, proxy=self.conf["client"]["proxy"], proxy_onion_only=self.conf["client"]["proxy_onion_only"]) header, content = utils.sdata((peer.host, peer.port), "POST", "/confirm/"+self.keys.pubkey+"/"+tx.in_seeds[1].hex(), message, proxy=self.conf["client"]["proxy"], proxy_onion_only=self.conf["client"]["proxy_onion_only"])
...@@ -697,16 +697,16 @@ class ClientThread(Thread): ...@@ -697,16 +697,16 @@ class ClientThread(Thread):
tx.need_confirm = False tx.need_confirm = False
tx.export_ubjson(self.db_txs) tx.export_ubjson(self.db_txs)
peer.up = True peer.up = True
utils.logPrint("Confirmed "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE) utils.logprint("Confirmed "+tx.sender_pubkey[:8]+" -> "+tx.receiver_pubkey[:8]+" = "+str(tx.in_amount)+":"+str(tx.in_base)+" -> "+str(tx.out_amount)+":"+str(tx.out_base), utils.LOG_TRACE)
utils.logPrint("Up "+str(peer), utils.LOG_TRACE) utils.logprint("Up "+str(peer), utils.LOG_TRACE)
except (ConnectionRefusedError, socks.GeneralProxyError, socket.gaierror, socket.timeout): except (ConnectionRefusedError, socks.GeneralProxyError, socket.gaierror, socket.timeout):
peer.up = False peer.up = False
utils.logPrint("Down "+str(peer), utils.LOG_TRACE) utils.logprint("Down "+str(peer), utils.LOG_TRACE)
except (ubjson.decoder.DecoderException, KeyError, AssertionError): except (ubjson.decoder.DecoderException, KeyError, AssertionError):
utils.logPrint("Error: bad response from "+str(peer), utils.LOG_WARN) utils.logprint("Error: bad response from "+str(peer), utils.LOG_WARN)
else: else:
utils.logPrint("Unknown peer: "+tx.sender_pubkey, utils.LOG_WARN) utils.logprint("Unknown peer: "+tx.sender_pubkey, utils.LOG_WARN)
# Remove expired requests # Remove expired requests
expire_txs = [] expire_txs = []
...@@ -720,11 +720,11 @@ class ClientThread(Thread): ...@@ -720,11 +720,11 @@ class ClientThread(Thread):
self.db_txs.delete(tx.in_seeds[2]) self.db_txs.delete(tx.in_seeds[2])
self.pool.remove(tx) self.pool.remove(tx)
if len(expire_txs) > 0: if len(expire_txs) > 0:
utils.logPrint("Removed "+str(len(expire_txs))+" expired txs", utils.LOG_TRACE) utils.logprint("Removed "+str(len(expire_txs))+" expired txs", utils.LOG_TRACE)
time.sleep(5) time.sleep(5)
def getCredentials(conf): def get_credentials(conf):
salt = conf["crypto"]["id_salt"] salt = conf["crypto"]["id_salt"]
if salt == "": if salt == "":
salt = getpass.getpass("Enter your passphrase (salt): ") salt = getpass.getpass("Enter your passphrase (salt): ")
...@@ -736,8 +736,8 @@ def getCredentials(conf): ...@@ -736,8 +736,8 @@ def getCredentials(conf):
# Main function # Main function
def main(): def main():
# Load conf & peers # Load conf & peers
conf = readConfig(DIR) conf = read_config(DIR)
peers, peers_index = utils.readPeers(DIR) peers, peers_index = utils.read_peers(DIR)
# Load txs # Load txs
pool = [] pool = []
...@@ -747,9 +747,9 @@ def main(): ...@@ -747,9 +747,9 @@ def main():
load_txs(db_txs, pool, tx_in_index, tx_out_index) load_txs(db_txs, pool, tx_in_index, tx_out_index)
# Get private key # Get private key
salt, password = getCredentials(conf) salt, password = get_credentials(conf)
keys = SigningKey.from_credentials(salt, password) keys = SigningKey.from_credentials(salt, password)
utils.logPrint("Pubkey: "+keys.pubkey, utils.LOG_INFO) utils.logprint("Pubkey: "+keys.pubkey, utils.LOG_INFO)
# Start threads # Start threads
clientThread = ClientThread(conf, peers, peers_index, keys, pool, tx_in_index, tx_out_index, db_txs) clientThread = ClientThread(conf, peers, peers_index, keys, pool, tx_in_index, tx_out_index, db_txs)
...@@ -763,7 +763,7 @@ def main(): ...@@ -763,7 +763,7 @@ def main():
while True: while True:
input() input()
except KeyboardInterrupt: except KeyboardInterrupt:
utils.logPrint("Stopping (^C)...", utils.LOG_INFO) utils.logprint("Stopping (^C)...", utils.LOG_INFO)
# Stop threads # Stop threads
serverThread.stop() serverThread.stop()
...@@ -772,7 +772,7 @@ def main(): ...@@ -772,7 +772,7 @@ def main():
clientThread.join() clientThread.join()
# Save # Save
utils.writePeers(DIR, peers) utils.write_peers(DIR, peers)
save_txs(db_txs, pool) save_txs(db_txs, pool)
db_txs.close() db_txs.close()
...@@ -793,23 +793,23 @@ if __name__ == "__main__": ...@@ -793,23 +793,23 @@ if __name__ == "__main__":
PUBLIC_HOST = subprocess.run(['curl', '-4', 'https://zettascript.org/tux/ip/'], stdout=subprocess.PIPE).stdout.decode("utf-8") PUBLIC_HOST = subprocess.run(['curl', '-4', 'https://zettascript.org/tux/ip/'], stdout=subprocess.PIPE).stdout.decode("utf-8")
print("Public host: " + PUBLIC_HOST) print("Public host: " + PUBLIC_HOST)
conf_overwrite["server.public_host"] = PUBLIC_HOST conf_overwrite["server.public_host"] = PUBLIC_HOST
readConfig(DIR, conf_overwrite) read_config(DIR, conf_overwrite)
if "-s" in sys.argv: if "-s" in sys.argv:
main() main()
elif "-i" in sys.argv: elif "-i" in sys.argv:
conf = readConfig(DIR) conf = read_config(DIR)
utils.readPeers(DIR) utils.read_peers(DIR)
elif "-I" in sys.argv: elif "-I" in sys.argv:
ID_SALT, ID_PASSWORD = gen_keys() ID_SALT, ID_PASSWORD = gen_keys()
conf = readConfig(DIR) conf = read_config(DIR)
utils.readPeers(DIR) utils.read_peers(DIR)
elif "-k" in sys.argv: elif "-k" in sys.argv:
conf = readConfig(DIR) conf = read_config(DIR)
salt, password = getCredentials(conf) salt, password = get_credentials(conf)
keys = SigningKey.from_credentials(salt, password) keys = SigningKey.from_credentials(salt, password)
print(keys.pubkey) print(keys.pubkey)
......
...@@ -109,7 +109,7 @@ LOG_ERROR = 8 ...@@ -109,7 +109,7 @@ LOG_ERROR = 8
LOGMSG_TYPES = {LOG_INFO:"\033[96minfo\033[0m", LOG_TRACE:"\033[39mtrace\033[0m", LOG_WARN:"\033[93mwarn\033[0m", LOG_ERROR:"\033[91merror\033[0m"} LOGMSG_TYPES = {LOG_INFO:"\033[96minfo\033[0m", LOG_TRACE:"\033[39mtrace\033[0m", LOG_WARN:"\033[93mwarn\033[0m", LOG_ERROR:"\033[91merror\033[0m"}
VERBOSITY = LOG_INFO | LOG_WARN | LOG_ERROR VERBOSITY = LOG_INFO | LOG_WARN | LOG_ERROR
def logPrint(msg:str, msgtype:int): def logprint(msg:str, msgtype:int):
if msgtype & VERBOSITY: if msgtype & VERBOSITY:
print(time.strftime("%Y-%m-%d %H:%M:%S")+" ["+LOGMSG_TYPES[msgtype]+"] "+msg) print(time.strftime("%Y-%m-%d %H:%M:%S")+" ["+LOGMSG_TYPES[msgtype]+"] "+msg)
...@@ -138,7 +138,7 @@ class Peer: ...@@ -138,7 +138,7 @@ class Peer:
return self.pubkey + " " + self.host + " " + str(self.port) return self.pubkey + " " + self.host + " " + str(self.port)
# Read peers list # Read peers list
def readPeers(cdir:str) -> (list, dict): def read_peers(cdir:str) -> (list, dict):
if not os.path.isfile(cdir+"/peers"): if not os.path.isfile(cdir+"/peers"):
open(cdir+"/peers", "w").close() open(cdir+"/peers", "w").close()
...@@ -158,13 +158,13 @@ def readPeers(cdir:str) -> (list, dict): ...@@ -158,13 +158,13 @@ def readPeers(cdir:str) -> (list, dict):
return peers, peers_index return peers, peers_index
# Save peers list # Save peers list
def writePeers(cdir:str, peers:list): def write_peers(cdir:str, peers:list):
peersfile = open(cdir+"/peers", "w") peersfile = open(cdir+"/peers", "w")
for peer in peers: for peer in peers:
peersfile.write(peer.export_str()+"\n") peersfile.write(peer.export_str()+"\n")
peersfile.close() peersfile.close()
def sendTransaction(sender_keys:SigningKey, receiver_pubkey:str, amount:int, comment:str): def send_transaction(sender_keys:SigningKey, receiver_pubkey:str, amount:int, comment:str):
sender_amount = silkaj.money.get_amount_from_pubkey(sender_keys.pubkey)[0] sender_amount = silkaj.money.get_amount_from_pubkey(sender_keys.pubkey)[0]
assert sender_amount >= amount, "not enough money" assert sender_amount >= amount, "not enough money"
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment