Files

464 lines
14 KiB
C++
Raw Permalink Normal View History

2017-11-09 19:34:51 +01:00
/*
* This file is part of the Flowee project
* Copyright (C) 2009-2010 Satoshi Nakamoto
* Copyright (C) 2009-2015 The Bitcoin Core developers
2021-03-08 18:14:47 +01:00
* Copyright (C) 2019-2021 Tom Zander <tom@flowee.org>
2017-11-09 19:34:51 +01:00
*
* 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/>.
*/
2018-01-16 10:47:52 +00:00
#ifndef FLOWEE_CHAIN_H
#define FLOWEE_CHAIN_H
2014-12-16 15:43:03 +01:00
#include "arith_uint256.h"
#include "pow.h"
#include "blocklocator.h"
#include <primitives/MutableBlock.h>
2019-04-02 19:56:36 +02:00
#include <tinyformat.h>
#include <uint256.h>
#include <Logger.h>
#include <vector>
2019-04-02 19:56:36 +02:00
#include <atomic>
2019-06-11 22:17:09 +02:00
#include <mutex>
struct CDiskBlockPos
{
int nFile;
unsigned int nPos;
2017-01-19 21:40:34 +01:00
ADD_SERIALIZE_METHODS
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(VARINT(nFile));
READWRITE(VARINT(nPos));
}
CDiskBlockPos() {
SetNull();
}
CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
nFile = nFileIn;
nPos = nPosIn;
}
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return (a.nFile == b.nFile && a.nPos == b.nPos);
}
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return !(a == b);
}
void SetNull() { nFile = -1; nPos = 0; }
bool IsNull() const { return (nFile == -1); }
std::string ToString() const
{
return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos);
}
};
enum BlockStatus {
//! Unused.
BLOCK_VALID_UNKNOWN = 0,
2014-07-12 00:02:35 +02:00
//! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
2014-07-12 00:02:35 +02:00
BLOCK_VALID_HEADER = 1,
//! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
//! are also at least TREE.
2014-07-12 00:02:35 +02:00
BLOCK_VALID_TREE = 2,
/**
* Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
* sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
* parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
*/
2014-07-12 00:02:35 +02:00
BLOCK_VALID_TRANSACTIONS = 3,
2015-04-28 14:47:17 +00:00
//! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30.
//! Implies all parents are also at least CHAIN.
2014-07-12 00:02:35 +02:00
BLOCK_VALID_CHAIN = 4,
//! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
2014-07-12 00:02:35 +02:00
BLOCK_VALID_SCRIPTS = 5,
//! All validity bits.
BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat
2021-03-08 18:14:47 +01:00
BLOCK_HAVE_METADATA = 128, //! metadata available in blk*.dat
BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO | BLOCK_HAVE_METADATA,
BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, //! descends from failed block
BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. A blockindex may have multiple pprev pointing
* to it, but at most one of them can be part of the currently active branch.
*/
class CBlockIndex
{
public:
//! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
const uint256* phashBlock;
//! pointer to the index of the predecessor of this block
CBlockIndex* pprev;
//! pointer to the index of some further predecessor of this block
CBlockIndex* pskip;
//! height of the entry in the chain. The genesis block has height 0
int nHeight;
//! Which # file this block is stored in (blk?????.dat)
int nFile;
//! Byte offset within blk?????.dat where this block's data is stored
unsigned int nDataPos;
//! Byte offset within rev?????.dat where this block's undo data is stored
unsigned int nUndoPos;
2021-03-08 18:14:47 +01:00
unsigned int nMetaDataFile;
//! Byte offset within inf?????.dat where this block's metadata is stored
unsigned int nMetaDataPos;
//! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
2014-12-16 15:43:03 +01:00
arith_uint256 nChainWork;
//! Number of transactions in this block.
//! Note: in a potential headers-first mode, this number cannot be relied upon
unsigned int nTx;
//! (memory only) Number of transactions in the chain up to and including this block.
//! This value will be non-zero only if and only if transactions for this block and all its parents are available.
//! Change to 64-bit type when necessary; won't happen before 2030
unsigned int nChainTx;
2020-02-27 13:35:56 +01:00
//! (memory only) Verification status of this block. See enum BlockStatus
unsigned int nStatus;
//! block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
//! (memory only) Sequential id assigned to distinguish order in which blocks are received.
uint32_t nSequenceId;
void SetNull()
{
2019-06-11 22:17:09 +02:00
phashBlock = nullptr;
pprev = nullptr;
pskip = nullptr;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
2021-03-08 18:14:47 +01:00
nMetaDataFile = 0;
nMetaDataPos = 0;
2014-12-16 15:43:03 +01:00
nChainWork = arith_uint256();
nTx = 0;
nChainTx = 0;
nStatus = 0;
nSequenceId = 0;
nVersion = 0;
hashMerkleRoot = uint256();
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex()
{
SetNull();
}
CBlockIndex(const BlockHeaderFields& block)
{
SetNull();
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CDiskBlockPos GetBlockPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_DATA) {
ret.nFile = nFile;
ret.nPos = nDataPos;
}
return ret;
}
CDiskBlockPos GetUndoPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_UNDO) {
ret.nFile = nFile;
ret.nPos = nUndoPos;
}
return ret;
}
2021-03-08 18:14:47 +01:00
CDiskBlockPos GetMetaDataPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_METADATA) {
ret.nFile = nMetaDataFile;
ret.nPos = nMetaDataPos;
}
return ret;
}
BlockHeaderFields GetBlockHeader() const
{
BlockHeaderFields block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
enum { nMedianTimeSpan=11 };
int64_t GetMedianTimePast() const
{
int64_t pmedian[nMedianTimeSpan];
int64_t* pbegin = &pmedian[nMedianTimeSpan];
int64_t* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
std::string ToString() const
{
return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, nHeight,
hashMerkleRoot.ToString(),
GetBlockHash().ToString());
}
//! Check whether this block index entry is valid up to the passed validity level.
bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
}
//! Raise the validity level of this block index entry.
//! Returns true if the validity was changed.
bool RaiseValidity(enum BlockStatus nUpTo)
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
return true;
}
return false;
}
//! Build the skiplist pointer for this entry.
void BuildSkip();
//! Efficiently find an ancestor of this block.
CBlockIndex* GetAncestor(int height);
const CBlockIndex* GetAncestor(int height) const;
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
CDiskBlockIndex() {
hashPrev = uint256();
}
2014-11-25 16:26:20 +01:00
explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
}
2017-01-19 21:40:34 +01:00
ADD_SERIALIZE_METHODS
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
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));
2021-03-08 18:14:47 +01:00
if (nStatus & BLOCK_HAVE_METADATA) {
READWRITE(VARINT(nMetaDataFile));
READWRITE(VARINT(nMetaDataPos));
}
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
}
uint256 GetBlockHash() const
{
BlockHeaderFields block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
2021-11-02 09:28:35 +01:00
return block.createHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s)",
GetBlockHash().ToString(),
hashPrev.ToString());
return str;
}
};
/** An in-memory indexed chain of blocks. */
class CChain {
private:
2019-06-11 22:17:09 +02:00
std::vector<CBlockIndex*> m_chain;
2019-04-02 19:56:36 +02:00
std::atomic<CBlockIndex *> m_tip;
2019-12-01 14:48:03 +01:00
mutable std::recursive_mutex m_lock;
public:
2019-04-02 19:56:36 +02:00
CChain();
CChain(const CChain &o);
2019-06-11 22:17:09 +02:00
/** Returns the index entry for the genesis block of this chain, or nullptr if none. */
CBlockIndex *Genesis() const {
2019-06-11 22:17:09 +02:00
return m_chain.size() > 0 ? m_chain[0] : nullptr;
}
2019-06-11 22:17:09 +02:00
/** Returns the index entry for the tip of this chain, or nullptr if none. */
CBlockIndex *Tip() const {
2019-06-11 22:17:09 +02:00
return m_tip.load();
}
2019-06-11 22:17:09 +02:00
/** Returns the index entry at a particular height in this chain, or nullptr if no such height exists. */
CBlockIndex *operator[](int nHeight) const {
2019-12-01 14:48:03 +01:00
std::lock_guard<std::recursive_mutex> lock(m_lock);
2019-06-11 22:17:09 +02:00
if (nHeight < 0 || nHeight >= (int)m_chain.size())
return nullptr;
return m_chain[nHeight];
}
/** Compare two chains efficiently. */
friend bool operator==(const CChain &a, const CChain &b) {
2019-06-11 22:17:09 +02:00
return a.m_chain.size() == b.m_chain.size() &&
a.m_chain[a.m_chain.size() - 1] == b.m_chain[b.m_chain.size() - 1];
}
/** Efficiently check whether a block is present in this chain. */
bool Contains(const CBlockIndex *pindex) const {
return (*this)[pindex->nHeight] == pindex;
}
2019-06-11 22:17:09 +02:00
/** Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip. */
CBlockIndex *Next(const CBlockIndex *pindex) const {
2019-12-01 14:48:03 +01:00
std::lock_guard<std::recursive_mutex> lock(m_lock);
2019-06-13 00:39:36 +02:00
if (!pindex || pindex->nHeight < 0 || pindex->nHeight + 1>= (int)m_chain.size())
2019-06-11 22:17:09 +02:00
return nullptr;
if (m_chain[pindex->nHeight] == pindex)
2019-06-13 00:39:36 +02:00
return m_chain[pindex->nHeight + 1];
2019-06-11 22:17:09 +02:00
return nullptr;
}
/** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
int Height() const {
2019-04-02 19:56:36 +02:00
auto tip = m_tip.load();
if (tip)
return tip->nHeight;
return -1;
}
2014-10-19 21:41:37 -04:00
/** Set/initialize a chain with a given tip. */
void SetTip(CBlockIndex *pindex);
/** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
2019-06-11 22:17:09 +02:00
CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const;
/** Find the last common block between this chain and a block index entry. */
const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
};
2018-01-15 15:26:12 +00:00
inline Log::SilentItem operator<<(Log::SilentItem item, const CDiskBlockPos&) { return item; }
inline Log::Item operator<<(Log::Item item, const CDiskBlockPos &pos) {
const bool old = item.useSpace();
item.nospace() << "DiskBlockPos(file=" << pos.nFile << ", offset=" << pos.nPos << ")";
if (old)
return item.space();
return item;
}
2018-01-16 10:47:52 +00:00
#endif