def etp_collect_money(address):
    try:
        # 发送其他智能资产
        resp = etp_request("getbalance", ["etp_test", "etp_test"])
        balance = 0
        try:
            balance = int(json.loads(resp).get("total-confirmed"))
            if int(balance) <= 10000:
                return None, ("balance is not enough error")
        except:
            return
        Fee = 10000
        params = ["etp_test", "etp_test", address, balance - Fee]
        resp = etp_request("send", params)
        if json.loads(resp).get("transaction") is None:
            return None, ("send ETP to %s failed." % address)
        ret = {}
        ret['data'] = [{
            "from_addr":
            "etp_test",
            "to_addr":
            address,
            "amount":
            float(balance - Fee) / float(100000000),
            "trx_id":
            json.loads(resp).get("transaction").get('hash')
        }]
        ret['errdata'] = []
        return ret, None
    except Exception as e:
        logger.info(traceback.format_exc())
        return None, e.message
Example #2
0
def async_test_log(message: str):
    """
    测试消息队列
    """
    time.sleep(5)

    logger.info(f"async_test_log: {message},{datetime.now()}")
def etp_withdraw_address(address, amount):
    try:
        resp = etp_request("getbalance",
                           ["etp_withdraw_test", "etp_withdraw_test"])
        try:
            amount = amount * float(100000000)
            balance = int(json.loads(resp).get("total-confirmed"))
            if int(balance) < amount:
                raise Exception("balance is not enough error")
        except:
            return
        Fee = 10000
        params = [
            "etp_withdraw_test", "etp_withdraw_test", address,
            int(amount) - Fee
        ]
        print params
        resp = etp_request("send", params)
        result = json.loads(resp)
        print result
        if result.get("transaction") is None:
            raise Exception("send ETP to %s failed." % address)
        return result.get('transaction').get('hash')

    except Exception, ex:
        logger.info(traceback.format_exc())
        return ""
Example #4
0
def init_db(server):
    with app.app_context():
        from model import db
        from model.JobGroup import JobGroupModel
        from model.Employee import EmployeeModel
        from model.Files import FilesModel
        from model.History import HistoryModel
        from model.Rate import RateModel
        db.init_app(app=server)
        db.create_all()
        init_values()
        logger.info(f"Init db={db}")
Example #5
0
def task_do():
    while len(TASKS) > 0:
        try:
            TASK_ID = TASKS[0]
            logger.info("Task instance [%s] is running begin..." % TASK_ID)
            run()
        except Exception as e:
            logger.exception(e)
        finally:
            logger.info("Task instance [%s] is running end!\r\n" % TASK_ID)
            TASKS.remove(TASK_ID)
            TASK_ID = ''
Example #6
0
def get_client(args):
    '''
    Gets and validates the client_id
    '''
    logger.info(type(args))
    logger.info("The request.args {}".format(args))
    if "client_id" in args:
        client_id = args["client_id"]
        for client in CLIENTS:
            if client_id in client.values():
                return client
            else:
                return None
    else:
        return None
Example #7
0
 def base_http_request(self, url, method, args):
     user = '******'
     passwd = 'b'
     basestr = encodestring('%s:%s' % (user, passwd))[:-1]
     args_j = json.dumps(args)
     payload =  "{\r\n \"id\": 1,\r\n \"method\": \"%s\",\r\n \"params\": %s\r\n}" % (method, args_j)
     headers = {
         'content-type': "application/json",
         'authorization': "Basic %s" % (basestr),
         'cache-control': "no-cache",
     }
     logger.info(payload)
     response = requests.request("POST", url, data=payload, headers=headers)
     rep = response.json()
     logger.info(rep)
     return rep
Example #8
0
    def upload(session, file):
        try:
            df, fname = FileService.parse_file(file)
            if not FileService.check_fname(fname=fname):
                raise ValueError("File already uploaded.")
            else:
                logger.info(f"Adding file={fname}")
                file = FilesModel(name=fname)
                session.add(file)
                fid = FilesModel.query.filter_by(name=fname).first().id
                JobGroupService.add(df=df)
                HistoryService.add(df=df, fid=fid)

        except Exception as e:
            logger.error(e)
            raise e
