我正在尝试生成info_hash
用于与跟踪器通信的 bittorent 协议。
但我不断收到无效的 info_hash 错误。问题似乎出在我的代码的 urlencoded 部分,但我不确定。
我生成了一个经过编码的 metainfo.info 的 sha1 并axios
用来发送我的notify。
axios 是否进一步编码参数什么是对 20 字节数组进行 urlencode 的最佳方法?
在我的代码下面:
const axios = require('axios').default;
const bencode = require('bencode');
const crypto = require('crypto');
const urlencode = require('urlencode');
class TrackerMessenger {
constructor(metainfo) {
this.url = metainfo.announce.toString();
this.info = this.unbufferer(metainfo.info);
// this.info = metainfo.info;
// console.log(this.info)
this.left = metainfo.info?.files?.length || metainfo.info?.length;
}
async announce(peer_id, hostinfos) {
const port = hostinfos.port;
const compact = 1;
const event = 'started';
const trackerid = undefined;
// console.log(encodeURIComponent(this.info_hash))
let hash = this.urlencode(this.info_hash);
const res = await axios.get(this.url, {
params: {
info_hash: hash,
peer_id,
port,
left: this.left,
compact,
event,
trackerid
}
});
console.log(res.data);
return res;
}
get info_hash() {
let info = bencode.encode(this.info).toString('utf8');
const info_hash = crypto.createHash('sha1').update(info, 'utf8').digest();
console.log(info_hash.length);
return info_hash;
}
unbufferer(obj) {
const unbuffered = {};
Object.entries(obj).forEach(entry => {
const [key, value] = entry;
unbuffered[key] = this.unbuffer(value);
});
return unbuffered;
}
unbuffer(value) {
let result = undefined;
if(value == undefined)
return result;
if(typeof value === 'object')
result = this.unbufferer(value);
else if(Array.isArray(value))
result = value.forEach(item => this.unbuffer(item));
else
result = (Buffer.isBuffer(value))? value.toString('utf8'): value;
return result;
}
urlencode(buffer) {
return urlencode(buffer);
}
}
module.exports = TrackerMessenger;