Nodejs Coinbase V2 REST端点返回无效签名



无法弄清楚coinbase v2 REST端点返回无效签名错误的原因,可能有人看到我做错了什么。我所发现的一切都与不再维护的旧NPM包的使用有关。还有一个Coinbase Pro包,但我不想与Pro API通信。

const { createHmac } = require('crypto');
const axios = require('axios');
(async () => {
const cbApiKey = 'xxx';
const apiSecret = 'xxx';
const method = 'GET';
const path = '/v2/user';
const body = '';

const timestamp = Math.floor(new Date().getTime() * 1e-3);
const message = timestamp + method + path + body;
const key = Buffer.from(apiSecret, 'base64');
const cbAccessSign = createHmac('sha256', key).update(message).digest('base64');
const instance = axios.create();
try {
const user = await instance.request({
method,
url: `https://api.coinbase.com${path}`,
headers: {
'CB-ACCESS-KEY': `${cbApiKey}`,
'CB-ACCESS-SIGN': `${cbAccessSign}`,
'CB-ACCESS-TIMESTAMP': `${timestamp}`,
"Content-Type": 'application/json',
},
}); 
console.log(user);
} catch (error) {
console.log(error);
}  
})();

我要在这里添加一些内容,因为它早些时候让我抓狂,即尝试crypto js没有效果,然后不得不进行大量的斗争,并制定了几个解决方案来使"crypto"在教程中使用,克服了它目前面临的所有障碍。

据我所知,大多数无效签名都可以追溯到CB-ACCESS-SIGN,最大的挑战是弄清楚crypto-js中的工作等价物是什么样子,并使所有这些在Angular 10中正常工作。

API调用的striped-down版本和访问符号的哈希字符串创建:

import * as CryptoJS from 'crypto-js';
async getUserCreds(apk: string, aps: string): Promise<any> {
let access_sign = Access_Sign(getUnixTimestamp(), 'GET', '/v2/user','',aps)
let httpOptions = {
headers: new HttpHeaders({
"CB-ACCESS-KEY": apk,
"CB-ACCESS-SIGN": access_sign,
"CB-ACCESS-TIMESTAMP": getUnixTimestamp().toString(),
"Content-Type": "application/json"
})
}
return this.http.get<any>('https://api.coinbase.com/v2/user',httpOptions)
.pipe(shareReplay(), catchError((x) => { return this.handleErrorLog(x) 
})).toPromise();
}

export function Access_Sign(timestamp: number, method: string, requestPath: string, body: string, secret: string) {
let prehash = timestamp + method.toUpperCase() + requestPath + body;
return CryptoJS.HmacSHA256(prehash, secret).toString(CryptoJS.enc.Hex);
}
export function getUnixTimestamp() {
return Math.floor(Date.now() / 1000)
}

我在这里找到了答案https://github.com/coinbase/coinbase-node/blob/master/lib/ClientBase.js#L101

签名的正确代码是

var signature = crypto.createHmac('sha256', this.apiSecret).update(message).digest('hex');

如果您仍然面临此问题,请确保路径包括/

我遇到这个问题是因为message上使用的path部分是accounts,而不是/accounts

最新更新