gpt4 book ai didi

python - 在 Python 3 中对 MtGox WebSocket API 的身份验证调用

转载 作者:太空宇宙 更新时间:2023-11-04 09:07:41 25 4
gpt4 key购买 nike

我正在尝试使用 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 中对字节和字符串编码和解码所做的更改有关。

提前致谢!

最佳答案

终于解决了!

这是 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"
})

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

关于python - 在 Python 3 中对 MtGox WebSocket API 的身份验证调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18557453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com