比特币索引数据库*.ldb、peers.dat解读

 比特币最新版本的索引数据库存储在区块文件同级目录下的index目录,采用leveldb数据库存储k/v数据,k的值为b+hash(区块),v的值代码如下:

template 
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) 
{
//VARINT为变长存储,规则如下:
//1、读取第1个字节。
//2、字节向左移动7位。结果后7位,设置为已读取字节的后7位。(比特位)
//3、如果已读取字节第0比特位(最高比特位)为 1,继续读下一字节,重复第2~4步骤。否则,结束。
if (!(nType & SER_GETHASH))
READWRITE(VARINT(nVersion));

READWRITE(VARINT(nHeight));
READWRITE(VARINT(nStatus));
READWRITE(VARINT(nTx));
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
READWRITE(VARINT(nFile));
if (nStatus & BLOCK_HAVE_DATA)
READWRITE(VARINT(nDataPos));
if (nStatus & BLOCK_HAVE_UNDO)
READWRITE(VARINT(nUndoPos));

//区块头数据
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
}

区块根据区块头中的上一区块hash值(key),在index数据库中,通过key查找上一区块的位置(nFile,nDataPos),从而定位到上一区块,如此重复,则“链”成。

比特币索引数据库*.ldb、peers.dat解读_第1张图片

 通过读取*.ldb中的键值对,根据上述规则,完全可以对应上,分析没有问题。

key (33) : 62 00 8C 37 96 C4 BE BD 0B CD 11 E4 A3 0D CB A6 FF B4 F5 CB 45 56 A6 C8 FA C6 37 3F 19 CD 10 BD 36
val(91) : 89 AE 2C 33 1D 01 00 D9 7E 8F 0A 00 00 00 20 E8 4F E5 3F 35 8F E7 7D 4C 81 F2 AE B9 A0 92 E5 23 82 6B 98 41 FF 70 D1 38 CC 56 44 0B D4 04 2B 67 3A 9C 5E 54 1B 05 4A 14 4A D0 9C F1 67 E2 3C 30 94 24 BF 8A 1C BC D4 E7 BD 17 27 97 E4 88 D0 AF 80 1E 5B FF FF 7F 20 01 00 00 00
_nVersion: 169900 pos:0 len:3 
nHeight: 51 pos:3 len:1 
nStatus: 29 pos:4 len:1 
nTx: 1 pos:5 len:1 
nFile: 0 pos:6 len:1 
nDataPos: 11646 pos:7 len:2 
nUndoPos: 2058 pos:9 len:2 

 peers.dat数据结构:

比特币索引数据库*.ldb、peers.dat解读_第2张图片

peers.dat解读:

 

比特币索引数据库*.ldb、peers.dat解读_第3张图片

 

Header: 
	MessageBytes: f9 be b4 d9 
	Version: 1 
	KeySize: 32 
	NKey: fa 24 ed ca d5 91 86 89 7a c5 a8 72 0e 74 74 38 c3 26 8d 4b 2f 44 52 45 8f 23 14 d8 3a 52 24 3b 
	NNew: 64235 
	NTried: 305 
	NewBuckets: 1024 
New_CAddrInfo[0]: pos 50
	Address.SerializationVersion: 98 fc 01 00 
	Address.Time: 1501624953 
	Address.ServiceFlags: 00 00 00 00 00 00 00 0d 
	Address.PeerAddress.IPAddress: 00 00 00 00 00 00 00 00 00 00 ff ff 68 c7 a7 3c (IPV4 104.199.167.60) 
	Address.PeerAddress.Port : 8333 
	Source: 00 00 00 00 00 00 00 00 00 00 ff ff 25 22 30 11 (IPV4 37.34.48.17) 
	LastSuccess: 0 
	Attempts: 0 
New_CAddrInfo[1]: pos 112
	Address.SerializationVersion: 98 fc 01 00 
	Address.Time: 1516555613 
	Address.ServiceFlags: 00 00 00 00 08 00 00 2d 
	Address.PeerAddress.IPAddress: 00 00 00 00 00 00 00 00 00 00 ff ff 2d 32 2e dd (IPV4 45.50.46.221) 
	Address.PeerAddress.Port : 8333 
	Source: 00 00 00 00 00 00 00 00 00 00 ff ff 25 22 30 11 (IPV4 37.34.48.17) 
	LastSuccess: 0 
	Attempts: 0 

至此,对比特币数据文件(.dat、.ldb)全部分析完毕,比特币数据结构完全掌握,有利于后续区块链应用系统实现的数据库设计......

你可能感兴趣的:(区块链)