-
Notifications
You must be signed in to change notification settings - Fork 29
/
checkpointsync.cpp
339 lines (287 loc) · 12.7 KB
/
checkpointsync.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Copyright (c) 2012-2013 PPCoin developers
// Copyright (c) 2014-2017 Primecoin Developers
// Distributed under conditional MIT/X11 software license,
// see the accompanying file COPYING
//
// The synchronized checkpoint system is first developed by Sunny King for
// ppcoin network in 2012, giving cryptocurrency developers a tool to gain
// additional network protection against 51% attack.
//
// Primecoin also adopts this security mechanism, and the enforcement of
// checkpoints is explicitly granted by user, thus granting only temporary
// consensual central control to developer at the threats of 51% attack.
//
// Concepts
//
// In the network there can be a privileged node known as 'checkpoint master'.
// This node can send out checkpoint messages signed by the checkpoint master
// key. Each checkpoint is a block hash, representing a block on the blockchain
// that the network should reach consensus on.
//
// Besides verifying signatures of checkpoint messages, each node also verifies
// the consistency of the checkpoints. If a conflicting checkpoint is received,
// it means either the checkpoint master key is compromised, or there is an
// operator mistake. In this situation the node would discard the conflicting
// checkpoint message and display a warning message. This precaution controls
// the damage to network caused by operator mistake or compromised key.
//
// Operations
//
// Checkpoint master key can be established by using the 'makekeypair' command
// The public key in source code should then be updated and private key kept
// in a safe place.
//
// Any node can be turned into checkpoint master by setting the 'checkpointkey'
// configuration parameter with the private key of the checkpoint master key.
// Operator should exercise caution such that at any moment there is at most
// one node operating as checkpoint master. When switching master node, the
// recommended procedure is to shutdown the master node and restart as
// regular node, note down the current checkpoint by 'getcheckpoint', then
// compare to the checkpoint at the new node to be upgraded to master node.
// When the checkpoint on both nodes match then it is safe to switch the new
// node to checkpoint master.
//
// The configuration parameter 'checkpointdepth' specifies how many blocks
// should the checkpoints lag behind the latest block in auto checkpoint mode.
// A depth of 0 is the minimum auto checkpoint policy and offers the strongest
// protection against 51% attack. A negative depth means that the checkpoints
// should not be automatically generated by the checkpoint master, but instead
// be manually entered by operator via the 'sendcheckpoint' command. The manual
// mode is also the default mode (default value -1 for checkpointdepth).
//
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "checkpointsync.h"
#include "base58.h"
#include "main.h"
#include "txdb.h"
#include "uint256.h"
#include "txmempool.h"
#include "consensus/validation.h"
#include "consensus/consensus.h"
#include <univalue.h>
using namespace std;
// Synchronized checkpoint (centrally broadcasted)
string CSyncCheckpoint::strMasterPrivKey = "";
uint256 hashSyncCheckpoint = ArithToUint256(arith_uint256(0));
uint256 hashPendingCheckpoint = ArithToUint256(arith_uint256(0));
CSyncCheckpoint checkpointMessage;
CSyncCheckpoint checkpointMessagePending;
uint256 hashInvalidCheckpoint = ArithToUint256(arith_uint256(0));
string strCheckpointWarning;
// Only descendant of current sync-checkpoint is allowed
bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
{
if (!mapBlockIndex.count(hashSyncCheckpoint))
return error("%s: block index missing for current sync-checkpoint %s", __func__, hashSyncCheckpoint.ToString());
if (!mapBlockIndex.count(hashCheckpoint))
return error("%s: block index missing for received sync-checkpoint %s", __func__, hashCheckpoint.ToString());
CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
{
// Received an older checkpoint, trace back from current checkpoint
// to the same height of the received checkpoint to verify
// that current checkpoint should be a descendant block
if (!chainActive.Contains(pindexCheckpointRecv))
{
hashInvalidCheckpoint = hashCheckpoint;
return error("%s: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", __func__, hashCheckpoint.ToString(), hashSyncCheckpoint.ToString());
}
return false; // ignore older checkpoint
}
// Received checkpoint should be a descendant block of the current
// checkpoint. Trace back to the same height of current checkpoint
// to verify.
CBlockIndex* pindex = pindexCheckpointRecv;
while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
if (!(pindex = pindex->pprev))
return error("%s: pprev2 null - block index structure failure", __func__);
if (pindex->GetBlockHash() != hashSyncCheckpoint)
{
hashInvalidCheckpoint = hashCheckpoint;
return error("%s: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", __func__, hashCheckpoint.ToString(), hashSyncCheckpoint.ToString());
}
return true;
}
bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
{
if (!pblocktree->WriteSyncCheckpoint(hashCheckpoint))
return error("%s: failed to write to txdb sync checkpoint %s", __func__, hashCheckpoint.ToString());
if (!pblocktree->Sync())
return error("%s: failed to commit to txdb sync checkpoint %s", __func__, hashCheckpoint.ToString().c_str());
hashSyncCheckpoint = hashCheckpoint;
return true;
}
bool AcceptPendingSyncCheckpoint()
{
LOCK(cs_main);
bool havePendingCheckpoint = hashPendingCheckpoint != ArithToUint256(arith_uint256(0)) && mapBlockIndex.count(hashPendingCheckpoint);
if (!havePendingCheckpoint)
return false;
if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
{
hashPendingCheckpoint = ArithToUint256(arith_uint256(0));
checkpointMessagePending.SetNull();
return false;
}
if (!chainActive.Contains(mapBlockIndex[hashPendingCheckpoint]))
return false;
if (!WriteSyncCheckpoint(hashPendingCheckpoint))
return error("%s: failed to write sync checkpoint %s", __func__, hashPendingCheckpoint.ToString());
hashPendingCheckpoint = ArithToUint256(arith_uint256(0));
checkpointMessage = checkpointMessagePending;
checkpointMessagePending.SetNull();
// Relay the checkpoint
if (!checkpointMessage.IsNull())
{
BOOST_FOREACH(CNode* pnode, vNodes)
checkpointMessage.RelayTo(pnode);
}
return true;
}
// Automatically select a suitable sync-checkpoint
uint256 AutoSelectSyncCheckpoint()
{
// Search backward for a block with specified depth policy
const CBlockIndex *pindex = chainActive.Tip();
while (pindex->pprev && pindex->nHeight + (int)GetArg("-checkpointdepth", -1) > chainActive.Tip()->nHeight)
pindex = pindex->pprev;
return pindex->GetBlockHash();
}
// Check against synchronized checkpoint
bool CheckSyncCheckpoint(const CBlockIndex* pindexNew)
{
LOCK(cs_main);
assert(pindexNew != NULL);
if (pindexNew->nHeight == 0)
return true;
const uint256& hashBlock = pindexNew->GetBlockHash();
int nHeight = pindexNew->nHeight;
// Checkpoint should always be accepted block
assert(mapBlockIndex.count(hashSyncCheckpoint));
const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
// Blocks could have been rewound on startup, do not
// return or false here or block could be marked invalid
if (!chainActive.Contains(pindexSync))
return true;
if (nHeight > pindexSync->nHeight)
{
// Trace back to same height as sync-checkpoint
const CBlockIndex* pindex = pindexNew;
while (pindex->nHeight > pindexSync->nHeight && !chainActive.Contains(pindex))
if (!(pindex = pindex->pprev))
return error("%s: pprev null - block index structure failure", __func__);
// at this point we could have:
// 1. found block in our blockchain
// 2. reached pindexSync->nHeight without finding it
if (!chainActive.Contains(pindex))
return error("%s: Only descendants of checkpoint accepted", __func__);
}
if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
return error("%s: Same height with sync-checkpoint", __func__);
if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
return error("%s: Lower height than sync-checkpoint", __func__);
return true;
}
// Reset synchronized checkpoint to last hardened checkpoint
bool ResetSyncCheckpoint()
{
LOCK(cs_main);
if (!WriteSyncCheckpoint(Params().GetConsensus().hashGenesisBlock))
return error("%s: failed to write sync checkpoint %s", __func__, Params().GetConsensus().hashGenesisBlock.ToString());
return true;
}
// Verify sync checkpoint master pubkey and reset sync checkpoint if changed
bool CheckCheckpointPubKey()
{
string strPubKey = "";
string strMasterPubKey = Params().GetConsensus().checkpointPubKey;
if (!pblocktree->ReadCheckpointPubKey(strPubKey) || strPubKey != strMasterPubKey)
{
// write checkpoint master key to db
if (!pblocktree->WriteCheckpointPubKey(strMasterPubKey))
return error("%s: failed to write new checkpoint master key to db", __func__);
if (!pblocktree->Sync())
return error("%s: failed to commit new checkpoint master key to db", __func__);
if (!ResetSyncCheckpoint())
return error("%s: failed to reset sync-checkpoint", __func__);
}
return true;
}
bool SetCheckpointPrivKey(string strPrivKey)
{
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(strPrivKey))
return error("%s: Checkpoint master key invalid", __func__);
CKey key = vchSecret.GetKey();
if (!key.IsValid())
return false;
CSyncCheckpoint::strMasterPrivKey = strPrivKey;
return true;
}
bool SendSyncCheckpoint(uint256 hashCheckpoint)
{
CSyncCheckpoint checkpoint;
checkpoint.hashCheckpoint = hashCheckpoint;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedSyncCheckpoint)checkpoint;
checkpoint.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
if (CSyncCheckpoint::strMasterPrivKey.empty())
return error("%s: Checkpoint master key unavailable.", __func__);
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(CSyncCheckpoint::strMasterPrivKey))
return error("%s: Checkpoint master key invalid", __func__);
CKey key = vchSecret.GetKey(); // If key is not correct openssl may crash
if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
return error("%s: Unable to sign checkpoint, check private key?", __func__);
if (!checkpoint.ProcessSyncCheckpoint())
return error("%s: Failed to process checkpoint.", __func__);
// Relay checkpoint
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
return true;
}
// Verify signature of sync-checkpoint message
bool CSyncCheckpoint::CheckSignature()
{
string strMasterPubKey = Params().GetConsensus().checkpointPubKey;
CPubKey key(ParseHex(strMasterPubKey));
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
return error("%s: verify signature failed", __func__);
// Now unserialize the data
CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
sMsg >> *(CUnsignedSyncCheckpoint*)this;
return true;
}
// Process synchronized checkpoint
bool CSyncCheckpoint::ProcessSyncCheckpoint()
{
if (!CheckSignature())
return false;
LOCK(cs_main);
if (!mapBlockIndex.count(hashCheckpoint))
{
LogPrintf("Missing headers for received sync-checkpoint %s\n", hashCheckpoint.ToString());
return false;
}
if (!ValidateSyncCheckpoint(hashCheckpoint))
return false;
bool pass = chainActive.Contains(mapBlockIndex[hashCheckpoint]);
if (!pass) {
// We haven't received the checkpoint chain, keep the checkpoint as pending
hashPendingCheckpoint = hashCheckpoint;
checkpointMessagePending = *this;
LogPrintf("%s: pending for sync-checkpoint %s\n", __func__, hashCheckpoint.ToString());
return false;
}
if (!WriteSyncCheckpoint(hashCheckpoint))
return error("%s: failed to write sync checkpoint %s", __func__, hashCheckpoint.ToString());
checkpointMessage = *this;
hashPendingCheckpoint = ArithToUint256(arith_uint256(0));
checkpointMessagePending.SetNull();
return true;
}