Dogecoin Core  1.14.2
P2P Digital Currency
auxpow.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 Vince Durham
3 // Copyright (c) 2009-2014 The Bitcoin developers
4 // Copyright (c) 2014-2016 Daniel Kraft
5 // Distributed under the MIT/X11 software license, see the accompanying
6 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 
8 #include "auxpow.h"
9 
10 #include "chainparams.h"
11 #include "compat/endian.h"
12 #include "consensus/consensus.h"
13 #include "consensus/merkle.h"
14 #include "consensus/validation.h"
15 #include "hash.h"
16 #include "script/script.h"
17 #include "txmempool.h"
18 #include "util.h"
19 #include "utilstrencodings.h"
20 #include "validation.h"
21 
22 #include <algorithm>
23 
24 /* Moved from wallet.cpp. CMerkleTx is necessary for auxpow, independent
25  of an enabled (or disabled) wallet. Always include the code. */
26 
27 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
28 
29 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
30 {
31  // Update the tx's hashBlock
32  hashBlock = pindex->GetBlockHash();
33 
34  // set the position of the transaction in the block
35  nIndex = posInBlock;
36 }
37 
38 void CMerkleTx::InitMerkleBranch(const CBlock& block, int posInBlock)
39 {
40  hashBlock = block.GetHash();
41  nIndex = posInBlock;
43 }
44 
45 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
46 {
47  if (hashUnset())
48  return 0;
49 
51 
52  // Find the block it claims to be in
53  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
54  if (mi == mapBlockIndex.end())
55  return 0;
56  CBlockIndex* pindex = (*mi).second;
57  if (!pindex || !chainActive.Contains(pindex))
58  return 0;
59 
60  pindexRet = pindex;
61  return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
62 }
63 
65 {
66  if (!IsCoinBase())
67  return 0;
68  int nCoinbaseMaturity = Params().GetConsensus(chainActive.Height()).nCoinbaseMaturity;
69  return std::max(0, (nCoinbaseMaturity + 1) - GetDepthInMainChain());
70 }
71 
72 
74 {
75  return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);
76 }
77 
78 /* ************************************************************************** */
79 
80 bool
81 CAuxPow::check(const uint256& hashAuxBlock, int nChainId,
82  const Consensus::Params& params) const
83 {
84  if (nIndex != 0)
85  return error("AuxPow is not a generate");
86 
87  if (params.fStrictChainId && parentBlock.GetChainId () == nChainId)
88  return error("Aux POW parent has our chain ID");
89 
90  if (vChainMerkleBranch.size() > 30)
91  return error("Aux POW chain merkle branch too long");
92 
93  // Check that the chain merkle root is in the coinbase
94  const uint256 nRootHash
96  std::vector<unsigned char> vchRootHash(nRootHash.begin(), nRootHash.end());
97  std::reverse(vchRootHash.begin(), vchRootHash.end()); // correct endian
98 
99  // Check that we are in the parent block merkle tree
102  return error("Aux POW merkle root incorrect");
103 
104  const CScript script = tx->vin[0].scriptSig;
105 
106  // Check that the same work is not submitted twice to our chain.
107  //
108 
109  CScript::const_iterator pcHead =
110  std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
111 
113  std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end());
114 
115  if (pc == script.end())
116  return error("Aux POW missing chain merkle root in parent coinbase");
117 
118  if (pcHead != script.end())
119  {
120  // Enforce only one chain merkle root by checking that a single instance of the merged
121  // mining header exists just before.
122  if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
123  return error("Multiple merged mining headers in coinbase");
124  if (pcHead + sizeof(pchMergedMiningHeader) != pc)
125  return error("Merged mining header is not just before chain merkle root");
126  }
127  else
128  {
129  // For backward compatibility.
130  // Enforce only one chain merkle root by checking that it starts early in the coinbase.
131  // 8-12 bytes are enough to encode extraNonce and nBits.
132  if (pc - script.begin() > 20)
133  return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase");
134  }
135 
136 
137  // Ensure we are at a deterministic point in the merkle leaves by hashing
138  // a nonce and our chain ID and comparing to the index.
139  pc += vchRootHash.size();
140  if (script.end() - pc < 8)
141  return error("Aux POW missing chain merkle tree size and nonce in parent coinbase");
142 
143  uint32_t nSize;
144  memcpy(&nSize, &pc[0], 4);
145  nSize = le32toh(nSize);
146  const unsigned merkleHeight = vChainMerkleBranch.size();
147  if (nSize != (1u << merkleHeight))
148  return error("Aux POW merkle branch size does not match parent coinbase");
149 
150  uint32_t nNonce;
151  memcpy(&nNonce, &pc[4], 4);
152  nNonce = le32toh (nNonce);
153  if (nChainIndex != getExpectedIndex (nNonce, nChainId, merkleHeight))
154  return error("Aux POW wrong index");
155 
156  return true;
157 }
158 
159 int
160 CAuxPow::getExpectedIndex (uint32_t nNonce, int nChainId, unsigned h)
161 {
162  // Choose a pseudo-random slot in the chain merkle tree
163  // but have it be fixed for a size/nonce/chain combination.
164  //
165  // This prevents the same work from being used twice for the
166  // same chain while reducing the chance that two chains clash
167  // for the same slot.
168 
169  /* This computation can overflow the uint32 used. This is not an issue,
170  though, since we take the mod against a power-of-two in the end anyway.
171  This also ensures that the computation is, actually, consistent
172  even if done in 64 bits as it was in the past on some systems.
173 
174  Note that h is always <= 30 (enforced by the maximum allowed chain
175  merkle branch length), so that 32 bits are enough for the computation. */
176 
177  uint32_t rand = nNonce;
178  rand = rand * 1103515245 + 12345;
179  rand += nChainId;
180  rand = rand * 1103515245 + 12345;
181 
182  return rand % (1 << h);
183 }
184 
185 uint256
187  const std::vector<uint256>& vMerkleBranch,
188  int nIndex)
189 {
190  if (nIndex == -1)
191  return uint256 ();
192  for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin ());
193  it != vMerkleBranch.end (); ++it)
194  {
195  if (nIndex & 1)
196  hash = Hash (BEGIN (*it), END (*it), BEGIN (hash), END (hash));
197  else
198  hash = Hash (BEGIN (hash), END (hash), BEGIN (*it), END (*it));
199  nIndex >>= 1;
200  }
201  return hash;
202 }
203 
204 void
206 {
207  /* Set auxpow flag right now, since we take the block hash below. */
208  header.SetAuxpowFlag(true);
209 
210  /* Build a minimal coinbase script input for merge-mining. */
211  const uint256 blockHash = header.GetHash ();
212  std::vector<unsigned char> inputData(blockHash.begin (), blockHash.end ());
213  std::reverse (inputData.begin (), inputData.end ());
214  inputData.push_back (1);
215  inputData.insert (inputData.end (), 7, 0);
216 
217  /* Fake a parent-block coinbase with just the required input
218  script and no outputs. */
219  CMutableTransaction coinbase;
220  coinbase.vin.resize(1);
221  coinbase.vin[0].prevout.SetNull();
222  coinbase.vin[0].scriptSig = (CScript () << inputData);
223  assert (coinbase.vout.empty());
224  CTransactionRef coinbaseRef = MakeTransactionRef(coinbase);
225 
226  /* Build a fake parent block with the coinbase. */
227  CBlock parent;
228  parent.nVersion = 1;
229  parent.vtx.resize(1);
230  parent.vtx[0] = coinbaseRef;
231  parent.hashMerkleRoot = BlockMerkleRoot(parent);
232 
233  /* Construct the auxpow object. */
234  header.SetAuxpow(new CAuxPow(coinbaseRef));
235  assert (header.auxpow->vChainMerkleBranch.empty());
236  header.auxpow->nChainIndex = 0;
237  assert (header.auxpow->vMerkleBranch.empty());
238  header.auxpow->nIndex = 0;
239  header.auxpow->parentBlock = parent;
240 }
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:15
const CChainParams & Params()
Return the currently selected parameters.
static uint256 CheckMerkleBranch(uint256 hash, const std::vector< uint256 > &vMerkleBranch, int nIndex)
Check a merkle branch.
Definition: auxpow.cpp:186
static void initAuxPow(CBlockHeader &header)
Initialise the auxpow of the given block header.
Definition: auxpow.cpp:205
bool check(const uint256 &hashAuxBlock, int nChainId, const Consensus::Params &params) const
Check the auxpow, given the merge-mined block's hash and our chain ID.
Definition: auxpow.cpp:81
CAuxPow()
Definition: auxpow.h:146
CPureBlockHeader parentBlock
Parent block header (on which the real PoW is done).
Definition: auxpow.h:136
int nChainIndex
Merkle tree index of the aux block header in the coinbase.
Definition: auxpow.h:133
static int getExpectedIndex(uint32_t nNonce, int nChainId, unsigned h)
Calculate the expected index in the merkle tree.
Definition: auxpow.cpp:160
std::vector< uint256 > vChainMerkleBranch
The merkle branch connecting the aux block to our coinbase.
Definition: auxpow.h:130
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:25
void SetAuxpow(CAuxPow *apow)
Set the block's auxpow (or unset it).
Definition: block.cpp:13
boost::shared_ptr< CAuxPow > auxpow
Definition: block.h:28
Definition: block.h:67
std::vector< CTransactionRef > vtx
Definition: block.h:70
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:158
uint256 GetBlockHash() const
Definition: chain.h:268
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:170
int Height() const
Return the maximal height in the chain.
Definition: chain.h:474
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:461
const Consensus::Params & GetConsensus(uint32_t nTargetHeight) const
Definition: chainparams.h:59
bool AcceptToMemoryPool(const CAmount &nAbsurdFee, CValidationState &state)
Pass this transaction to the mempool.
Definition: auxpow.cpp:73
const uint256 & GetHash() const
Definition: auxpow.h:113
int GetDepthInMainChain() const
Definition: auxpow.h:104
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned.
Definition: auxpow.h:34
bool IsCoinBase() const
Definition: auxpow.h:114
int GetBlocksToMaturity() const
Definition: auxpow.cpp:64
void InitMerkleBranch(const CBlock &block, int posInBlock)
Actually compute the Merkle branch.
Definition: auxpow.cpp:38
uint256 hashBlock
Definition: auxpow.h:38
int nIndex
Definition: auxpow.h:48
std::vector< uint256 > vMerkleBranch
Definition: auxpow.h:41
void SetMerkleBranch(const CBlockIndex *pindex, int posInBlock)
Definition: auxpow.cpp:29
CTransactionRef tx
Definition: auxpow.h:37
bool hashUnset() const
Definition: auxpow.h:109
int32_t nVersion
Definition: pureheader.h:29
int32_t GetChainId() const
Extract the chain ID.
Definition: pureheader.h:110
void SetAuxpowFlag(bool auxpow)
Set the auxpow flag.
Definition: pureheader.h:138
uint256 GetHash() const
Definition: pureheader.cpp:20
uint256 hashMerkleRoot
Definition: pureheader.h:31
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:377
Capture information about block/transaction validation.
Definition: validation.h:22
unsigned char * end()
Definition: uint256.h:61
unsigned char * begin()
Definition: uint256.h:56
iterator begin()
Definition: prevector.h:289
iterator end()
Definition: prevector.h:291
256-bit opaque blob.
Definition: uint256.h:123
uint32_t le32toh(uint32_t little_endian_32bits)
Definition: endian.h:160
void * memcpy(void *a, const void *b, size_t c)
uint256 Hash(const T1 pbegin, const T1 pend)
Compute the 256-bit hash of an object.
Definition: hash.h:70
std::vector< uint256 > BlockMerkleBranch(const CBlock &block, uint32_t position)
Definition: merkle.cpp:179
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:158
A mutable version of CTransaction.
Definition: transaction.h:413
std::vector< CTxOut > vout
Definition: transaction.h:416
std::vector< CTxIn > vin
Definition: transaction.h:415
Parameters that influence chain consensus.
Definition: params.h:39
bool fStrictChainId
Definition: params.h:80
uint32_t nCoinbaseMaturity
Definition: params.h:61
#define AssertLockHeld(cs)
Definition: sync.h:86
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:459
uint256 uint256S(const char *str)
Definition: uint256.h:144
bool error(const char *fmt, const Args &... args)
Definition: util.h:87
#define UBEGIN(a)
#define BEGIN(a)
Utilities for converting data from/to strings.
#define END(a)
#define UEND(a)
CCriticalSection cs_main
Global state.
Definition: validation.cpp:61
CTxMemPool mempool(::minRelayTxFee)
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
BlockMap mapBlockIndex
Definition: validation.cpp:63
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:64