Example #9
0
def authorize():
    logger.info("Inside authorize")
    headers = {'Content-Type': 'text/html'}
    resp = {}
    if not request.args:
        resp["error"] = "Missing request parameters."
        return make_response(
            render_template("error.html", error='Missing request parameters.'),
            200, headers)

    client = get_client(request.args)
    redirect_uri = get_redirect_uri(request.args, client)
    if not client:
        # Check for known client
        logger.error('Unknown client %s', request.args['client_id'])
        resp["error"] = "Unknown client."
        return make_response(
            render_template("error.html", error='Unknown client.'), 400,
            headers)
    elif not redirect_uri:
        logger.error("Mismatched redirect URI, expected %s got %s",
                     client["redirect_uris"], request.args["redirect_uri"])
        resp["error"] = "Invalid redirect URI."
        return resp
    else:
        # Check for the scopes
        req_scope = None
        client_scope = client["scope"].split(" ")
        if request.args['scope']:
            req_scope = request.args['scope'].split(' ')

        same = [item for item in req_scope if item in client_scope]
        if len(same) == 0:
            # client asked for a scope it could not have
            resp["error"] = "invalid_scope"
            return make_response(
                render_template("error.html", error='Invalid Scope'), 400,
                headers)

        reqid = generate_auth_code()
        REQUESTS[reqid] = request.query_string

        return make_response(
            render_template("authorize.html",
                            reqid=reqid,
                            scope=req_scope,
                            client=client), 200, headers)
Example #10
0
def query(method, args):
    url = "http://%s:%s" % (app.config['QUERY_SERVICE_HOST'], app.config['QUERY_SERVICE_PORT'])
    user = '******'
    passwd = 'b'
    basestr = encodestring('%s:%s' % (user, passwd))[:-1]
    args_j = json.dumps(args)
    payload = "{\r\n \"id\": 1,\r\n \"method\": \"%s\",\r\n \"params\": %s\r\n}" % (method, args_j)
    headers = {
        'content-type': "text/plain",
        'authorization': "Basic %s" % (basestr),
        'cache-control': "no-cache",
    }
    logger.info(payload)
    response = requests.request("POST", url, data=payload, headers=headers)
    rep = response.json()
    logger.info(rep)
    return rep
Example #11
0
def eth_collect_money(cash_sweep_account, accountList, safeBlock):
    try:
        result_data = {}
        result_data["errdata"] = []
        result_data["data"] = []
        print accountList
        last_block_num = get_latest_block_num() - int(safeBlock)
        # 存储创建成功的交易单号
        for account in accountList:
            amount = eth_get_no_precision_balance(account,last_block_num)

            print (float(amount) / pow(10, 18))
            print float(float(amount) / pow(10, 18)) > float(temp_config.ETH_Minimum)
            if float(float(amount) / pow(10, 18)) > float(temp_config.ETH_Minimum):
                print hex(long((amount - pow(10, 15)))).replace('L', '')
                # 转账给目标账户
                result = eth_request("personal_unlockAccount", [account, temp_config.ETH_SECRET_KEY, 10000])
                if json.loads(result).get("result") is None:
                    result_data["errdata"].append(
                        {"from_addr": account, "to_addr": cash_sweep_account, "amount": float(amount) / pow(10, 18),
                         "error_reason": u"账户解锁失败"})
                    # 写入归账失败的列表
                    continue

                ret = eth_request("eth_sendTransaction",[{"from": account, "to": cash_sweep_account,
                                                          "value": hex(long((amount - pow(10,15)))).replace('L',''),
                                                          "gas": "0x76c0", "gasPrice": "0x1dcd6500"}])
                if json.loads(result).get("result") is None:
                    result_data["errdata"].append(
                        {"from_addr": account, "to_addr": cash_sweep_account, "amount": float(amount) / pow(10, 18),
                         "error_reason": u"账户创建交易失败"})
                    # 写入归账失败的列表
                    continue
                else:
                    result_data["data"].append(
                        {"from_addr": account, "to_addr": cash_sweep_account, "amount": float(amount) / pow(10, 18),
                         "trx_id": json.loads(ret).get("result")})
                    # 获取交易详情按笔计入details
                    # 写入归账成功返回
        return result_data, None
    except Exception, ex:
        logger.info(traceback.format_exc())
        return None, ex.message
Example #12
0
def token():
    headers = {'Content-Type': 'text/html'}
    req_headers = request.headers
    auth = req_headers['authorization']
    client_id = None
    client_secret = None

    if (auth):
        auth_string = auth.split(' ')[1]
        creds = auth_string.split(":")
        client_id = base64.b64decode(creds[0]).decode('utf-8')
        client_secret = base64.b64decode(creds[1]).decode('utf-8')

    if request.form['client_id']:
        if client_id:
            return 'Invalid client id.', 401

        client_id = request.form['client_id']
        client_secret = request.form['client_secret']

    client = get_client_from_id(client_id)

    if client is None:
        logger.info(f'Unknown client id: {client_id}')
        return 'Unknown client.', 401

    if client_secret != client['client_secret']:
        logger.warn('Mismatched client secret.')
        return 'Invalid client', 401

    if request.form['grant_type'] and request.form['grant_type'] == 'authorization_code':

        auth_code = CODES.pop(request.form['code'])

        if auth_code:
            if auth_code['client_id'] == client_id:
                access_token = generate_access_token()

                r = redis.Redis()
                r.hmset(access_token)

    return make_response(render_template('error.html', error='Not Supported Yet.'), 503, headers)
Example #13
0
    while len(TASKS) > 0:
        try:
            TASK_ID = TASKS[0]
            logger.info("Task instance [%s] is running begin..." % TASK_ID)
            run()
        except Exception as e:
            logger.exception(e)
        finally:
            logger.info("Task instance [%s] is running end!\r\n" % TASK_ID)
            TASKS.remove(TASK_ID)
            TASK_ID = ''


def task_run():
    try:
        timer = threading.Timer(60, task_run)
        timer.start()
        TASKS.append(str(uuid.uuid1()))
        if not TASK_ID:
            task_do()
    except Exception as e:
        logger.exception(e)


if __name__ == "__main__":
    try:
        logger.info('Win sevice is starting...\r\n')
        timer = threading.Timer(60, task_run)
        timer.start()
    except Exception as e:
        logger.exception(e)
Example #14
0
def approve():
    logger.info("==> approve()")
    headers = {'Content-Type': 'text/html'}
    params = {}

    if not request.form:
        logger.error("Missing post parameters. Bad request.")
        return make_response(
            render_template(
                'error.html',
                error='Missing post form parameters. Bad request.'), 400,
            headers)
        # return "Bad Request", 400
    else:
        query = REQUESTS.pop(request.form['reqid'], None)
        query = query.decode('UTF-8')
        print("The query: ", query)
        if not query:
            logger.error("Did not get a query string.")
            return make_response(
                render_template('error.html', error='Bad Request'), 400,
                headers)
        else:
            params = parse.parse_qs(query)
            print(params)
        if request.form["approve"]:
            logger.debug("Approving a token request.")
            if params["response_type"][0] == 'code':
                code = generate_auth_code()
                # Not sure whwer the user comes from.
                # user = request.form['user']

                scope = params['scope'][0]
                req_scope = scope.split(' ')

                client = get_client_from_query(params)
                print(client)
                client_scope = client['scope']

                same = [item for item in req_scope if item in client_scope]
                if len(same) == 0:
                    # Client asked for a scope it could not have.
                    return make_response(
                        render_template('error.html', error='Invalid Scope'),
                        400, headers)

                # Save for later. A dictionary of stuff
                CODES[code] = {
                    'authorizationRequest': query,
                    'scope': scope,
                    'client_id': client['client_id']
                }

                # Build the redirect url
                redirect_uri = params['redirect_uri'][0]
                if redirect_uri not in client['redirect_uris']:
                    return make_response(
                        render_template('error.html',
                                        error='Invalid redirect URI.'), 400,
                        headers)

                state = params['state'][0]
                payload = {'code': code, 'state': state}

                the_location = ''.join(
                    (redirect_uri, '?', parse.urlencode(payload)))
                print(the_location)
                return redirect(the_location, code=302)

    return "Got here", 200
Example #15
0
 def post(self):
     logger.info("Received a POST.")
     return render_template("error.html", error="Not the correct action.")