main.h 15.1 KB
Newer Older
Tom Zander's avatar
Tom Zander committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * This file is part of the Flowee project
 * Copyright (C) 2009-2010 Satoshi Nakamoto
 * Copyright (C) 2009-2015 The Bitcoin Core developers
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
19

20 21
#ifndef FLOWEE_MAIN_H
#define FLOWEE_MAIN_H
22

23
#if defined(HAVE_CONFIG_H)
24
#include "config/flowee-config.h"
25 26
#endif

27
#include "amount.h"
28
#include "chain.h"
29
#include "net.h"
Jorge Timón's avatar
Jorge Timón committed
30
#include "script/script_error.h"
31
#include "sync.h"
32

33 34 35 36
#include <algorithm>
#include <exception>
#include <map>
#include <set>
37
#include <cstdint>
38 39 40
#include <string>
#include <utility>
#include <vector>
s_nakamoto's avatar
s_nakamoto committed
41

42
#include <boost/atomic.hpp>
43 44
#include <boost/unordered_map.hpp>

45 46
#include <script/interpreter.h>

s_nakamoto's avatar
s_nakamoto committed
47
class CBlockIndex;
48
class CBloomFilter;
49
class CChainParams;
50
class CInv;
51
class CScriptCheck;
52
class CTxMemPool;
Tom Zander's avatar
Tom Zander committed
53
class ValidationInterface;
54
class CValidationState;
55
class UnspentOutputDatabase;
56 57

struct CNodeStateStats;
Alex Morcos's avatar
Alex Morcos committed
58
struct LockPoints;
59

Tom Zander's avatar
Tom Zander committed
60 61
/** The maximum size of a blk?????.dat file */
static const unsigned int MAX_BLOCKFILE_SIZE = 0x40000000; // 1024 MiB
62

63
/** Number of blocks that can be requested at any given time from a single peer. */
Pieter Wuille's avatar
Pieter Wuille committed
64 65
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
/** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
66
static const unsigned int BLOCK_STALLING_TIMEOUT = 6;
Pieter Wuille's avatar
Pieter Wuille committed
67
/** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
Corinne Dashjr's avatar
Corinne Dashjr committed
68
 *  less than this number, we reached its tip. Changing this value is a protocol upgrade. */
Pieter Wuille's avatar
Pieter Wuille committed
69 70 71 72 73 74
static const unsigned int MAX_HEADERS_RESULTS = 2000;
/** Size of the "block download window": how far ahead of our current height do we fetch?
 *  Larger windows tolerate larger download speed differences between peer, but increase the potential
 *  degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
 *  harder). We'll probably want to make this a per-peer adaptive value at some point. */
static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
75 76 77 78
/** Time to wait (in seconds) between writing blocks/block index to disk. */
static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
/** Time to wait (in seconds) between flushing chainstate to disk. */
static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
79 80
/** Maximum length of reject messages. */
static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
81 82 83 84 85 86 87
/** Average delay between local address broadcasts in seconds. */
static const unsigned int AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24 * 24 * 60;
/** Average delay between peer address broadcasts in seconds. */
static const unsigned int AVG_ADDRESS_BROADCAST_INTERVAL = 30;
/** Average delay between trickled inventory broadcasts in seconds.
 *  Blocks, whitelisted receivers, and a random 25% of transactions bypass this. */
static const unsigned int AVG_INVENTORY_BROADCAST_INTERVAL = 5;
88 89
/** Block download timeout base, expressed in millionths of the block interval (i.e. 10 min) */
static const int64_t BLOCK_DOWNLOAD_TIMEOUT_BASE = 1000000;
90 91
/** Additional block download timeout per parallel downloading peer (i.e. 5 min) */
static const int64_t BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 500000;
92

93 94 95
/** Maximum number of headers to announce when relaying blocks with headers message.*/
static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;

s_nakamoto's avatar
s_nakamoto committed
96
extern CCriticalSection cs_main;
97
extern CTxMemPool mempool;
98 99
extern uint64_t nLastBlockTx;
extern uint64_t nLastBlockSize;
100
extern const std::string strMessageMagic;
101 102
extern CWaitableCriticalSection csBestBlock;
extern CConditionVariable cvBlockChange;
103
extern bool fIsBareMultisigStd;
104
extern bool fRequireStandard;
105
extern bool fCheckpointsEnabled;
Gavin Andresen's avatar
Gavin Andresen committed
106
extern CFeeRate minRelayTxFee;
s_nakamoto's avatar
s_nakamoto committed
107

