Пример #1
0
def utxoGetUnspendOutput(fromAddress):
    url = UTXO_URL + '/find_all_spendable_outputs?from_address=' + fromAddress.lower(
    )
    resp = requests.get(url)
    resp = json.loads(resp.content.decode("utf-8"))
    logger.info('utxoGetUnspendOutput resp=%s, url=%s' % (resp, url))
    return resp
Пример #2
0
def newCoinbase(request):
    postBody = request.body
    #logger.info('newCoinbase, request.body=%s %s' % (request.method, request.body))
    headers = {'Content-Type': 'application/json; charset=UTF-8'}
    if request.method == 'OPTIONS' or request.method == 'GET':
        return HttpResponse()

    try:
        url = UTXO_URL + '/broadcast_tx'
        data = {'tx': postBody}
        logger.info('newCoinbase, rawTx=%s' % data)
        resp = requests.post(url, data)
        logger.info('newCoinbase, resp=%s' % resp.json())
        return JsonResponse(resp.json())
    except Exception as e:
        logger.error("newCoinbase error, e=%s, body=%s" % (e, request.body))
        traceback.print_exc()
        err = {
            "jsonrpc": "2.0",
            "id": 1,
            "error": {
                "code": -1,
                "message": "newCoinbase error "
            }
        }
        return JsonResponse(err)

    return JsonResponse(resp)
Пример #3
0
def eth_getBalance(reqDict):
    address = reqDict['params'][0]
    balance = utxoGetBalance(address.lower())
    logger.info('eth_getBalance address=%s, balance=%s' % (address, balance))
    if not balance:
        balance = 0
    ret = {"id": reqDict['id'], "jsonrpc": "2.0", "result": hex(balance)}
    return ret
Пример #4
0
def utxoGetBalance(address):
    url = UTXO_URL + '/get_balance?address=' + address.lower()
    resp = requests.get(url)
    resp = json.loads(resp.content.decode("utf-8"))
    if resp['code'] != 'success':
        logger.error('utxoGetBalance resp error: %s' % resp)
        return None
    logger.info('utxoGetBalance resp=%s, url=%s' % (resp, url))
    return resp['balance']
Пример #5
0
def recoverTransactionRaw(rawTx):
    try:
        from transactions import Transaction, vrs_from
        from signing import hash_of_signed_transaction
    except Exception as e:
        logger.info('import eth_account path')
        eth_dir = eth_account.__path__[0]
        lib_path = os.path.abspath(os.path.join(eth_dir, 'internal'))
        sys.path.append(lib_path)
        from transactions import Transaction, vrs_from
        from signing import hash_of_signed_transaction

    txn_bytes = HexBytes(rawTx)
    txn = Transaction.from_bytes(txn_bytes)
    msg_hash = hash_of_signed_transaction(txn)
    sender = eth_account.Account.recoverHash(msg_hash, vrs=vrs_from(txn))
    txn.sender = sender
    return txn
Пример #6
0
def eth_sendRawTransaction(reqDict):
    rawTx = reqDict['params'][0]

    txn = recoverTransactionRaw(rawTx)
    #logger.info('txn: %s' % txn)
    #logger.info('nonce: %s' % txn.nonce)
    #logger.info('gasPrice: %s' % txn.gasPrice)
    #logger.info('gas: %s' % txn.gas)
    #logger.info('to: %s, len=%d, type=%s' % (txn.to, len(txn.to), type(txn.to)))
    toAddr = eth_utils.to_checksum_address(txn.to)
    #logger.info('toAddr: %s' % toAddr)
    #logger.info('value: %s, type=%s, int=%d' % (txn.value, type(txn.value), int(txn.value)))
    #logger.info('data: %s' % txn.data)
    #logger.info('v: %s' % txn.v)
    #logger.info('r: %s' % txn.r)
    #logger.info('s: %s' % txn.s)
    #logger.info('sender: %s' % txn.sender)

    resp = utxoGetUnspendOutput(txn.sender.lower())
    ret = {
        "id": reqDict['id'],
        "jsonrpc": "2.0",
        "error": {
            "code": -1,
        }
    }
    if (not resp) or (resp['code'] != 'success'):
        ret["error"]['message'] = "get utxo error"
        return ret

    tx = new_utxo_transaction(txn.sender.lower(), toAddr.lower(),
                              int(txn.value), resp['accumulated'],
                              resp['unspent_outs'])
    if not tx:
        ret["error"]['message'] = "sender doesn't have enough funds to send tx"
        return ret
    ret.pop('error')
    ret['result'] = tx.ID
    logger.info('eth_sendRawTransaction tx.ID=%s' % tx.ID)
    trans = tx.serialize().replace('"', "'", -1)
    resp = utxoBroadTx(trans, tx.ID)
    return ret
