1

我正在尝试使用 MtGox.com WebSocket API 进行身份验证,并在很长一段时间后设法完成了 JSON 数据所需的“调用”属性。然而,我意识到我正在使用 Python 2 来运行我的代码示例,并且最终要在其中实现 API 的应用程序是用 Python 3 编写的。当我试图让它在 Python 3 中工作时,我遇到了几个问题尽管经过了几次长时间的尝试,仍无法解决。

我也尝试过2to3,但似乎没有针对此类问题的内置修复程序。

可在此处找到经过身份验证的 API 调用的 API 规范: https ://en.bitcoin.it/wiki/MtGox/API/Streaming#Authenticated_commands

这是我用来生成 JSON 调用的工作 Python 2 脚本,然后我通过我为 Chrome 找到的 WebSocket 控制台扩展运行该脚本。

import hashlib
import time
import hmac
import json
import base64
import binascii

apikey = ""
apisecret = ""

def _nonce():
    """produce a unique nonce that is guaranteed to be ever increasing"""
    microtime = int(time.time() * 1E6)
    return microtime

def _reqid(nonce):
    return hashlib.md5(str(nonce)).hexdigest()

def send_signed_call(api_endpoint, params):
    nonce = _nonce()
    reqid = _reqid(nonce)
    call = json.dumps({
        "id"       : reqid,
        "nonce"    : nonce,
        "call"     : api_endpoint,
        "params"   : params,
    })

    sign = hmac.new(base64.b64decode(apisecret), call, hashlib.sha512).digest()
    signedcall = apikey.replace("-", "").decode("hex") + sign + call

    return json.dumps({
        "op"      : "call",
        "call"    : base64.b64encode(signedcall),
        "id"      : reqid,
        "context" : "mtgox.com"
    })

msg = send_signed_call("private/info", {})
print(msg)

我遇到的一些错误与不再存在的 String.decode("hex") 有关,我还有其他一些错误,但不幸的是我没有跟踪所有这些错误,因为我尝试了很多不同的方法. 我还查看了其他语言中相同功能的代码示例,但找不到与 Python 3 问题相关的任何线索。Python 3 中对字节和字符串编码和解码所做的更改似乎与很多事情有关。

提前非常感谢!

4

1 回答 1

5

终于解决了!

这是该send_signed_call功能的工作版本,享受:

def send_signed_call(api_endpoint, params):
    nonce = _nonce()
    reqid = _reqid(nonce)
    call = json.dumps({
        "id"       : reqid,
        "nonce"    : nonce,
        "call"     : api_endpoint,
        "params"   : params,
    })
    callByte = bytes(call, "utf-8")

    sign = hmac.new(base64.b64decode(api_secret), callByte, hashlib.sha512).digest()
    skey = bytes.fromhex(api_key.replace("-",""))

    signedcall = skey + sign + callByte
    return json.dumps({
        "op"      : "call",
        "call"    : base64.b64encode(signedcall).decode("utf-8"),
        "id"      : reqid,
        "context" : "mtgox.com"
    })

你们不知道我现在的熊猫有多开心!

于 2013-09-06T19:14:43.167 回答