Peter Tschipper's avatar
Peter Tschipper committed
108 109 110
// Xpress Validation: begin section
/**
 * Transactions that have already been accepted into the memory pool do not need to be
111
 * re-verified and can avoid having to do a second and expensive CheckInputs() when
Peter Tschipper's avatar
Peter Tschipper committed
112 113 114
 * processing a new block.  (Protected by cs_main)
 */
static std::set<uint256> setPreVerifiedTxHash;
115 116 117 118 119 120
/**
 * Orphans that are added to the thinblock must be verifed since they have never been
 *  accepted into the memory pool.
 */
static std::set<uint256> setUnVerifiedOrphanTxHash;
// BU - Xpress Validation: end section
Peter Tschipper's avatar
Peter Tschipper committed
121

122
/** Best header we've seen so far (used for getheaders queries' starting points). */
123 124
extern CBlockIndex *pindexBestHeader;

125
/** Minimum disk space required - used in CheckDiskSpace() */
126
static const uint64_t nMinDiskSpace = 52428800;
s_nakamoto's avatar
s_nakamoto committed
127

128 129 130 131 132
/** Register with a network node to receive its signals */
void RegisterNodeSignals(CNodeSignals& nodeSignals);
/** Unregister a network node */
void UnregisterNodeSignals(CNodeSignals& nodeSignals);

133 134 135 136 137
/** 
 * Process an incoming block. This only returns after the best known valid
 * block is made active. Note that it does not, however, guarantee that the
 * specific block passed to it has been checked for validity!
 * 
138
 * @param[out]  state   This may be set to an Error state if any error occurred processing it, including during validation/connection/etc of otherwise unrelated blocks during reorganisation; or it may be set to an Invalid state if pblock is itself invalid (but this is not guaranteed even when the block is checked). If you want to *possibly* get feedback on whether pblock is valid, you must also install a CValidationInterface (see validationinterface.h) - this will have its BlockChecked method called whenever *any* block completes validation.
139 140
 * @param[in]   pfrom   The node which we are receiving the block from; it is added to mapBlockSource and may be penalised if the block is invalid.
 * @param[in]   pblock  The block we want to process.
141
 * @param[in]   fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
142 143 144
 * @param[out]  dbp     If pblock is stored to disk (or already there), this will be set to its location.
 * @return True if state.IsValid()
 */
145
bool ProcessNewBlock(CValidationState& state, const CChainParams& chainparams, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos* dbp);
146
/** Check whether enough disk space is available for an incoming block */
147
bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
148
/** Initialize a new block tree database + block data on disk */
149
bool InitBlockIndex(const CChainParams& chainparams);
150
/** Load the block tree and coins database from disk */
151
bool LoadBlockIndexDB(const UnspentOutputDatabase *utxo);
152 153
/** Unload database information */
void UnloadBlockIndex();
154
/** Process protocol messages received from a given node */
s_nakamoto's avatar
s_nakamoto committed
155
bool ProcessMessages(CNode* pfrom);
156 157 158 159 160
/**
 * Send queued protocol messages to be sent to a give node.
 *
 * @param[in]   pto             The node which we are sending messages to.
 */
161
bool SendMessages(CNode* pto);
162
/** Try to detect Partition (network isolation) attacks against us */
163
void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing);
fanquake's avatar
fanquake committed
164
/** Check whether we are doing an initial block download (synchronizing from disk or network) */
s_nakamoto's avatar
s_nakamoto committed
165
bool IsInitialBlockDownload();
166 167 168 169 170 171 172
/** Format a string that describes several potential problems detected by the core.
 * strFor can have three values:
 * - "rpc": get critical warnings, which should put the client in safe mode if non-empty
 * - "statusbar": get all warnings
 * - "gui": get all warnings, translated (where possible) for GUI
 * This function only returns the highest priority warning of the set selected by strFor.
 */
173
std::string GetWarnings(const std::string& strFor);
174
/** Find the best known block, and make it the tip of the block chain */
175
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
176

177 178 179
bool MarkBlockAsReceived(const uint256& hash);
bool IsBlockInFlight(const uint256 &hash);

Pieter Wuille's avatar
Pieter Wuille committed
180 181
/** Get statistics from node state */
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
182 183
/** Increase a node's misbehavior score. */
void Misbehaving(NodeId nodeid, int howmuch);
184 185
/** Flush all state, indexes and buffers to disk. */
void FlushStateToDisk();
186

187 188 189 190 191
void queueRejectMessage(int peerId, const uint256 &blockHash, std::uint8_t rejectCode, const std::string &rejectReason);

class CBlockUndo;
bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart);

192 193
/** (try to) add transaction to memory pool **/
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
194
                        bool* pfMissingInputs, bool fOverrideMempoolLimit=false, bool fRejectAbsurdFee=false);
195
void AlertNotify(const std::string& strMessage, bool fThread);
s_nakamoto's avatar
s_nakamoto committed
196

Pieter Wuille's avatar
Pieter Wuille committed
197 198
struct CNodeStateStats {
    int nMisbehavior;
Pieter Wuille's avatar
Pieter Wuille committed
199
    int nSyncHeight;
200 201
    int nCommonHeight;
    std::vector<int> vHeightInFlight;
Pieter Wuille's avatar
Pieter Wuille committed
202 203
};

204 205 206 207
struct CDiskTxPos : public CDiskBlockPos
{
    unsigned int nTxOffset; // after header

Søren Bredlund Caspersen's avatar
Søren Bredlund Caspersen committed
208
    ADD_SERIALIZE_METHODS
Kamil Domanski's avatar
Kamil Domanski committed
209

210
    template <typename Stream, typename Operation>
211
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
212 213
        READWRITE(*(CDiskBlockPos*)this);
        READWRITE(VARINT(nTxOffset));
Kamil Domanski's avatar
Kamil Domanski committed
214
    }
215 216 217 218 219 220 221

    CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
    }

    CDiskTxPos() {
        SetNull();
    }
s_nakamoto's avatar
s_nakamoto committed
222

223 224 225 226 227
    void SetNull() {
        CDiskBlockPos::SetNull();
        nTxOffset = 0;
    }
};
s_nakamoto's avatar
s_nakamoto committed
228 229


230
/** Context-independent validity checks */
231
bool CheckTransaction(const CTransaction& tx, CValidationState& state);
Pieter Wuille's avatar
Pieter Wuille committed
232

233 234 235 236 237 238 239 240 241 242
/**
 * Check if transaction is final and can be included in a block with the
 * specified height and time. Consensus critical.
 */
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);

/**
 * Check if transaction will be final in the next block to be created.
 *
 * Calls IsFinalTx() with current block height and appropriate block time.
243 244
 *
 * See consensus/consensus.h for flag definitions.
245
 */
246
bool CheckFinalTx(const CTransaction &tx, int flags = -1);
Pieter Wuille's avatar
Pieter Wuille committed
247

Alex Morcos's avatar
Alex Morcos committed
248 249 250 251
/**
 * Test whether the LockPoints height and time are still valid on the current chain
 */
bool TestLockPointValidity(const LockPoints* lp);
252 253 254 255 256 257 258 259 260 261

/**
 * Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
 * Consensus critical. Takes as input a list of heights at which tx's inputs (in order) confirmed.
 */
bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block);

/**
 * Check if transaction will be BIP 68 final in the next block to be created.
 *
Alex Morcos's avatar
Alex Morcos committed
262
 * Simulates calling SequenceLocks() with data from the tip of the current active chain.
Alex Morcos's avatar
Alex Morcos committed
263 264 265 266
 * Optionally stores in LockPoints the resulting height and time calculated and the hash
 * of the block needed for calculation or skips the calculation and uses the LockPoints
 * passed in for evaluation.
 * The LockPoints should not be considered valid if CheckSequenceLocks returns false.
267 268 269
 *
 * See consensus/consensus.h for flag definitions.
 */
270
bool CheckSequenceLocks(CTxMemPool &mp, const CTransaction &tx, int flags, LockPoints* lp = nullptr, bool useExistingLockPoints = false, CBlockIndex *tip = nullptr);
271

s_nakamoto's avatar
s_nakamoto committed
272

273
/** Functions for disk access for blocks */
274 275
bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams);
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
s_nakamoto's avatar
s_nakamoto committed
276

277 278
/** Functions for validating blocks and updating the block tree */

279
/** Context-independent validity checks */
280
bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
281

282
/** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
283
bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
284

285
/**  Mark this index as 'dirty' to be saved to disk soon */
286
void MarkIndexUnsaved(CBlockIndex *index);
287

Pieter Wuille's avatar
Pieter Wuille committed
288 289 290
class CBlockFileInfo
{
public:
291 292 293
    unsigned int nBlocks;      //! number of blocks stored in file
    unsigned int nSize;        //! number of used bytes of block file
    unsigned int nUndoSize;    //! number of used bytes in the undo file
Pieter Wuille's avatar
Pieter Wuille committed
294

Søren Bredlund Caspersen's avatar
Søren Bredlund Caspersen committed
295
    ADD_SERIALIZE_METHODS
Kamil Domanski's avatar
Kamil Domanski committed
296

297
    template <typename Stream, typename Operation>
298
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
Pieter Wuille's avatar
Pieter Wuille committed
299 300 301
        READWRITE(VARINT(nBlocks));
        READWRITE(VARINT(nSize));
        READWRITE(VARINT(nUndoSize));
Kamil Domanski's avatar
Kamil Domanski committed
302
    }
Pieter Wuille's avatar
Pieter Wuille committed
303 304 305 306 307 308 309 310 311 312 313

     void SetNull() {
         nBlocks = 0;
         nSize = 0;
         nUndoSize = 0;
     }

     CBlockFileInfo() {
         SetNull();
     }

314
     std::string ToString() const;
Pieter Wuille's avatar
Pieter Wuille committed
315

316
     /** update statistics (does not update nSize) */
317
     void AddBlock() {
Pieter Wuille's avatar
Pieter Wuille committed
318 319 320 321
         nBlocks++;
     }
};

Tom Zander's avatar
Tom Zander committed
322 323 324 325 326 327
extern CCriticalSection cs_LastBlockFile;
extern std::vector<CBlockFileInfo> vinfoBlockFile;
extern int nLastBlockFile;
extern std::set<int> setDirtyFileInfo;


jtimon's avatar
jtimon committed
328 329
/** Find the last common block between the parameter chain and a locator. */
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
s_nakamoto's avatar
s_nakamoto committed
330

331
/** Mark a block as invalid. */
332
// bool InvalidateBlock(CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex *pindex);
333 334

/** Remove invalidity status from a block and its descendants. */
335
// bool ReconsiderBlock(CBlockIndex *pindex);
336

337
/** The currently-connected chain of blocks (protected by cs_main). */
338
extern CChain chainActive;
s_nakamoto's avatar
s_nakamoto committed
339

340 341
class UnspentOutputDatabase;
extern UnspentOutputDatabase *g_utxo;
342

343 344
void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age);

345 346 347 348 349 350
/** Reject codes greater or equal to this can be returned by AcceptToMemPool
 * for transactions, to signal internal conditions. They cannot and should not
 * be sent over the P2P network.
 */
static const unsigned int REJECT_INTERNAL = 0x100;
/** Too high fee. Can not be triggered by P2P transactions */
351
static const unsigned int REJECT_HIGHFEE = 0x100;
352 353 354 355
/** Transaction is already known (either in mempool or blockchain) */
static const unsigned int REJECT_ALREADY_KNOWN = 0x101;
/** Transaction conflicts with a transaction already known */
static const unsigned int REJECT_CONFLICT = 0x102;
356

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
enum FlushStateMode {
    FLUSH_STATE_NONE,
    FLUSH_STATE_IF_NEEDED,
    FLUSH_STATE_PERIODIC,
    FLUSH_STATE_ALWAYS
};
/**
 * Update the on-disk chain state.
 * The caches and indexes are flushed depending on the mode we're called with
 * if they're too large, if it's been a while since the last write,
 * or always and in all cases if we're in prune mode and are deleting files.
 */
bool FlushStateToDisk(CValidationState &state, FlushStateMode mode);

void CheckForkWarningConditions();
void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip);

374
#endif