pythonflask

OSError: [WinError 10038] An operation was attempted on something that is not a socket FLASK


At some point i was messing around with flask sockets but ended up not using the libraries, I then reverted my code but ended up getting socket errors even though my code no longer contained anything remotely related to bi-directional socket connections.

The following is my code (sorry for the spaggetti i'm still terrible at coding):

import time, json, xxhash, threading, random
from flask import Flask, request
from string import digits
from random import choice
app = Flask(__name__)

target = 5
last_block, key = time.time(), int(''.join(choice(digits) for i in range(8)))
pending_transactions, pending_data = [], []

user_data = {}

def import_user_data(username):
    with open(f'user_data\\{username}.json', 'r') as f:
        return json.load(f)

def export_user_data(username, data):
    with open(f'user_data\\{username}.json', 'w') as f:
        return json.dump(data, f)

def create_user_data(user, password):
    try:
        with open(f'user_data\\{user}.json', 'x') as f:
            json.dump({"password": password, "balance": 0, "transactions": []}, f)
        return True
    except Exception:
        return False

def get_balance(user):
    data = import_user_data(user)
    return data.get("balance")

def post_transaction(amount, sender, recipient, memo):
    txid = xxhash.xxh64(random.randbytes(64)).hexdigest()

    if sender != "Mainnet":
        user = import_user_data(sender)
        if len(user["transactions"]) >= 25:
            user["transactions"].pop(-1)
        user["transactions"].append({"txid": txid, "sender": sender, "recipient": recipient, "amount": amount, "memo": memo})
        export_user_data(sender, user)

    user = import_user_data(recipient)
    if len(user["transactions"]) >= 25:
        user["transactions"].pop(-1)
    user["transactions"].append({"txid": txid, "sender": sender, "recipient": recipient, "amount": amount, "memo": memo})
    export_user_data(recipient, user)

    return txid
def payout(username):
    global target
    data = import_user_data(username)

    reward = target * 10 + 1

    data["balance"] += reward
    export_user_data(username, data)
    post_transaction(reward, "Mainnet", username, f"mining reward! (target: {target})")

def transfer(sender, recipient, amount):
    data = import_user_data(sender)

    if not float(data.get("balance")) < float(amount):
        data["balance"] -= float(amount)
        export_user_data(data, sender)

        data = import_user_data(recipient)
        data["balance"] += float(amount)

        export_user_data(data, recipient)

    return {"txid": post_transaction(amount, sender, recipient, memo)}

def new_block(block, last_block):
    global target, key

    t = block - last_block
    key = int(''.join(choice(digits) for i in range(8)))

    if t > 80:
        target -= 1
    if t < 50:
        target += 1

    for i in range(0, len(pending_transactions)):
        pass

def chain():
    global target, last_block

    try:
        while True:

            if time.time() - last_block > 81:
                target -= 1
                last_block = time.time()
                time.sleep(30)

    except Exception as e:
        print(e)

@app.route("/create_account")
def create_acc():
    try:
        e, t = time.time(), target

        if request.json["hash"] == xxhash.xxh64(request.json["nonce"], seed=int(e)).hexdigest():

            username, password = xxhash.xxh64(random.randbytes(64)).hexdigest(), xxhash.xxh64(random.randbytes(64)).hexdigest()
            create_user_data(username, password)

            return {"output": True, "username": username, "password": password}

    except Exception as e:
        return {"output": False, "info": e}

@app.route("/mine", methods=['GET', 'POST'])
def mine():
    global key, last_block, target

    if request.method == "GET":
        return {"target": target, "key": key}
    else:
        e, t = time.time(), target

        if request.json["hash"] == xxhash.xxh64(request.json["nonce"], seed=key).hexdigest():
            new_block(e, last_block)

            last_block = e

            payout(request.json["username"])

            return {"output": True, "info": "you have submitted a valid block!"}
        else:
            return {"output": False, "info": "your submission is invalid"}

if __name__ == '__main__':
    c = threading.Thread(target=chain)
    c.start()

    app.run(debug=True, port=80, host="127.0.0.1")

Let me know if more information should be provided

  1. I reinstalled Flask along with its dependancies.
  2. I followed the steps in this https://stackoverflow.com/questions/45355301/running-flask-raises-winerror-10038 forum post
  3. I restarted my computer yet the error persisted, although the error only pops up once every few minutes.

EDIT: The following is the error along with the traceback:

Exception in thread Thread-3:
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\threading.py", line 980, in _bootstrap_inner
    self.run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\threading.py", line 917, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\jerrb\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\werkzeug\serving.py", line 804, in serve_forever
    super().serve_forever(poll_interval=poll_interval)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\socketserver.py", line 232, in serve_forever
    ready = selector.select(poll_interval)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\selectors.py", line 324, in select
    r, w, _ = self._select(self._readers, self._writers, [], timeout)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\selectors.py", line 315, in _select
    r, w, x = select.select(r, w, w, timeout)
OSError: [WinError 10038] An operation was attempted on something that is not a socket

Solution

  • After hours of fuss and scrolling through the internet, ChatGPT managed to solve my problem within 3 minutes. I solved my issue by reinstalling Winsock2 completely using the following cmd commands.

    netsh winsock reset catalog
    netsh int ipv4 reset reset.log
    netsh int ipv6 reset reset.log
    

    The problem was caused by heavy corruption of Winsock2