"All serialization functions of bitcoin client are implemented in serilaze. H. Among them, cdatastream class is the core structure of data serialization.
CDataStream
Cdatastream has a character class container for storing serialized data. It combines a container type and a stream interface to process data. It uses six member functions to achieve this function:
[cpp]view plaincopy
classCDataStream
{
protected:
typedefvector>vector_ type;
vector_ typevch;
unsignedintnReadPos;
shortstate;
shortexceptmask;
public:
intnType;
intnVersion;
//......
}
VCH stores the serialized data. It is a character container type with a custom memory allocator. The memory allocator will be called by the implementation of the container when memory needs to be allocated / released. The memory allocator will empty the data in the memory before releasing the memory to the operating system to prevent other processes on the machine from accessing the data, so as to ensure the security of data storage. The implementation of the memory allocator is not discussed here. Readers can find it by themselves in serialize. H.
Nredpos is the starting position where VCH reads data.
State is the error identifier. This variable is used to indicate possible errors in serialization / deserialization.
Exceptmask is the error mask. It is initialized as IOS:: badbit | IOS:: failbit. Similar to state, it is used to indicate the type of error.
The value of ntype is Ser_ NETWORK,SER_ DISK,SER_ GETHASH,SER_ SKIPSIG,SER_ One of blockheaderonly, which is used to notify cdatastream to perform a specific serialization operation. These five symbols are defined in an enum type enum. Each symbol is of type int (4 bytes) and its value is to the power of 2.
[cpp]view plaincopy
enum
{
//primaryactions
SER_ NETWORK=(1<< 0),
SER_ DISK=(1<< 1),
SER_ GETHASH=(1<< 2),
//modifiers
SER_ SKIPSIG=(1<< 16),
SER_ BLOCKHEADERONLY=(1<< 17),
};
Nversion is the version number.
Cdatastream:: read() and cdatastream:: write()
The member functions cdatastream:: read() and cdatastream:: write() are low-level functions used to serialize / deserialize cdatastream objects.
[cpp]view plaincopy
CDataStream&read(char*pch,intnSize)
{
//Readfromthebeginningofthebuffer
assert(nSize>=0);
unsignedintnReadPosNext=nReadPos+nSize;
if(nReadPosNext>=vch.size())
{
if(nReadPosNext>vch.size())
{
setstate(ios::failbit,""CDataStream::read():endofdata"");
memset(pch,0,nSize);
nSize=vch.size()-nReadPos;
}
memcpy(pch,&vch[nReadPos],nSize);
nReadPos=0;
vch.clear();
return(*this);
}
memcpy(pch,&vch[nReadPos],nSize);
nReadPos=nReadPosNext;
return(*this);
}
CDataStream&write(constchar*pch,intnSize)
{
//Writetotheendofthebuffer
assert(nSize>=0);
vch.insert(vch.end(),pch,pch+nSize);
return(*this);
}
Cdatastream:: read() copies nSize characters from cdatastream to a memory space pointed by char * PCH. The following is its implementation process:
Calculate the end position of the data to be read from VCH, unsigned int nredposnext = nredpos + nSize.
If the end position is larger than the size of the VCH, there is currently not enough data to read. In this case, set the state to IOS:: failbit by calling the function setstate(), and copy all zeros to PCH.
Otherwise, call memcpy (PCH, &vch [nredpos], nSize) to copy nSize characters, starting from the nredpos position of VCH to a pre allocated memory pointed by PCH. Then move forward from nredpos to the next starting position nredposnext (line 22).
The implementation shows that 1) when a piece of data is read from the stream, the piece of data cannot be read again; 2) Nredpos is the read location for the first valid data.
Cdatastream:: write() is very simple. It appends nSize characters pointed by PCH to the end of VCH.
Macros readdata() and writedata()
The functions cdatastream:: read() and cdatastream:: write() are used to serialize / deserialize primitive types (int, bool, unsigned long, etc.). To serialize these data types, pointers to these types are converted to char *. Since the sizes of these types are currently known, they can be read from cdatastream or written to the character buffer. Two macros that reference these functions are defined as assistants.
[cpp]view plaincopy
#defineWRITEDATA(s,obj)s.write((char*)&(obj),sizeof(obj))
#defineREADDATA(s,obj)s.read((char*)&(obj),sizeof(obj))
Here are examples of how to use these macros. The following function serializes an unsigned long type.
[cpp]view plaincopy
[cpp]view plaincopy
templateinlinevoidSerialize(Stream&s,unsignedlonga,int,int=0){WRITEDATA(s,a);}
Replace writedata (s, a) with its own definition. The following is the expanded function:
[cpp]view plaincopy
templateinlinevoidSerialize(Stream&s,unsignedlonga,int,int=0){s.write((char*)&(a),sizeof(a));}
The function accepts an unsigned long parameter a, obtains its memory address, converts the pointer to char * and calls the function s.write().
Operators < < and > > in cdatastream
Cdatastream overloads the operators < < and > > for serialization and deserialization.
[cpp]view plaincopy
template
CDataStream&operator<<(const T& obj)
{
//Serializetothisstream
::Serialize(*this,obj,nType,nVersion);
return(*this);
}
template
CDataStream&operator>>(T&obj)
{
//Unserializefromthisstream
::Unserialize(*this,obj,nType,nVersion);
return(*this);
}
The header file serialize. H contains 14 overloaded global functions to 14 original types (signed and unsigned versions, char, short, int, long and long, and char, float, double and bool) and 6 overloaded versions of 6 composite types (string, vector, pair, map, set and cscript). Therefore, for these types, you can simply serialize / deserialize data using the following code:
[cpp]view plaincopy
CDataStreamss(SER_ GETHASH);
ss<
ss>>obj3>>obj4;// Deserialization
If no implemented type matches the second parameter obj, the following generic t global functions will be called.
[cpp]view plaincopy
template
inlinevoidSerialize(Stream&os,constT&a,longnType,intnVersion=VERSION)
{
a.Serialize(os,(int)nType,nVersion);
}
For this generic version, type t should be used to implement a member function and signature T:: Serialize (stream, int, int). It will be called through a. serialize().
How to implement serialization of a type
In the previous introduction, generic t needs to implement the following three member functions for serialization.
[cpp]view plaincopy
unsignedintGetSerializeSize(intnType=0,intnVersion=VERSION)const;
voidSerialize(Stream&s,intnType=0,intnVersion=VERSION)const;
voidUnserialize(Stream&s,intnType=0,intnVersion=VERSION);
These three functions will be called by their corresponding global functions with generic t. These global functions are called by the overloaded operators < < and > > in cdatastream.
A macro implement_ Serialize (statements) is used to define the implementation of these three functions of any type.
[cpp]view plaincopy
#defineIMPLEMENT_ SERIALIZE(statements)\
unsignedintGetSerializeSize(intnType=0,intnVersion=VERSION)const\
{\
CSerActionGetSerializeSizeser_ action;\
constboolfGetSize=true;\
constboolfWrite=false;\
constboolfRead=false;\
unsignedintnSerSize=0;\
ser_ streamplaceholders;\
s.nType=nType;\
s.nVersion=nVersion;\
{statements}\
returnnSerSize;\
}\
template\
voidSerialize(Stream&s,intnType=0,intnVersion=VERSION)const\
{\
CSerActionSerializeser_ action;\
constboolfGetSize=false;\
constboolfWrite=true;\
constboolfRead=false;\
unsignedintnSerSize=0;\
{statements}\
}\
template\
voidU
Our other product: