diff --git a/client.py b/client.py index ca0135eb54462ec51468bbb2091eb7d0d4aa6751..368e23be804fbcdb8111ca70a304c8aba5de7ffb 100644 --- a/client.py +++ b/client.py @@ -253,17 +253,17 @@ def mix(db_txs, amount, base, sender, path, host, proxy=None, proxy_onion_only=F if send_tx: 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 db_txs.put(comment_seeds[0][1], PublicKey(sender.pubkey).encrypt_seal(ubjson.dumpb(message))) except socket.timeout: - logPrint("Error when sending tx: timeout", LOG_ERROR) + logprint("Error when sending tx: timeout", LOG_ERROR) except Exception as e: - logPrint("Error when sending tx: " + str(e), LOG_ERROR) + logprint("Error when sending tx: " + str(e), LOG_ERROR) 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: 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": @@ -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) - 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)) diff --git a/server.py b/server.py index cf424c25688346823fac7c78530598e2af646ca8..36b72fc5ab1fc8859156b6f9436a9dac18295929 100644 --- a/server.py +++ b/server.py @@ -55,7 +55,7 @@ MIX_INTERVAL = 60 MIX_MIN_TXS = 5 # minimum amount of txs to mix 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": content_raw = ubjson.dumpb(resp) mime = "application/ubjson" @@ -90,7 +90,7 @@ class TX: self.confirms = b"" self.tx_sent = False - def genMixConfirm(self, keys): + def gen_mix_confirm(self, keys): message = { "document": "gmixer-mixconfirm1", "sender_pubkey": self.sender_pubkey, @@ -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_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): for tx in pool: tx.export_ubjson(db_txs) # Read ini config file -def readConfig(cdir, conf_overwrite={}): +def read_config(cdir, conf_overwrite={}): if not os.path.isfile(cdir+"/config.json"): configfile = open(cdir+"/config.json", "w") configfile.write("{}") @@ -169,7 +169,7 @@ def readConfig(cdir, conf_overwrite={}): try: conf = json.load(configfile) except json.JSONDecodeError: - utils.logPrint("Config: bad JSON => abort", utils.LOG_ERROR) + utils.logprint("Config: bad JSON => abort", utils.LOG_ERROR) exit(1) conf.setdefault("server", {}) @@ -227,7 +227,7 @@ class ServerThread(Thread): self.sock.settimeout(5) self.sock.bind(server_addr) 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: try: @@ -275,7 +275,7 @@ class ServerThread(Thread): try: url = httpreq[0].split(b" ")[1].decode().split("/") except IndexError: - sendResponse(client, "400 Bad Request", {"error": "bad_http"}) + send_response(client, "400 Bad Request", {"error": "bad_http"}) continue while "" in url: url.remove("") @@ -297,26 +297,26 @@ class ServerThread(Thread): in_amount = int(utils.getargv("mix", "", 2, url)) in_base = int(utils.getargv("mix", "", 3, url)) except ValueError: - sendResponse(client, "401 Unauthorized", {"error": "bad_amount_base"}, resp_format) + send_response(client, "401 Unauthorized", {"error": "bad_amount_base"}, resp_format) continue send_confirm = not "client" in url try: sender_keys = PublicKey(sender_pubkey) except ValueError: - sendResponse(client, "401 Unauthorized", {"error": "bad_sender_pubkey"}, resp_format) + send_response(client, "401 Unauthorized", {"error": "bad_sender_pubkey"}, resp_format) continue try: raw = libnacl.sign.Verifier(sender_keys.hex_pk()).verify(content) # Verify except ValueError: - sendResponse(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format) + send_response(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format) continue try: data = self.keys.decrypt_seal(raw[32:]) # Decrypt except libnacl.CryptError: - sendResponse(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format) + send_response(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format) continue try: @@ -328,7 +328,7 @@ class ServerThread(Thread): 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) 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 receiver_pubkey = data["receiver"] # receiver pubkey @@ -344,13 +344,13 @@ class ServerThread(Thread): try: PublicKey(receiver_pubkey) except ValueError: - sendResponse(client, "403 Forbidden", {"error": "bad_rec_pubkey"}, resp_format) + send_response(client, "403 Forbidden", {"error": "bad_rec_pubkey"}, resp_format) continue try: PublicKey(onetime_pubkey) except ValueError: - sendResponse(client, "403 Forbidden", {"error": "bad_onetime_pubkey"}, resp_format) + send_response(client, "403 Forbidden", {"error": "bad_onetime_pubkey"}, resp_format) continue # Save tx in pool @@ -359,7 +359,7 @@ class ServerThread(Thread): last_node = len(message) == 0 tx.need_send = not 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_in_index[in_seeds[1]] = tx self.pool.append(tx) @@ -372,21 +372,21 @@ class ServerThread(Thread): try: out_seed1 = bytes.fromhex(utils.getargv("confirm", "", 2, url)) except ValueError: - sendResponse(client, "401 Unauthorized", {"error": "bad_url"}, resp_format) + send_response(client, "401 Unauthorized", {"error": "bad_url"}, resp_format) continue 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 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: - sendResponse(client, "403 Forbidden", {"error": "cannot_confirm"}, resp_format) + send_response(client, "403 Forbidden", {"error": "cannot_confirm"}, resp_format) continue 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 receiver_keys = PublicKey(tx.receiver_pubkey) @@ -394,23 +394,23 @@ class ServerThread(Thread): try: data = libnacl.sign.Verifier(receiver_keys.hex_pk()).verify(content) # Verify except ValueError: - sendResponse(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format) + send_response(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format) continue try: data = self.keys.decrypt_seal(data) # Decrypt except libnacl.CryptError: - sendResponse(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format) + send_response(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format) continue 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 tx.confirms = data[64:]# TODO check size 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 resp["confirm_ok"] = tx.out_seeds[2] @@ -420,28 +420,28 @@ class ServerThread(Thread): try: in_seed1 = bytes.fromhex(utils.getargv("getconfirm", "", 2, url)) except ValueError: - sendResponse(client, "401 Unauthorized", {"error": "bad_url"}, resp_format) + send_response(client, "401 Unauthorized", {"error": "bad_url"}, resp_format) continue 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 tx = self.tx_in_index[in_seed1] 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 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 - message = tx.genMixConfirm(self.keys) + message = tx.gen_mix_confirm(self.keys) resp["confirm"] = message tx.need_confirm = False 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: peers_list = [] @@ -454,22 +454,22 @@ class ServerThread(Thread): try: new_keys = PublicKey(new_pubkey) except ValueError: - sendResponse(client, "401 Unauthorized", {"error": "bad_pubkey"}, resp_format) + send_response(client, "401 Unauthorized", {"error": "bad_pubkey"}, resp_format) continue try: message = libnacl.sign.Verifier(new_keys.hex_pk()).verify(content) # Verify except ValueError: - sendResponse(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format) + send_response(client, "401 Unauthorized", {"error": "bad_signature"}, resp_format) continue try: message = self.keys.decrypt_seal(message) # Decrypt except libnacl.CryptError: - sendResponse(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format) + send_response(client, "403 Forbidden", {"error": "bad_encryption"}, resp_format) continue try: message = ubjson.loadb(message) 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 if new_pubkey == message["pubkey"]: @@ -477,13 +477,13 @@ class ServerThread(Thread): peer = utils.Peer(new_pubkey, message["host"], message["port"], True) self.peers.append(peer) self.peers_index[new_pubkey] = peer - utils.logPrint("Add "+str(peer), utils.LOG_TRACE) + utils.logprint("Add "+str(peer), utils.LOG_TRACE) else: 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 - sendResponse(client, "200 OK", resp, resp_format) + send_response(client, "200 OK", resp, resp_format) self.sock.close() def stop(self): @@ -506,8 +506,8 @@ class ClientThread(Thread): self.bma_endpoints = ["BMAS "+host for host in conf["client"]["bma_hosts"]] self.work = True - def detectPeers(self):# Check known peers and ask them for their known peer list - utils.logPrint("Start peers detection", utils.LOG_TRACE) + def detect_peers(self):# Check known peers and ask them for their known peer list + utils.logprint("Start peers detection", utils.LOG_TRACE) modified = True asked = [] @@ -527,42 +527,42 @@ class ClientThread(Thread): }) message = peer.keys.encrypt_seal(message) # Encrypt message = self.keys.sign(message) # Sign - utils.logPrint("Ask "+str(peer), utils.LOG_TRACE) + utils.logprint("Ask "+str(peer), utils.LOG_TRACE) 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 except (ConnectionRefusedError, socks.GeneralProxyError, socket.gaierror, socket.timeout): peer.up = False - utils.logPrint("Down "+str(peer), utils.LOG_TRACE) + utils.logprint("Down "+str(peer), utils.LOG_TRACE) continue peer.up = True - utils.logPrint("Up "+str(peer), utils.LOG_TRACE) + utils.logprint("Up "+str(peer), utils.LOG_TRACE) try: message = ubjson.loadb(content) assert "peers" in message assert type(message["peers"]) == list 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 for i_peer in message["peers"]: try: assert "pubkey" in i_peer and "host" in i_peer and "port" in i_peer int(i_peer["port"]) except (AssertionError, ValueError): - utils.logPrint("Bad json from "+str(peer), utils.LOG_ERROR) + utils.logprint("Bad json from "+str(peer), utils.LOG_ERROR) continue if i_peer["pubkey"] in self.peers_index or i_peer["pubkey"] == self.keys.pubkey: continue try: new_peer = utils.Peer(i_peer["pubkey"], i_peer["host"], i_peer["port"], None) except ValueError: - utils.logPrint("Bad pubkey from "+str(peer), utils.LOG_ERROR) + utils.logprint("Bad pubkey from "+str(peer), utils.LOG_ERROR) continue self.peers.append(new_peer) self.peers_index[new_peer.pubkey] = new_peer modified = True - utils.logPrint("Add "+str(new_peer), utils.LOG_TRACE) - utils.logPrint("Finished peers detection", utils.LOG_TRACE) + utils.logprint("Add "+str(new_peer), utils.LOG_TRACE) + utils.logprint("Finished peers detection", utils.LOG_TRACE) async def mix(self): can_mix = False @@ -573,7 +573,7 @@ class ClientThread(Thread): if not can_mix: return - utils.logPrint("Starting mix", utils.LOG_TRACE) + utils.logprint("Starting mix", utils.LOG_TRACE) t = time.time() client = None for bma_endpoint in self.bma_endpoints: @@ -582,11 +582,11 @@ class ClientThread(Thread): await client(bma.node.summary) break except: - utils.logPrint("BMA down: "+bma_endpoint, utils.LOG_WARN) + utils.logprint("BMA down: "+bma_endpoint, utils.LOG_WARN) await client.close() client = None if client: - utils.logPrint("BMA up: "+bma_endpoint, utils.LOG_TRACE) + utils.logprint("BMA up: "+bma_endpoint, utils.LOG_TRACE) ready_txs = [] # Get txs history @@ -624,24 +624,24 @@ class ClientThread(Thread): random.shuffle(txs) for tx in txs: 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.export_ubjson(self.db_txs) 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: - utils.logPrint("Error when sending tx: " + str(e), utils.LOG_ERROR) + utils.logprint("Error when sending tx: " + str(e), utils.LOG_ERROR) 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: - 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): - 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_mix = time.time() + self.conf["mix"]["mix_interval"] @@ -650,7 +650,7 @@ class ClientThread(Thread): # Detect peers if t > next_peers_detection: - self.detectPeers() + self.detect_peers() next_peers_detection = time.time()+120 # Mix @@ -661,7 +661,7 @@ class ClientThread(Thread): for tx in self.pool: 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: peer = self.peers_index[tx.receiver_pubkey] message = self.keys.sign(tx.out_seeds[1] + tx.message) # Sign @@ -673,22 +673,22 @@ class ClientThread(Thread): tx.need_send = False tx.export_ubjson(self.db_txs) 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("Up "+str(peer), 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) except (ConnectionRefusedError, socks.GeneralProxyError, socket.gaierror, socket.timeout): 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): - utils.logPrint("Error: bad response from "+str(peer), utils.LOG_WARN) + utils.logprint("Error: bad response from "+str(peer), utils.LOG_WARN) 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: - 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: peer = self.peers_index[tx.sender_pubkey] - message = tx.genMixConfirm(self.keys) + message = tx.gen_mix_confirm(self.keys) 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"]) @@ -697,16 +697,16 @@ class ClientThread(Thread): tx.need_confirm = False tx.export_ubjson(self.db_txs) 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("Up "+str(peer), 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) except (ConnectionRefusedError, socks.GeneralProxyError, socket.gaierror, socket.timeout): 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): - utils.logPrint("Error: bad response from "+str(peer), utils.LOG_WARN) + utils.logprint("Error: bad response from "+str(peer), utils.LOG_WARN) else: - utils.logPrint("Unknown peer: "+tx.sender_pubkey, utils.LOG_WARN) + utils.logprint("Unknown peer: "+tx.sender_pubkey, utils.LOG_WARN) # Remove expired requests expire_txs = [] @@ -720,11 +720,11 @@ class ClientThread(Thread): self.db_txs.delete(tx.in_seeds[2]) self.pool.remove(tx) 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) -def getCredentials(conf): +def get_credentials(conf): salt = conf["crypto"]["id_salt"] if salt == "": salt = getpass.getpass("Enter your passphrase (salt): ") @@ -736,8 +736,8 @@ def getCredentials(conf): # Main function def main(): # Load conf & peers - conf = readConfig(DIR) - peers, peers_index = utils.readPeers(DIR) + conf = read_config(DIR) + peers, peers_index = utils.read_peers(DIR) # Load txs pool = [] @@ -747,9 +747,9 @@ def main(): load_txs(db_txs, pool, tx_in_index, tx_out_index) # Get private key - salt, password = getCredentials(conf) + salt, password = get_credentials(conf) keys = SigningKey.from_credentials(salt, password) - utils.logPrint("Pubkey: "+keys.pubkey, utils.LOG_INFO) + utils.logprint("Pubkey: "+keys.pubkey, utils.LOG_INFO) # Start threads clientThread = ClientThread(conf, peers, peers_index, keys, pool, tx_in_index, tx_out_index, db_txs) @@ -763,7 +763,7 @@ def main(): while True: input() except KeyboardInterrupt: - utils.logPrint("Stopping (^C)...", utils.LOG_INFO) + utils.logprint("Stopping (^C)...", utils.LOG_INFO) # Stop threads serverThread.stop() @@ -772,7 +772,7 @@ def main(): clientThread.join() # Save - utils.writePeers(DIR, peers) + utils.write_peers(DIR, peers) save_txs(db_txs, pool) db_txs.close() @@ -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") print("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: main() elif "-i" in sys.argv: - conf = readConfig(DIR) - utils.readPeers(DIR) + conf = read_config(DIR) + utils.read_peers(DIR) elif "-I" in sys.argv: ID_SALT, ID_PASSWORD = gen_keys() - conf = readConfig(DIR) - utils.readPeers(DIR) + conf = read_config(DIR) + utils.read_peers(DIR) elif "-k" in sys.argv: - conf = readConfig(DIR) - salt, password = getCredentials(conf) + conf = read_config(DIR) + salt, password = get_credentials(conf) keys = SigningKey.from_credentials(salt, password) print(keys.pubkey) diff --git a/utils.py b/utils.py index 341f07344cd973cc089c79f06d8e1280a9dbe990..af2ab28a3e10da7a1c120a72bf298ebed5e9d40a 100644 --- a/utils.py +++ b/utils.py @@ -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"} VERBOSITY = LOG_INFO | LOG_WARN | LOG_ERROR -def logPrint(msg:str, msgtype:int): +def logprint(msg:str, msgtype:int): if msgtype & VERBOSITY: print(time.strftime("%Y-%m-%d %H:%M:%S")+" ["+LOGMSG_TYPES[msgtype]+"] "+msg) @@ -138,7 +138,7 @@ class Peer: return self.pubkey + " " + self.host + " " + str(self.port) # Read peers list -def readPeers(cdir:str) -> (list, dict): +def read_peers(cdir:str) -> (list, dict): if not os.path.isfile(cdir+"/peers"): open(cdir+"/peers", "w").close() @@ -158,13 +158,13 @@ def readPeers(cdir:str) -> (list, dict): return peers, peers_index # Save peers list -def writePeers(cdir:str, peers:list): +def write_peers(cdir:str, peers:list): peersfile = open(cdir+"/peers", "w") for peer in peers: peersfile.write(peer.export_str()+"\n") 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] assert sender_amount >= amount, "not enough money"