Пример #7
0
def utxoBroadTx(rawTx, txID):
    resp = utxoGetTxByHash(txID)
    if resp['code'] == 'success':
        logger.info('txID already exist in blockchain, txID=' + txID)
        return resp
    url = UTXO_URL + '/broadcast_tx'
    data = {'tx': rawTx}
    logger.info('utxoBroadTx, rawTx=%s' % rawTx)
    resp = requests.post(url, data)
    logger.info('utxoBroadTx, resp=%s' % resp)
    return resp.json()
Пример #8
0
def order(request):
    try:
        params = load_json(request.body)
    except Exception as e:
        return JsonResponse({"error": True, "msg": "body should json type"})

    if not params.get('amount'):
        return JsonResponse({"error": True, "msg": "Need param amount"})
    if not params.get('destAddress'):
        return JsonResponse({"error": True, "msg": "Need param destAddress"})
    if not params.get('pair'):
        return JsonResponse({"error": True, "msg": "Need param pair"})
    if not (params.get('pair') in ["TRIETH", "ETHTRI"]):
        return JsonResponse({"error": True, "msg": "Not support pair"})

    re_dict = {"error": False, "msg": "", "data": {"input": {}, "output": {}}}

    try:
        sourceCoin = params['pair'][0:3]
        targetCoin = params['pair'][3:]
        ce = CoinExchangeList.objects.filter(
            source_coin_name=sourceCoin, target_coin_name=targetCoin).first()
        targetAmount = Decimal(params['amount']) * Decimal(ce.rate)
        if not DBOperation.isBalanceSufficient(targetCoin, targetAmount):
            re_dict["error"] = True
            re_dict[
                "msg"] = "insufficient balance for coin %s of amount %s" % (
                    targetCoin, targetAmount)
            response = JsonResponse(re_dict)
            return response

        re_dict["data"]["id"] = random_str(100)
        re_dict["data"]["amount"] = params['amount']
        re_dict["data"]["pair"] = params['pair']
        re_dict["data"]["payment_address"] = DBOperation.genNewAddress(
            sourceCoin, False)
        re_dict["data"]["validFor"] = ce.order_valid_seconds
        seconds = time.time()
        timestamp = stamp2UTCdatetime(seconds)
        re_dict["data"]["timestamp_created"] = timestamp
        re_dict["data"]["status"] = "OPEN"
        re_dict["data"]["input"]['amount'] = Decimal(params['amount'])
        re_dict["data"]["input"]['currency'] = sourceCoin
        re_dict["data"]["output"]['amount'] = targetAmount
        re_dict["data"]["output"]['currency'] = targetCoin

        order = Order()
        order.order_id = re_dict["data"]["id"]
        order.source_coin_name = sourceCoin
        order.source_amount = re_dict["data"]["input"]['amount']
        order.target_coin_name = targetCoin
        order.target_amount = re_dict["data"]["output"]['amount']
        order.create_time_stamp = seconds
        order.rate = ce.rate
        order.target_coin_address = params.get('destAddress')
        order.source_coin_payment_address = re_dict["data"]["payment_address"]
        order.source_coin_payment_amount = 0
        order.transaction_in_id = 0
        order.transaction_out_id = 0
        order.is_finished = False
        order.save()
        logger.info("%s->%s insert order in db, id=%s" %
                    (sourceCoin, targetCoin, order.id))
        response = JsonResponse(re_dict)
    except Exception as e:
        logger.error(e)

    return response
Пример #9
0
def utxoGetLatestHeight():
    url = UTXO_URL + '/get_latest_block_height'
    resp = requests.get(url)
    resp = json.loads(resp.content.decode("utf-8"))
    logger.info('utxoGetLatestHeight resp=%s, url=%s' % (resp, url))
    return resp['latest_block_height']
Пример #10
0
def utxoGetTxByHash(hash):
    url = UTXO_URL + '/get_tx_by_hash?hash=' + hash
    resp = requests.get(url)
    resp = json.loads(resp.content.decode("utf-8"))
    logger.info('utxoGetTxByHash resp=%s, url=%s' % (resp, url))
    return resp