zlib的uncompress()奇怪地返回Z_BUF_ERROR

时间:2011-06-29 21:38:36

标签: c++ qt zlib bitcoin

我正在编写基于Qt的客户端应用程序。它使用QTcpSocket连接到远程服务器。在发送任何实际数据之前,它需要发送登录信息,这是zlib-compressed json。

据我所知,从服务器来源来看,为了使一切正常,我需要在4个字节之后发送X字节的压缩数据,其长度为未压缩数据。

在服务器端解压缩如下所示:

/* look at first 32 bits of buffer, which contains uncompressed len */
unc_len = le32toh(*((uint32_t *)buf));
if (unc_len > CLI_MAX_MSG)
    return NULL;

/* alloc buffer for uncompressed data */
obj_unc = malloc(unc_len + 1);
if (!obj_unc)
    return NULL;

/* decompress buffer (excluding first 32 bits) */
comp_p = buf + 4;
if (uncompress(obj_unc, &dest_len, comp_p, buflen - 4) != Z_OK)
    goto out;
if (dest_len != unc_len)
    goto out;
memcpy(obj_unc + unc_len, &zero, 1);    /* null terminate */

我正在使用Qt内置的zlib压缩json(我刚刚下载了标题并将其放在mingw的include文件夹中):

char json[] = "{\"version\":1,\"user\":\"test\"}";
char pass[] = "test";

std::auto_ptr<Bytef> message(new Bytef[             // allocate memory for:
                             sizeof(ubbp_header)    //  + msg header
                             + sizeof(uLongf)       //  + uncompressed data size
                             + strlen(json)         //  + compressed data itself
                             + 64                   //  + reserve (if compressed size > uncompressed size)
                             + SHA256_DIGEST_LENGTH]);//+ SHA256 digest

uLongf unc_len = strlen(json);
uLongf enc_len = strlen(json) + 64;

// header goes first, so server will determine that we want to login
Bytef* pHdr = message.get();

// after that: uncompressed data length and data itself
Bytef* pLen = pHdr + sizeof(ubbp_header);
Bytef* pDat = pLen + sizeof(uLongf);

// hash of compressed message updated with user pass
Bytef* pSha;

if (Z_OK != compress(pLen, &enc_len, (Bytef*)json, unc_len))
{
    qDebug("Compression failed.");
    return false;
}

此处填写功能代码:http://pastebin.com/hMY2C4n5

即使服务器正确收到未压缩的长度,uncompress()也会返回Z_BUF_ERROR

P.S。:我实际上是在写pushpool的客户端来弄清楚它的二进制协议是如何工作的。我在官方比特币论坛上问过这个问题,但那里没有运气。 http://forum.bitcoin.org/index.php?topic=24257.0

1 个答案:

答案 0 :(得分:1)

原来这是服务器端的错误。比特币论坛帖子中的更多细节。