]>
Commit | Line | Data |
---|---|---|
d247a5d1 | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
f914f1a7 | 2 | // Copyright (c) 2009-2014 The Bitcoin Core developers |
78253fcb | 3 | // Distributed under the MIT software license, see the accompanying |
bc909a7a | 4 | // file COPYING or https://www.opensource.org/licenses/mit-license.php . |
d247a5d1 | 5 | |
d247a5d1 | 6 | #include "miner.h" |
8e8b6d70 | 7 | #ifdef ENABLE_MINING |
c7aaab7a | 8 | #include "pow/tromp/equi_miner.h" |
2cc0a252 | 9 | #endif |
51ed9ec9 | 10 | |
eda37330 | 11 | #include "amount.h" |
bebe7282 | 12 | #include "chainparams.h" |
ca4a5f26 | 13 | #include "cc/StakeGuard.h" |
20c3ac51 | 14 | #include "importcoin.h" |
691161d4 | 15 | #include "consensus/consensus.h" |
be126699 | 16 | #include "consensus/upgrades.h" |
da29ecbc | 17 | #include "consensus/validation.h" |
8e8b6d70 JG |
18 | #ifdef ENABLE_MINING |
19 | #include "crypto/equihash.h" | |
42181656 | 20 | #include "crypto/verus_hash.h" |
8e8b6d70 | 21 | #endif |
85aab2a0 | 22 | #include "hash.h" |
93bd00a0 | 23 | #include "key_io.h" |
d247a5d1 | 24 | #include "main.h" |
a6df7ab5 | 25 | #include "metrics.h" |
51ed9ec9 | 26 | #include "net.h" |
df852d2b | 27 | #include "pow.h" |
bebe7282 | 28 | #include "primitives/transaction.h" |
8e165d57 | 29 | #include "random.h" |
22c4272b | 30 | #include "timedata.h" |
8e8b6d70 | 31 | #include "ui_interface.h" |
ad49c256 WL |
32 | #include "util.h" |
33 | #include "utilmoneystr.h" | |
b2993bc5 | 34 | #include "validationinterface.h" |
09eb201b | 35 | |
df756d24 MT |
36 | #include "zcash/Address.hpp" |
37 | #include "transaction_builder.h" | |
38 | ||
fdda3c50 JG |
39 | #include "sodium.h" |
40 | ||
ad49c256 | 41 | #include <boost/thread.hpp> |
a3c26c2e | 42 | #include <boost/tuple/tuple.hpp> |
8e8b6d70 JG |
43 | #ifdef ENABLE_MINING |
44 | #include <functional> | |
45 | #endif | |
5a360a5c | 46 | #include <mutex> |
ad49c256 | 47 | |
2299bd95 MT |
48 | #include "pbaas/pbaas.h" |
49 | #include "pbaas/notarization.h" | |
b7c685b8 | 50 | #include "pbaas/identity.h" |
e7e14f44 | 51 | #include "rpc/pbaasrpc.h" |
13ed2980 | 52 | #include "transaction_builder.h" |
2299bd95 | 53 | |
09eb201b | 54 | using namespace std; |
7b4737c8 | 55 | |
d247a5d1 JG |
56 | ////////////////////////////////////////////////////////////////////////////// |
57 | // | |
58 | // BitcoinMiner | |
59 | // | |
60 | ||
c6cb21d1 GA |
61 | // |
62 | // Unconfirmed transactions in the memory pool often depend on other | |
63 | // transactions in the memory pool. When we select transactions from the | |
64 | // pool, we select by highest priority or fee rate, so we might consider | |
65 | // transactions that depend on transactions that aren't yet in the block. | |
66 | // The COrphan class keeps track of these 'temporary orphans' while | |
67 | // CreateBlock is figuring out which transactions to include. | |
68 | // | |
d247a5d1 JG |
69 | class COrphan |
70 | { | |
71 | public: | |
4d707d51 | 72 | const CTransaction* ptx; |
d247a5d1 | 73 | set<uint256> setDependsOn; |
c6cb21d1 | 74 | CFeeRate feeRate; |
02bec4b2 | 75 | double dPriority; |
e9e70b95 | 76 | |
c6cb21d1 | 77 | COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0) |
d247a5d1 | 78 | { |
d247a5d1 | 79 | } |
d247a5d1 JG |
80 | }; |
81 | ||
51ed9ec9 BD |
82 | uint64_t nLastBlockTx = 0; |
83 | uint64_t nLastBlockSize = 0; | |
d247a5d1 | 84 | |
c6cb21d1 GA |
85 | // We want to sort transactions by priority and fee rate, so: |
86 | typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority; | |
d247a5d1 JG |
87 | class TxPriorityCompare |
88 | { | |
89 | bool byFee; | |
e9e70b95 | 90 | |
d247a5d1 JG |
91 | public: |
92 | TxPriorityCompare(bool _byFee) : byFee(_byFee) { } | |
e9e70b95 | 93 | |
d247a5d1 JG |
94 | bool operator()(const TxPriority& a, const TxPriority& b) |
95 | { | |
96 | if (byFee) | |
97 | { | |
98 | if (a.get<1>() == b.get<1>()) | |
99 | return a.get<0>() < b.get<0>(); | |
100 | return a.get<1>() < b.get<1>(); | |
101 | } | |
102 | else | |
103 | { | |
104 | if (a.get<0>() == b.get<0>()) | |
105 | return a.get<1>() < b.get<1>(); | |
106 | return a.get<0>() < b.get<0>(); | |
107 | } | |
108 | } | |
109 | }; | |
110 | ||
bebe7282 | 111 | void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) |
22c4272b | 112 | { |
113 | pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); | |
5ead4b17 JG |
114 | |
115 | // Updating time can change work required on testnet: | |
4c902704 | 116 | if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) { |
5ead4b17 | 117 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); |
b86dc980 | 118 | } |
22c4272b | 119 | } |
120 | ||
5416af1d | 121 | #include "komodo_defs.h" |
122 | ||
69767347 | 123 | extern CCriticalSection cs_metrics; |
6e78d3df | 124 | extern int32_t KOMODO_MININGTHREADS,KOMODO_LONGESTCHAIN,ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE; |
48d800c2 | 125 | extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED; |
5f63373e | 126 | extern bool VERUS_MINTBLOCKS; |
42181656 | 127 | extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[]; |
128 | extern const char *ASSETCHAINS_ALGORITHMS[]; | |
5296a850 | 129 | extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[]; |
7c130297 | 130 | extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; |
b2a98c42 MT |
131 | extern uint160 ASSETCHAINS_CHAINID; |
132 | extern uint160 VERUS_CHAINID; | |
f2d873d0 | 133 | extern std::string VERUS_CHAINNAME; |
68b309c0 | 134 | extern int32_t PBAAS_STARTBLOCK, PBAAS_ENDBLOCK; |
7af5cf39 | 135 | extern string PBAAS_HOST, PBAAS_USERPASS, ASSETCHAINS_RPCHOST, ASSETCHAINS_RPCCREDENTIALS;; |
f8f61a6d | 136 | extern int32_t PBAAS_PORT; |
7af5cf39 | 137 | extern uint16_t ASSETCHAINS_RPCPORT; |
d9f176ac | 138 | extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY; |
292809f7 | 139 | void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len); |
d9f176ac | 140 | |
94a465a6 | 141 | extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; |
f24b36ca | 142 | uint32_t Mining_start,Mining_height; |
28a62b60 | 143 | int32_t My_notaryid = -1; |
8683bd8d | 144 | int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); |
b4810651 | 145 | int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize); |
d63fdb34 | 146 | int32_t komodo_baseid(char *origbase); |
3bc88f14 | 147 | int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag); |
29bd53a1 | 148 | int64_t komodo_block_unlocktime(uint32_t nHeight); |
18443f69 | 149 | uint64_t komodo_commission(const CBlock *block); |
d231a6a7 | 150 | int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig); |
06f41160 | 151 | int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig, CPubKey &pk); |
496f1fd2 | 152 | int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33); |
7652ed92 | 153 | |
1685bba0 MT |
154 | void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int &nExtraNonce, bool buildMerkle, uint32_t *pSaveBits) |
155 | { | |
156 | // Update nExtraNonce | |
157 | static uint256 hashPrevBlock; | |
158 | if (hashPrevBlock != pblock->hashPrevBlock) | |
159 | { | |
160 | nExtraNonce = 0; | |
161 | hashPrevBlock = pblock->hashPrevBlock; | |
162 | } | |
163 | ++nExtraNonce; | |
164 | ||
165 | if (pSaveBits) | |
166 | { | |
167 | *pSaveBits = pblock->nBits; | |
168 | } | |
169 | ||
170 | int32_t nHeight = pindexPrev->GetHeight() + 1; | |
171 | ||
598ba98b | 172 | if (CConstVerusSolutionVector::activationHeight.ActiveVersion(nHeight) >= CConstVerusSolutionVector::activationHeight.SOLUTION_VERUSV4) |
1685bba0 MT |
173 | { |
174 | // coinbase should already be finalized in the new version | |
175 | if (buildMerkle) | |
176 | { | |
177 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); | |
178 | } | |
179 | ||
180 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); | |
181 | ||
182 | uint256 mmvRoot; | |
183 | { | |
184 | LOCK(cs_main); | |
185 | // set the PBaaS header | |
186 | ChainMerkleMountainView mmv = chainActive.GetMMV(); | |
187 | mmvRoot = mmv.GetRoot(); | |
188 | } | |
189 | ||
190 | pblock->AddUpdatePBaaSHeader(mmvRoot); | |
191 | ||
192 | // POS blocks have already had their solution space filled, and there is no actual extra nonce, extradata is used | |
193 | // for POS proof, so don't modify it | |
194 | if (!pblock->IsVerusPOSBlock()) | |
195 | { | |
196 | uint8_t dummy; | |
197 | // clear extra data to allow adding more PBaaS headers | |
198 | pblock->SetExtraData(&dummy, 0); | |
199 | ||
200 | // combine blocks and set compact difficulty if necessary | |
201 | uint32_t savebits; | |
202 | if ((savebits = ConnectedChains.CombineBlocks(*pblock)) && pSaveBits) | |
203 | { | |
204 | arith_uint256 ours, merged; | |
205 | ours.SetCompact(pblock->nBits); | |
206 | merged.SetCompact(savebits); | |
207 | if (merged > ours) | |
208 | { | |
209 | *pSaveBits = savebits; | |
210 | } | |
211 | } | |
212 | ||
213 | // extra nonce is kept in the header, not in the coinbase any longer | |
214 | // this allows instant spend transactions to use coinbase funds for | |
215 | // inputs by ensuring that once final, the coinbase transaction hash | |
216 | // will not continue to change | |
217 | CDataStream s(SER_NETWORK, PROTOCOL_VERSION); | |
218 | s << nExtraNonce; | |
219 | std::vector<unsigned char> vENonce(s.begin(), s.end()); | |
220 | ||
221 | assert(pblock->ExtraDataLen() >= vENonce.size()); | |
222 | pblock->SetExtraData(vENonce.data(), vENonce.size()); | |
223 | } | |
224 | } | |
225 | else | |
226 | { | |
227 | // finalize input of coinbase | |
228 | CMutableTransaction txcb(pblock->vtx[0]); | |
229 | txcb.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; | |
230 | assert(txcb.vin[0].scriptSig.size() <= 100); | |
231 | pblock->vtx[0] = txcb; | |
232 | if (buildMerkle) | |
233 | { | |
234 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); | |
235 | } | |
236 | ||
237 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); | |
238 | } | |
239 | } | |
240 | ||
88d014d0 | 241 | CBlockTemplate* CreateNewBlock(const CChainParams& chainparams, const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake) |
d247a5d1 | 242 | { |
8626f666 | 243 | CScript scriptPubKeyIn(_scriptPubKeyIn); |
06f41160 | 244 | |
41f170fd MT |
245 | // instead of one scriptPubKeyIn, we take a vector of them along with relative weight. each is assigned a percentage of the block subsidy and |
246 | // mining reward based on its weight relative to the total | |
bb6c3482 | 247 | std::vector<pair<int, CScript>> minerOutputs = scriptPubKeyIn.size() ? std::vector<pair<int, CScript>>({make_pair((int)1, scriptPubKeyIn)}) : std::vector<pair<int, CScript>>(); |
41f170fd | 248 | |
88bc6df5 | 249 | // TODO: when we accept a parameter of the minerOutputs vector, remove this comment but not the check |
c3250dcd | 250 | CTxDestination firstDestination; |
bb6c3482 | 251 | if (!(scriptPubKeyIn.size() && ConnectedChains.SetLatestMiningOutputs(minerOutputs, firstDestination) || isStake)) |
06f41160 | 252 | { |
34d1aa13 | 253 | fprintf(stderr,"%s: Must have valid miner outputs, including script with valid PK or PKH destination.\n", __func__); |
88bc6df5 | 254 | return NULL; |
06f41160 | 255 | } |
256 | ||
bb6c3482 | 257 | if (minerOutputs.size()) |
06f41160 | 258 | { |
bb6c3482 | 259 | int64_t shareCheck = 0; |
260 | for (auto output : minerOutputs) | |
c3250dcd | 261 | { |
bb6c3482 | 262 | shareCheck += output.first; |
263 | if (shareCheck < 0 || shareCheck > INT_MAX) | |
264 | { | |
265 | fprintf(stderr,"Invalid miner outputs share specifications\n"); | |
266 | return NULL; | |
267 | } | |
c3250dcd | 268 | } |
06f41160 | 269 | } |
270 | ||
c3250dcd MT |
271 | CPubKey pk = boost::apply_visitor<GetPubKeyForPubKey>(GetPubKeyForPubKey(), firstDestination); |
272 | ||
88d014d0 | 273 | uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; |
2a6a442a | 274 | //fprintf(stderr,"create new block\n"); |
df756d24 | 275 | // Create new block |
16593898 | 276 | if ( gpucount < 0 ) |
277 | gpucount = KOMODO_MAXGPUCOUNT; | |
08c58194 | 278 | std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); |
d247a5d1 | 279 | if(!pblocktemplate.get()) |
1b5b89ba | 280 | { |
281 | fprintf(stderr,"pblocktemplate.get() failure\n"); | |
d247a5d1 | 282 | return NULL; |
1b5b89ba | 283 | } |
d247a5d1 | 284 | CBlock *pblock = &pblocktemplate->block; // pointer for convenience |
12217420 | 285 | |
286 | // set version according to the current tip height, add solution if it is | |
287 | // VerusHash | |
288 | if (ASSETCHAINS_ALGO == ASSETCHAINS_VERUSHASH) | |
289 | { | |
290 | pblock->nSolution.resize(Eh200_9.SolutionWidth); | |
291 | } | |
292 | else | |
293 | { | |
294 | pblock->nSolution.clear(); | |
295 | } | |
296 | pblock->SetVersionByHeight(chainActive.LastTip()->GetHeight() + 1); | |
297 | ||
298 | // -regtest only: allow overriding block.nVersion with | |
dbca89b7 | 299 | // -blockversion=N to test forking scenarios |
793a72e3 | 300 | if (chainparams.MineBlocksOnDemand()) |
dbca89b7 | 301 | pblock->nVersion = GetArg("-blockversion", pblock->nVersion); |
e9e70b95 | 302 | |
41f170fd | 303 | // Add dummy coinbase tx placeholder as first transaction |
4949004d | 304 | pblock->vtx.push_back(CTransaction()); |
41f170fd | 305 | |
d247a5d1 JG |
306 | pblocktemplate->vTxFees.push_back(-1); // updated at end |
307 | pblocktemplate->vTxSigOps.push_back(-1); // updated at end | |
e9e70b95 | 308 | |
d247a5d1 | 309 | // Largest block you're willing to create: |
ad898b40 | 310 | unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); |
d247a5d1 JG |
311 | // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: |
312 | nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); | |
e9e70b95 | 313 | |
d247a5d1 JG |
314 | // How much of the block should be dedicated to high-priority transactions, |
315 | // included regardless of the fees they pay | |
316 | unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); | |
317 | nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); | |
e9e70b95 | 318 | |
d247a5d1 JG |
319 | // Minimum block size you want to create; block will be filled with free transactions |
320 | // until there are no more or the block reaches this size: | |
037b4f14 | 321 | unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); |
d247a5d1 | 322 | nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); |
e9e70b95 | 323 | |
d247a5d1 | 324 | // Collect memory pool transactions into the block |
a372168e | 325 | CAmount nFees = 0; |
df756d24 | 326 | |
41f170fd MT |
327 | // if this is a reserve currency, update the currency state from the coinbase of the last block |
328 | bool isVerusActive = IsVerusActive(); | |
329 | CPBaaSChainDefinition &thisChain = ConnectedChains.ThisChain(); | |
a1a4dc8b | 330 | CCoinbaseCurrencyState currencyState = CCoinbaseCurrencyState(CCurrencyState(thisChain.conversion, thisChain.premine, 0, 0, 0), 0, 0, CReserveOutput(), 0, 0, 0); |
41f170fd MT |
331 | CAmount exchangeRate; |
332 | ||
df756d24 MT |
333 | // we will attempt to spend any cheats we see |
334 | CTransaction cheatTx; | |
335 | boost::optional<CTransaction> cheatSpend; | |
336 | uint256 cbHash; | |
337 | ||
687e93d5 MT |
338 | extern CWallet *pwalletMain; |
339 | ||
562852ab | 340 | CBlockIndex* pindexPrev = 0; |
d247a5d1 JG |
341 | { |
342 | LOCK2(cs_main, mempool.cs); | |
562852ab | 343 | pindexPrev = chainActive.LastTip(); |
4b729ec5 | 344 | const int nHeight = pindexPrev->GetHeight() + 1; |
df756d24 MT |
345 | const Consensus::Params &consensusParams = chainparams.GetConsensus(); |
346 | uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, consensusParams); | |
88d014d0 | 347 | bool sapling = consensusParams.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_SAPLING); |
a0dd01bc | 348 | |
a1d3c6fb | 349 | const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); |
a0dd01bc | 350 | uint32_t proposedTime = GetAdjustedTime(); |
351 | if (proposedTime == nMedianTimePast) | |
352 | { | |
353 | // too fast or stuck, this addresses the too fast issue, while moving | |
354 | // forward as quickly as possible | |
355 | for (int i; i < 100; i++) | |
356 | { | |
357 | proposedTime = GetAdjustedTime(); | |
358 | if (proposedTime == nMedianTimePast) | |
359 | MilliSleep(10); | |
360 | } | |
361 | } | |
362 | pblock->nTime = GetAdjustedTime(); | |
363 | ||
7c70438d | 364 | CCoinsViewCache view(pcoinsTip); |
f9155fec | 365 | uint32_t expired; uint64_t commission; |
6ff77181 | 366 | |
4fc309f0 | 367 | SaplingMerkleTree sapling_tree; |
31a04d28 SB |
368 | assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree)); |
369 | ||
d247a5d1 JG |
370 | // Priority order to process transactions |
371 | list<COrphan> vOrphan; // list memory doesn't move | |
372 | map<uint256, vector<COrphan*> > mapDependers; | |
373 | bool fPrintPriority = GetBoolArg("-printpriority", false); | |
e9e70b95 | 374 | |
d247a5d1 JG |
375 | // This vector will be sorted into a priority queue: |
376 | vector<TxPriority> vecPriority; | |
df756d24 MT |
377 | vecPriority.reserve(mempool.mapTx.size() + 1); |
378 | ||
379 | // check if we should add cheat transaction | |
380 | CBlockIndex *ppast; | |
ec8a120b | 381 | CTransaction cb; |
83a426bc | 382 | int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY; |
df756d24 MT |
383 | if (cheatCatcher && |
384 | sapling && chainActive.Height() > 100 && | |
83a426bc | 385 | (ppast = chainActive[cheatHeight]) && |
df756d24 | 386 | ppast->IsVerusPOSBlock() && |
83a426bc | 387 | cheatList.IsHeightOrGreaterInList(cheatHeight)) |
df756d24 MT |
388 | { |
389 | // get the block and see if there is a cheat candidate for the stake tx | |
390 | CBlock b; | |
88d014d0 | 391 | if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, chainparams.GetConsensus(), 1)) |
df756d24 MT |
392 | { |
393 | CTransaction &stakeTx = b.vtx[b.vtx.size() - 1]; | |
394 | ||
395 | if (cheatList.IsCheatInList(stakeTx, &cheatTx)) | |
396 | { | |
397 | // make and sign the cheat transaction to spend the coinbase to our address | |
398 | CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight); | |
399 | ||
73a4cd20 | 400 | uint32_t voutNum; |
401 | // get the first vout with value | |
402 | for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++) | |
403 | { | |
404 | if (b.vtx[0].vout[voutNum].nValue > 0) | |
405 | break; | |
406 | } | |
407 | ||
df756d24 | 408 | // send to the same pub key as the destination of this block reward |
73a4cd20 | 409 | if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx)) |
df756d24 | 410 | { |
df756d24 | 411 | LOCK(pwalletMain->cs_wallet); |
6c621e0e | 412 | TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight); |
ec8a120b | 413 | cb = b.vtx[0]; |
df756d24 MT |
414 | cbHash = cb.GetHash(); |
415 | ||
416 | bool hasInput = false; | |
417 | for (uint32_t i = 0; i < cb.vout.size(); i++) | |
418 | { | |
419 | // add the spends with the cheat | |
73a4cd20 | 420 | if (cb.vout[i].nValue > 0) |
df756d24 MT |
421 | { |
422 | tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue); | |
423 | hasInput = true; | |
424 | } | |
425 | } | |
426 | ||
427 | if (hasInput) | |
428 | { | |
fa6c4d7c | 429 | // this is a send from a t-address to a sapling address, which we don't have an ovk for. |
df756d24 MT |
430 | // Instead, generate a common one from the HD seed. This ensures the data is |
431 | // recoverable, at least for us, while keeping it logically separate from the ZIP 32 | |
432 | // Sapling key hierarchy, which the user might not be using. | |
433 | uint256 ovk; | |
434 | HDSeed seed; | |
435 | if (pwalletMain->GetHDSeed(seed)) { | |
436 | ovk = ovkForShieldingFromTaddr(seed); | |
437 | ||
ac2b2404 | 438 | // send everything to Sapling address |
439 | tb.SendChangeTo(cheatCatcher.value(), ovk); | |
440 | ||
2d02c19e | 441 | tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey); |
df756d24 | 442 | |
88d014d0 | 443 | TransactionBuilderResult buildResult(tb.Build()); |
444 | if (!buildResult.IsError() && buildResult.IsTx()) | |
445 | { | |
446 | cheatSpend = buildResult.GetTxOrThrow(); | |
447 | } | |
448 | else | |
449 | { | |
450 | LogPrintf("Error building cheat catcher transaction: %s\n", buildResult.GetError().c_str()); | |
451 | } | |
df756d24 MT |
452 | } |
453 | } | |
454 | } | |
455 | } | |
456 | } | |
457 | } | |
458 | ||
271326fa | 459 | if (cheatSpend) |
460 | { | |
90cc70cc | 461 | cheatTx = cheatSpend.value(); |
271326fa | 462 | std::list<CTransaction> removed; |
45bb4681 | 463 | mempool.removeConflicts(cheatTx, removed); |
c8700efe | 464 | printf("Found cheating stake! Adding cheat spend for %.8f at block #%d, coinbase tx\n%s\n", |
ec8a120b | 465 | (double)cb.GetValueOut() / (double)COIN, nHeight, cheatSpend.value().vin[0].prevout.hash.GetHex().c_str()); |
45bb4681 | 466 | |
467 | // add to mem pool and relay | |
468 | if (myAddtomempool(cheatTx)) | |
469 | { | |
470 | RelayTransaction(cheatTx); | |
471 | } | |
271326fa | 472 | } |
473 | ||
41f170fd MT |
474 | // |
475 | // Now start solving the block | |
476 | // | |
477 | ||
478 | uint64_t nBlockSize = 1000; // initial size | |
479 | uint64_t nBlockTx = 1; // number of transactions - always have a coinbase | |
480 | uint32_t autoTxSize = 0; // extra transaction overhead that we will add while creating the block | |
481 | int nBlockSigOps = 100; | |
482 | ||
483 | // VerusPoP staking transaction data | |
484 | CMutableTransaction txStaked; // if this is a stake operation, the staking transaction that goes at the end | |
485 | uint32_t nStakeTxSize = 0; // serialized size of the stake transaction | |
486 | ||
487 | // if this is not for mining, first determine if we have a right to bother | |
488 | if (isStake) | |
489 | { | |
490 | uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr; | |
491 | txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight); | |
492 | ||
493 | //if ( blocktime > pindexPrev->GetMedianTimePast()+60 ) | |
494 | // blocktime = pindexPrev->GetMedianTimePast() + 60; | |
495 | if (ASSETCHAINS_LWMAPOS != 0) | |
496 | { | |
497 | uint32_t nBitsPOS; | |
498 | arith_uint256 posHash; | |
499 | ||
500 | siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk); | |
501 | blocktime = GetAdjustedTime(); | |
502 | ||
503 | // change the default scriptPubKeyIn to the same output script exactly as the staking transaction | |
504 | // TODO: improve this and just implement stake guard here rather than keeping this legacy | |
505 | if (siglen > 0) | |
506 | scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey); | |
507 | } | |
508 | else | |
509 | { | |
510 | siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig); | |
511 | } | |
512 | ||
513 | if (siglen <= 0) | |
514 | { | |
515 | return NULL; | |
516 | } | |
517 | ||
518 | pblock->nTime = blocktime; | |
519 | nStakeTxSize = GetSerializeSize(txStaked, SER_NETWORK, PROTOCOL_VERSION); | |
520 | nBlockSize += nStakeTxSize; | |
bb6c3482 | 521 | |
522 | // get the public key and make a miner output if needed for this | |
523 | if (!minerOutputs.size()) | |
524 | { | |
525 | minerOutputs.push_back(make_pair((int)1, txStaked.vout[0].scriptPubKey)); | |
526 | txnouttype typeRet; | |
527 | std::vector<std::vector<unsigned char>> vSolutions; | |
528 | if (Solver(txStaked.vout[0].scriptPubKey, typeRet, vSolutions)) | |
529 | { | |
530 | if (typeRet == TX_PUBKEY) | |
531 | { | |
532 | pk = CPubKey(vSolutions[0]); | |
533 | } | |
b7c685b8 | 534 | else if (typeRet == TX_CRYPTOCONDITION) |
535 | { | |
536 | if (vSolutions[0].size() == 33) | |
537 | { | |
538 | pk = CPubKey(vSolutions[0]); | |
539 | } | |
540 | else if (vSolutions[0].size() == 34 && vSolutions[0][0] == COptCCParams::ADDRTYPE_PK) | |
541 | { | |
542 | pk = CPubKey(std::vector<unsigned char>(vSolutions[0].begin() + 1, vSolutions[0].end())); | |
543 | } | |
544 | else if (vSolutions[0].size() == 20) | |
545 | { | |
546 | pwalletMain->GetPubKey(CKeyID(uint160(vSolutions[0])), pk); | |
547 | } | |
0d7fed99 | 548 | else if (vSolutions[0].size() == 21 && vSolutions[0][0] == COptCCParams::ADDRTYPE_ID) |
b7c685b8 | 549 | { |
550 | // destination is an identity, see if we can get its public key | |
5bc89dab | 551 | std::pair<CIdentityMapKey, CIdentityMapValue> identity; |
b7c685b8 | 552 | |
5bc89dab | 553 | if (pwalletMain->GetIdentity(CIdentityID(uint160(std::vector<unsigned char>(vSolutions[0].begin() + 1, vSolutions[0].end()))), identity) && |
554 | identity.second.IsValidUnrevoked() && | |
555 | identity.second.primaryAddresses.size()) | |
b7c685b8 | 556 | { |
5bc89dab | 557 | CPubKey pkTmp = boost::apply_visitor<GetPubKeyForPubKey>(GetPubKeyForPubKey(), identity.second.primaryAddresses[0]); |
b7c685b8 | 558 | if (pkTmp.IsValid()) |
559 | { | |
560 | pk = pkTmp; | |
561 | } | |
562 | else | |
563 | { | |
5bc89dab | 564 | pwalletMain->GetPubKey(CKeyID(GetDestinationID(identity.second.primaryAddresses[0])), pk); |
b7c685b8 | 565 | } |
566 | } | |
567 | } | |
568 | } | |
bb6c3482 | 569 | else |
570 | { | |
571 | pwalletMain->GetPubKey(CKeyID(uint160(vSolutions[0])), pk); | |
572 | } | |
573 | } | |
574 | ConnectedChains.SetLatestMiningOutputs(minerOutputs, firstDestination); | |
575 | } | |
41f170fd MT |
576 | } |
577 | ||
bb6c3482 | 578 | ConnectedChains.AggregateChainTransfers(firstDestination, nHeight); |
579 | ||
41f170fd MT |
580 | // Now the coinbase - |
581 | // A PBaaS coinbase must have some additional outputs to enable certain chain state and functions to be properly | |
582 | // validated. All but currency state and the first chain definition are either optional or not valid on non-fractional reserve PBaaS blockchains | |
583 | // All of these are instant spend outputs that have no maturity wait time and may be spent in the same block. | |
584 | // | |
585 | // 1. (required) currency state - current state of currency supply and optionally reserve, premine, etc. This is primarily a data output to provide | |
586 | // cross check for coin minting and burning operations, making it efficient to determine up-to-date supply, reserves, and conversions. To provide | |
587 | // an extra level of supply cross-checking and fast data retrieval, this is part of all PBaaS chains' protocol, not just reserves. | |
588 | // This output also includes reserve and native amounts for total conversions, less fees, of any conversions between Verus reserve and the | |
589 | // native currency. | |
590 | // | |
591 | // 2. (block 1 required) chain definition - in order to confirm the amount of coins converted and issued within the possible range, before chain start, | |
592 | // new PBaaS chains have a zero-amount, unspendable chain definition output. | |
593 | // | |
594 | // 3. (block 1 optional) initial import utxo - for any chain with conversion or pre-conversion, the first coinbase must include an initial import utxo. | |
595 | // Pre-conversions are handled on the launch chain before the PBaaS chain starts, so they are an additional output, which begins | |
596 | // as a fixed amount and is spent with as many outputs as necessary to the recipients of the pre-conversion transactions when those pre-conversions | |
597 | // are imported. All pre-converted outputs get their source currency from a thread that starts with this output in block 1. | |
598 | // | |
599 | // 4. (block 1 optional) initial export utxo - reserve chains, or any chain that will use exports to another chain must have an initial export utxo, any chain | |
600 | // may have one, but currently, they can only be spent with valid exports, which only occur on reserve chains | |
601 | // | |
602 | // 5. (optional) notarization output - in order to ensure that notarization can occur independent of the availability of fungible | |
603 | // coins on the network, and also that the notarization can provide a spendable finalization output and possible reward | |
604 | // | |
605 | // In addition, each PBaaS block can be mined with optional, fee-generating transactions. Inporting transactions from the reserve chain or sending | |
606 | // exported transactions to the reserve chain are optional fee-generating steps that would be easy to do when running multiple daemons. | |
607 | // The types of transactions miners/stakers may facilitate or create for fees are as follows: | |
608 | // | |
609 | // 1. Earned notarization of Verus chain - spends the notarization instant out. must be present and spend the notarization output if there is a notarization output | |
610 | // | |
611 | // 2. Imported transactions from the export thread for this PBaaS chain on the Verus blockchain - imported transactions must spend the import utxo | |
612 | // thread, represent the export from the alternate chain which spends the export output from the prior import transaction, carry a notary proof, and | |
613 | // include outputs that map to each of its inputs on the source chain. Outputs can include unconverted reserve outputs only on fractional | |
614 | // reserve chains, pre-converted outputs for any chain with launch conversion, and post launch outputs to be converted on fractional reserve | |
615 | // chains. Each are handled in the following way: | |
616 | // a. Unconverted outputs are left as outputs to the intended destination of Verus reserve token and do not pass through the coinbase | |
617 | // b. Pre-converted outputs require that the import transaction spend the last pre-conversion output starting at block 1 as the source for | |
618 | // pre-converted currency. | |
619 | // | |
620 | // 3. Zero or more aggregated exports that combine individual cross-chain transactions and reserve transfer outputs for export to the Verus chain. | |
621 | // | |
622 | // 4. Conversion distribution transactions for all native and reserve currency conversions, including reserve transfer outputs without conversion as | |
623 | // a second step for reserve transfers that have conversion included. Any remaining pre-converted reserve must always remain in a change output | |
624 | // until it is exhausted | |
88bc6df5 | 625 | CTxOut premineOut, chainDefinitionOut, importThreadOut, exportThreadOut, currencyStateOut, notarizationOut; |
41f170fd MT |
626 | CMutableTransaction newNotarizationTx, newConversionOutputTx; |
627 | ||
628 | // size of conversion tx | |
0574c740 | 629 | std::vector<CInputDescriptor> conversionInputs; |
41f170fd | 630 | |
4fa3b13d | 631 | // if we are a PBaaS chain, first make sure we don't start prematurely, and if |
68b309c0 | 632 | // we should make an earned notarization, make it and set index to non-zero value |
41f170fd MT |
633 | int32_t notarizationTxIndex = 0; // index of notarization if it is added |
634 | int32_t conversionTxIndex = 0; // index of conversion transaction if it is added | |
635 | ||
636 | // export transactions can be created here by aggregating all pending transfer requests and either getting 10 or more together, or | |
637 | // waiting n (10) blocks since the last one. each export must spend the output of the one before it | |
638 | std::vector<CMutableTransaction> exportTransactions; | |
639 | ||
640 | // all transaction outputs requesting conversion to another currency (PBaaS fractional reserve only) | |
641 | // these will be used to calculate conversion price, fees, and generate coinbase conversion output as well as the | |
642 | // conversion output transaction | |
643 | std::vector<CTxOut> reserveConversionTo; | |
644 | std::vector<CTxOut> reserveConversionFrom; | |
645 | ||
68b309c0 | 646 | int64_t pbaasTransparentIn = 0; |
eb0a6550 | 647 | int64_t pbaasTransparentOut = 0; |
1fa4454d | 648 | int64_t blockSubsidy = GetBlockSubsidy(nHeight, consensusParams); |
ebee7b5b | 649 | |
41f170fd MT |
650 | uint160 thisChainID = ConnectedChains.ThisChain().GetChainID(); |
651 | ||
8577896f | 652 | uint256 mmrRoot; |
13ed2980 | 653 | vector<CInputDescriptor> notarizationInputs; |
1fa4454d | 654 | |
41f170fd MT |
655 | // used as scratch for making CCs, should be reinitialized each time |
656 | CCcontract_info CC; | |
657 | CCcontract_info *cp; | |
658 | vector<CTxDestination> vKeys; | |
c3250dcd | 659 | CPubKey pkCC; |
41f170fd MT |
660 | |
661 | // Create coinbase tx and set up the null input with height | |
662 | CMutableTransaction coinbaseTx = CreateNewContextualCMutableTransaction(consensusParams, nHeight); | |
bb6c3482 | 663 | coinbaseTx.vin.push_back(CTxIn(uint256(), (uint32_t)-1, CScript() << nHeight << OP_0)); |
41f170fd MT |
664 | |
665 | // default outputs for mining and before stake guard or fee calculation | |
666 | // store the relative weight in the amount output to convert later to a relative portion | |
667 | // of the reward + fees | |
668 | for (auto &spk : minerOutputs) | |
669 | { | |
670 | coinbaseTx.vout.push_back(CTxOut(spk.first, spk.second)); | |
671 | } | |
672 | ||
673 | // we will update amounts and fees later, but convert the guarded output now for validity checking and size estimate | |
674 | if (isStake) | |
675 | { | |
676 | // if there is a specific destination, use it | |
677 | CTransaction stakeTx(txStaked); | |
678 | CStakeParams p; | |
679 | if (ValidateStakeTransaction(stakeTx, p, false)) | |
680 | { | |
681 | if (!p.pk.IsValid()) | |
682 | { | |
683 | LogPrintf("CreateNewBlock: invalid public key\n"); | |
684 | fprintf(stderr,"CreateNewBlock: invalid public key\n"); | |
685 | return NULL; | |
686 | } | |
687 | for (auto &cbOutput : coinbaseTx.vout) | |
688 | { | |
689 | if (!MakeGuardedOutput(cbOutput.nValue, p.pk, stakeTx, cbOutput)) | |
690 | { | |
691 | LogPrintf("CreateNewBlock: failed to make GuardedOutput on staking coinbase\n"); | |
692 | fprintf(stderr,"CreateNewBlock: failed to make GuardedOutput on staking coinbase\n"); | |
693 | return NULL; | |
694 | } | |
695 | } | |
696 | } | |
697 | else | |
698 | { | |
699 | LogPrintf("CreateNewBlock: invalid stake transaction\n"); | |
700 | fprintf(stderr,"CreateNewBlock: invalid stake transaction\n"); | |
701 | return NULL; | |
702 | } | |
703 | } | |
704 | ||
34d1aa13 MT |
705 | CAmount totalEmission = blockSubsidy; |
706 | ||
1fa4454d | 707 | // make earned notarization only if this is not the notary chain and we have enough subsidy |
41f170fd | 708 | if (!isVerusActive) |
2299bd95 | 709 | { |
68b309c0 | 710 | // if we don't have a connected root PBaaS chain, we can't properly check |
41f170fd | 711 | // and notarize the start block, so we have to pass the notarization and cross chain steps |
989b1de1 | 712 | bool notaryConnected = ConnectedChains.IsVerusPBaaSAvailable() && ConnectedChains.notaryChainHeight >= PBAAS_STARTBLOCK; |
e7e14f44 | 713 | |
e7c700b5 | 714 | // get current currency state differently, depending on height |
e7e14f44 MT |
715 | if (nHeight == 1) |
716 | { | |
5b122537 | 717 | blockSubsidy -= GetBlockOnePremine(); // separate subsidy, which can go to miner, from premine |
718 | ||
e7e14f44 MT |
719 | if (!notaryConnected) |
720 | { | |
e7c700b5 | 721 | // cannt make block 1 unless we can properly notarize that the launch chain is past the start block |
e7e14f44 MT |
722 | return NULL; |
723 | } | |
724 | ||
e7c700b5 | 725 | // if some amount of pre-conversion was allowed |
e7e14f44 MT |
726 | if (thisChain.maxpreconvert) |
727 | { | |
728 | // this is invalid | |
729 | if (thisChain.conversion <= 0) | |
730 | { | |
731 | return NULL; | |
732 | } | |
733 | ||
734 | // get the total amount pre-converted | |
735 | UniValue params(UniValue::VARR); | |
736 | params.push_back(ASSETCHAINS_CHAINID.GetHex()); | |
737 | ||
738 | UniValue result; | |
739 | try | |
740 | { | |
741 | result = find_value(RPCCallRoot("getinitialcurrencystate", params), "result"); | |
742 | } catch (exception e) | |
743 | { | |
744 | result = NullUniValue; | |
745 | } | |
746 | ||
58148aef | 747 | if (!result.isNull()) |
748 | { | |
749 | currencyState = CCoinbaseCurrencyState(result); | |
750 | } | |
751 | ||
752 | if (result.isNull() || !currencyState.IsValid()) | |
e7e14f44 MT |
753 | { |
754 | // no matter what happens, we should be able to get a valid currency state of some sort, if not, fail | |
755 | LogPrintf("Unable to get initial currency state to create block.\n"); | |
756 | printf("Failure to get initial currency state. Cannot create block.\n"); | |
757 | return NULL; | |
758 | } | |
44bbca51 | 759 | |
760 | if (currencyState.ReserveIn < ConnectedChains.ThisChain().minpreconvert) | |
761 | { | |
762 | // no matter what happens, we should be able to get a valid currency state of some sort, if not, fail | |
763 | LogPrintf("This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\n"); | |
764 | printf("This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\n"); | |
765 | return NULL; | |
766 | } | |
e7e14f44 | 767 | } |
41f170fd MT |
768 | |
769 | // add needed block one coinbase outputs | |
88bc6df5 | 770 | // send normal reward to the miner, premine to the address in the chain definition, and pre-converted to the |
41f170fd | 771 | // import thread out |
dd4f0fdd | 772 | if (GetBlockOnePremine()) |
e7e14f44 | 773 | { |
41f170fd MT |
774 | premineOut = CTxOut(GetBlockOnePremine(), GetScriptForDestination(CTxDestination(ConnectedChains.ThisChain().address))); |
775 | coinbaseTx.vout.push_back(premineOut); | |
e7e14f44 | 776 | } |
41f170fd MT |
777 | |
778 | // chain definition - always | |
779 | // make the chain definition output | |
780 | vKeys.clear(); | |
781 | cp = CCinit(&CC, EVAL_PBAASDEFINITION); | |
782 | ||
783 | // send this to EVAL_PBAASDEFINITION address as a destination, locked by the default pubkey | |
c3250dcd | 784 | pkCC = CPubKey(ParseHex(CC.CChexstr)); |
41f170fd MT |
785 | vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(thisChainID, EVAL_PBAASDEFINITION))); |
786 | thisChain.preconverted = currencyState.ReserveIn; // update known, preconverted amount | |
715182a4 | 787 | |
c3250dcd | 788 | chainDefinitionOut = MakeCC1of1Vout(EVAL_PBAASDEFINITION, 0, pkCC, vKeys, thisChain); |
41f170fd MT |
789 | coinbaseTx.vout.push_back(chainDefinitionOut); |
790 | ||
791 | // import - only spendable for reserve currency or currency with preconversion to allow import of conversions, this output will include | |
90100fac | 792 | // all pre-converted coins and all pre-conversion fees, denominated in Verus reserve currency |
41f170fd MT |
793 | vKeys.clear(); |
794 | cp = CCinit(&CC, EVAL_CROSSCHAIN_IMPORT); | |
795 | ||
c3250dcd MT |
796 | pkCC = CPubKey(ParseHex(CC.CChexstr)); |
797 | ||
798 | // import thread is specific to the chain importing from | |
799 | vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.notaryChain.GetChainID(), EVAL_CROSSCHAIN_IMPORT))); | |
41f170fd | 800 | |
1b268198 | 801 | // log import of all reserve in as well as the fees that are passed through the initial ReserveOut in the initial import |
41f170fd | 802 | importThreadOut = MakeCC1of1Vout(EVAL_CROSSCHAIN_IMPORT, |
c3250dcd | 803 | currencyState.ReserveToNative(thisChain.preconverted, thisChain.conversion), pkCC, vKeys, |
1b268198 | 804 | CCrossChainImport(ConnectedChains.NotaryChain().GetChainID(), currencyState.ReserveIn + currencyState.ReserveOut.nValue)); |
c3250dcd | 805 | |
41f170fd MT |
806 | coinbaseTx.vout.push_back(importThreadOut); |
807 | ||
808 | // export - currently only spendable for reserve currency, but added for future capabilities | |
809 | vKeys.clear(); | |
810 | cp = CCinit(&CC, EVAL_CROSSCHAIN_EXPORT); | |
811 | ||
c3250dcd | 812 | pkCC = CPubKey(ParseHex(CC.CChexstr)); |
85ed4204 | 813 | vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.NotaryChain().GetChainID(), EVAL_CROSSCHAIN_EXPORT))); |
41f170fd | 814 | |
c3250dcd | 815 | exportThreadOut = MakeCC1of1Vout(EVAL_CROSSCHAIN_EXPORT, 0, pkCC, vKeys, |
41f170fd | 816 | CCrossChainExport(ConnectedChains.NotaryChain().GetChainID(), 0, 0, 0)); |
5cd8b21a | 817 | |
41f170fd | 818 | coinbaseTx.vout.push_back(exportThreadOut); |
e7e14f44 MT |
819 | } |
820 | else | |
4fa3b13d | 821 | { |
e7e14f44 | 822 | CBlock block; |
e7c700b5 | 823 | assert(nHeight > 1); |
41f170fd | 824 | currencyState = ConnectedChains.GetCurrencyState(nHeight - 1); |
1f15dff1 | 825 | currencyState.Fees = 0; |
5b122537 | 826 | currencyState.ConversionFees = 0; |
1f15dff1 | 827 | currencyState.NativeIn = 0; |
828 | currencyState.ReserveIn = 0; | |
829 | currencyState.ReserveOut.nValue = 0; | |
830 | ||
41f170fd | 831 | if (!currencyState.IsValid()) |
e7e14f44 | 832 | { |
41f170fd MT |
833 | // we should be able to get a valid currency state, if not, fail |
834 | LogPrintf("Unable to get initial currency state to create block #%d.\n", nHeight); | |
835 | printf("Failure to get initial currency state. Cannot create block #%d.\n", nHeight); | |
836 | return NULL; | |
e7e14f44 | 837 | } |
989b1de1 MT |
838 | } |
839 | ||
34d1aa13 | 840 | // update the currency state to include emissions before calculating conversions |
58148aef | 841 | // premine is an emission that is factored in before this |
34d1aa13 MT |
842 | currencyState.UpdateWithEmission(totalEmission); |
843 | ||
41f170fd MT |
844 | // always add currency state output for coinbase |
845 | vKeys.clear(); | |
846 | cp = CCinit(&CC, EVAL_CURRENCYSTATE); | |
847 | ||
7b961d96 | 848 | CPubKey currencyOutPK(ParseHex(cp->CChexstr)); |
41f170fd | 849 | vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(thisChainID, EVAL_CURRENCYSTATE)))); |
41f170fd MT |
850 | |
851 | // make an output that either carries zero coins pre-converting, or the initial supply for block 1, conversion amounts will be adjusted later | |
7b961d96 | 852 | currencyStateOut = MakeCC1of1Vout(EVAL_CURRENCYSTATE, 0, currencyOutPK, vKeys, currencyState); |
41f170fd MT |
853 | |
854 | coinbaseTx.vout.push_back(currencyStateOut); | |
855 | ||
989b1de1 | 856 | if (notaryConnected) |
4fa3b13d | 857 | { |
41f170fd | 858 | // if we have access to our notary daemon |
1fa4454d | 859 | // create a notarization if we would qualify, and add it to the mempool and block |
687e93d5 | 860 | CTransaction prevTx, crossTx, lastConfirmed, lastImportTx; |
4fa3b13d | 861 | ChainMerkleMountainView mmv = chainActive.GetMMV(); |
8577896f | 862 | mmrRoot = mmv.GetRoot(); |
1fa4454d MT |
863 | int32_t confirmedInput = -1; |
864 | CTxDestination confirmedDest; | |
687e93d5 | 865 | if (CreateEarnedNotarization(newNotarizationTx, notarizationInputs, prevTx, crossTx, lastConfirmed, nHeight, &confirmedInput, &confirmedDest)) |
4fa3b13d | 866 | { |
1fa4454d MT |
867 | // we have a valid, earned notarization transaction. we still need to complete it as follows: |
868 | // 1. Add an instant-spend input from the coinbase transaction to fund the finalization output | |
869 | // | |
870 | // 2. if we are spending finalization outputs, create an output of the same amount as a finalization output | |
871 | // plus and any excess from the other, orphaned finalizations to the creator of the confirmed notarization | |
872 | // | |
e7e14f44 | 873 | // 3. make sure the currency state is correct |
1fa4454d MT |
874 | |
875 | // input should either be 0 or PBAAS_MINNOTARIZATIONOUTPUT + all finalized outputs | |
41f170fd | 876 | // we will add PBAAS_MINNOTARIZATIONOUTPUT from a coinbase instant spend in all cases and double that when it is 0 for block 1 |
68b309c0 MT |
877 | for (const CTxIn& txin : newNotarizationTx.vin) |
878 | { | |
879 | const uint256& prevHash = txin.prevout.hash; | |
1fa4454d | 880 | const CCoins *pcoins = view.AccessCoins(prevHash); |
68b309c0 MT |
881 | pbaasTransparentIn += pcoins && (pcoins->vout.size() > txin.prevout.n) ? pcoins->vout[txin.prevout.n].nValue : 0; |
882 | } | |
eb0a6550 | 883 | |
1fa4454d MT |
884 | // calculate the amount that will be sent to the confirmed notary address |
885 | // this will only be non-zero if we have finalized inputs | |
886 | if (pbaasTransparentIn > 0) | |
eb0a6550 | 887 | { |
1fa4454d | 888 | pbaasTransparentOut = pbaasTransparentIn - PBAAS_MINNOTARIZATIONOUTPUT; |
eb0a6550 | 889 | } |
890 | ||
1fa4454d | 891 | if (pbaasTransparentOut) |
eb0a6550 | 892 | { |
1fa4454d MT |
893 | // if we are on a non-fungible chain, reward out must be unspendable |
894 | // make a normal output to the confirmed notary with the excess right behind the op_return | |
895 | // TODO: make this a cc out to only allow spending on a fungible chain | |
896 | CTxOut rewardOut = CTxOut(pbaasTransparentOut, GetScriptForDestination(confirmedDest)); | |
897 | newNotarizationTx.vout.insert(newNotarizationTx.vout.begin() + newNotarizationTx.vout.size() - 1, rewardOut); | |
eb0a6550 | 898 | } |
41f170fd MT |
899 | |
900 | // make the earned notarization coinbase output | |
901 | vKeys.clear(); | |
902 | cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION); | |
903 | ||
904 | // send this to EVAL_EARNEDNOTARIZATION address as a destination, locked by the default pubkey | |
c3250dcd | 905 | pkCC = CPubKey(ParseHex(cp->CChexstr)); |
6b732553 | 906 | vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(VERUS_CHAINID, EVAL_EARNEDNOTARIZATION)))); |
41f170fd MT |
907 | |
908 | int64_t needed = nHeight == 1 ? PBAAS_MINNOTARIZATIONOUTPUT << 1 : PBAAS_MINNOTARIZATIONOUTPUT; | |
909 | ||
910 | // output duplicate notarization as coinbase output for instant spend to notarization | |
911 | // the output amount is considered part of the total value of this coinbase | |
912 | CPBaaSNotarization pbn(newNotarizationTx); | |
c3250dcd | 913 | notarizationOut = MakeCC1of1Vout(EVAL_EARNEDNOTARIZATION, needed, pkCC, vKeys, pbn); |
41f170fd MT |
914 | coinbaseTx.vout.push_back(notarizationOut); |
915 | ||
bb6c3482 | 916 | // place the notarization |
68b309c0 MT |
917 | pblock->vtx.push_back(CTransaction(newNotarizationTx)); |
918 | pblocktemplate->vTxFees.push_back(0); | |
919 | pblocktemplate->vTxSigOps.push_back(-1); // updated at end | |
bb6c3482 | 920 | nBlockSize += GetSerializeSize(newNotarizationTx, SER_NETWORK, PROTOCOL_VERSION); |
921 | notarizationTxIndex = pblock->vtx.size() - 1; | |
922 | nBlockTx++; | |
68b309c0 MT |
923 | } |
924 | else if (nHeight == 1) | |
925 | { | |
926 | // failed to notarize at block 1 | |
927 | return NULL; | |
4fa3b13d | 928 | } |
687e93d5 MT |
929 | |
930 | // if we have a last confirmed notarization, then check for new imports from the notary chain | |
931 | if (lastConfirmed.vout.size()) | |
833b3007 | 932 | { |
687e93d5 | 933 | // we need to find the last unspent import transaction |
88d014d0 | 934 | std::vector<CAddressUnspentDbEntry> unspentOutputs; |
687e93d5 MT |
935 | |
936 | bool found = false; | |
937 | ||
938 | // we cannot get export to a chain that has shut down | |
939 | // if the chain definition is spent, a chain is inactive | |
940 | if (GetAddressUnspent(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.NotaryChain().GetChainID(), EVAL_CROSSCHAIN_IMPORT)), 1, unspentOutputs)) | |
941 | { | |
0c21c983 | 942 | // if one spends the prior one, get the one that is not spent |
687e93d5 MT |
943 | for (auto txidx : unspentOutputs) |
944 | { | |
687e93d5 MT |
945 | uint256 blkHash; |
946 | CTransaction itx; | |
947 | if (myGetTransaction(txidx.first.txhash, lastImportTx, blkHash) && | |
948 | CCrossChainImport(lastImportTx).IsValid() && | |
949 | (lastImportTx.IsCoinBase() || | |
950 | (myGetTransaction(lastImportTx.vin[0].prevout.hash, itx, blkHash) && | |
951 | CCrossChainImport(itx).IsValid()))) | |
952 | { | |
953 | found = true; | |
0c21c983 | 954 | break; |
687e93d5 MT |
955 | } |
956 | } | |
957 | } | |
958 | ||
67aac3cf | 959 | if (found && pwalletMain) |
687e93d5 MT |
960 | { |
961 | UniValue params(UniValue::VARR); | |
962 | UniValue param(UniValue::VOBJ); | |
963 | ||
4f86f9ca | 964 | CMutableTransaction txTemplate = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight); |
965 | int i; | |
966 | for (i = 0; i < lastImportTx.vout.size(); i++) | |
687e93d5 | 967 | { |
4f86f9ca | 968 | COptCCParams p; |
969 | if (lastImportTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.evalCode == EVAL_CROSSCHAIN_IMPORT) | |
970 | { | |
971 | txTemplate.vin.push_back(CTxIn(lastImportTx.GetHash(), (uint32_t)i)); | |
972 | break; | |
973 | } | |
974 | } | |
975 | ||
976 | UniValue result = NullUniValue; | |
977 | if (i < lastImportTx.vout.size()) | |
687e93d5 | 978 | { |
4f86f9ca | 979 | param.push_back(Pair("name", thisChain.name)); |
980 | param.push_back(Pair("lastimporttx", EncodeHexTx(lastImportTx))); | |
981 | param.push_back(Pair("lastconfirmednotarization", EncodeHexTx(lastConfirmed))); | |
5e346982 | 982 | param.push_back(Pair("importtxtemplate", EncodeHexTx(txTemplate))); |
05075a67 | 983 | param.push_back(Pair("totalimportavailable", lastImportTx.vout[txTemplate.vin[0].prevout.n].nValue)); |
4f86f9ca | 984 | params.push_back(param); |
985 | ||
986 | try | |
987 | { | |
988 | result = find_value(RPCCallRoot("getlatestimportsout", params), "result"); | |
989 | } catch (exception e) | |
990 | { | |
991 | printf("Could not get latest imports from notary chain\n"); | |
992 | } | |
687e93d5 MT |
993 | } |
994 | ||
67aac3cf | 995 | if (result.isArray() && result.size()) |
687e93d5 MT |
996 | { |
997 | LOCK(pwalletMain->cs_wallet); | |
998 | ||
999 | uint256 lastImportHash = lastImportTx.GetHash(); | |
1000 | for (int i = 0; i < result.size(); i++) | |
1001 | { | |
1002 | CTransaction itx; | |
1003 | if (result[i].isStr() && DecodeHexTx(itx, result[i].get_str()) && itx.vin.size() && itx.vin[0].prevout.hash == lastImportHash) | |
1004 | { | |
0574c740 | 1005 | // sign the transaction spending the last import and add to mempool |
687e93d5 MT |
1006 | CMutableTransaction mtx(itx); |
1007 | CCrossChainImport cci(lastImportTx); | |
1008 | ||
1009 | bool signSuccess; | |
1010 | SignatureData sigdata; | |
1011 | CAmount value; | |
1012 | const CScript *pScriptPubKey; | |
1013 | ||
687e93d5 | 1014 | signSuccess = ProduceSignature( |
67aac3cf | 1015 | TransactionSignatureCreator(pwalletMain, &itx, 0, lastImportTx.vout[itx.vin[0].prevout.n].nValue, SIGHASH_ALL), lastImportTx.vout[itx.vin[0].prevout.n].scriptPubKey, sigdata, consensusBranchId); |
687e93d5 | 1016 | |
0574c740 | 1017 | if (!signSuccess) |
687e93d5 | 1018 | { |
0574c740 | 1019 | break; |
687e93d5 MT |
1020 | } |
1021 | ||
0574c740 | 1022 | UpdateTransaction(mtx, 0, sigdata); |
9a91da5a | 1023 | itx = CTransaction(mtx); |
0574c740 | 1024 | |
687e93d5 MT |
1025 | // commit to mempool and remove any conflicts |
1026 | std::list<CTransaction> removed; | |
1027 | mempool.removeConflicts(itx, removed); | |
1028 | CValidationState state; | |
1029 | if (!myAddtomempool(itx, &state)) | |
1030 | { | |
bb6c3482 | 1031 | LogPrintf("Failed to add import transactions to the mempool due to: %s\n", state.GetRejectReason().c_str()); |
1032 | printf("Failed to add import transactions to the mempool due to: %s\n", state.GetRejectReason().c_str()); | |
687e93d5 MT |
1033 | break; // if we failed to add one, the others will fail to spend it |
1034 | } | |
0574c740 | 1035 | |
1036 | lastImportTx = itx; | |
1037 | lastImportHash = itx.GetHash(); | |
687e93d5 MT |
1038 | } |
1039 | } | |
1040 | } | |
1041 | } | |
833b3007 | 1042 | } |
4fa3b13d | 1043 | } |
2299bd95 | 1044 | } |
34d1aa13 MT |
1045 | else |
1046 | { | |
1047 | currencyState.UpdateWithEmission(totalEmission); | |
1048 | } | |
e7e14f44 | 1049 | |
41f170fd MT |
1050 | // coinbase should have all necessary outputs (TODO: timelock is not supported or finished yet) |
1051 | uint32_t nCoinbaseSize = GetSerializeSize(coinbaseTx, SER_NETWORK, PROTOCOL_VERSION); | |
1052 | nBlockSize += nCoinbaseSize; | |
e7c700b5 | 1053 | |
41f170fd MT |
1054 | // now create the priority array, including market order reserve transactions, since they can always execute, leave limits for later |
1055 | bool haveReserveTransactions = false; | |
1056 | uint32_t reserveExchangeLimitSize = 0; | |
1057 | std::vector<const CTransaction *> limitOrders; | |
2299bd95 | 1058 | |
41f170fd | 1059 | // now add transactions from the mem pool to the priority heap |
e328fa32 | 1060 | for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin(); |
4d707d51 | 1061 | mi != mempool.mapTx.end(); ++mi) |
d247a5d1 | 1062 | { |
e328fa32 | 1063 | const CTransaction& tx = mi->GetTx(); |
41f170fd | 1064 | uint256 hash = tx.GetHash(); |
e9e70b95 | 1065 | |
a1d3c6fb | 1066 | int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) |
e9e70b95 | 1067 | ? nMedianTimePast |
1068 | : pblock->GetBlockTime(); | |
9c034267 | 1069 | |
9bb37bf0 | 1070 | if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight)) |
61f8caf2 | 1071 | { |
51376f3c | 1072 | //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight)); |
14aa6cc0 | 1073 | continue; |
61f8caf2 | 1074 | } |
9c034267 | 1075 | |
161f617d | 1076 | if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 ) |
6ff77181 | 1077 | { |
64b45b71 | 1078 | //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime); |
d247a5d1 | 1079 | continue; |
14aa6cc0 | 1080 | } |
df756d24 | 1081 | |
d247a5d1 JG |
1082 | COrphan* porphan = NULL; |
1083 | double dPriority = 0; | |
a372168e | 1084 | CAmount nTotalIn = 0; |
e7e14f44 | 1085 | CAmount nTotalReserveIn = 0; |
d247a5d1 | 1086 | bool fMissingInputs = false; |
41f170fd MT |
1087 | CReserveTransactionDescriptor rtxd; |
1088 | bool isReserve = mempool.IsKnownReserveTransaction(hash, rtxd); | |
e7e14f44 | 1089 | |
0cb91a8d | 1090 | if (tx.IsCoinImport()) |
d247a5d1 | 1091 | { |
0cb91a8d SS |
1092 | CAmount nValueIn = GetCoinImportValue(tx); |
1093 | nTotalIn += nValueIn; | |
1094 | dPriority += (double)nValueIn * 1000; // flat multiplier | |
1095 | } else { | |
41f170fd | 1096 | // separate limit orders to be added later, we add them at the end, failed fill or kills are normal transactions, consider them reserve txs |
15e4d481 | 1097 | if (isReserve && rtxd.IsReserveExchange() && rtxd.IsLimit()) |
41f170fd MT |
1098 | { |
1099 | // if we might expire, refresh and check again | |
1100 | if (rtxd.IsFillOrKill()) | |
1101 | { | |
1102 | rtxd = CReserveTransactionDescriptor(tx, view, nHeight); | |
1103 | mempool.PrioritiseReserveTransaction(rtxd, currencyState); | |
1104 | } | |
1105 | ||
1106 | // if is is a failed conversion, drop through | |
1107 | if (!rtxd.IsFillOrKillFail()) | |
1108 | { | |
1109 | limitOrders.push_back(&tx); | |
1110 | reserveExchangeLimitSize += GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
41f170fd MT |
1111 | continue; |
1112 | } | |
1113 | } | |
1114 | if (isReserve) | |
1115 | { | |
1116 | nTotalIn += rtxd.nativeIn; | |
1117 | nTotalReserveIn += rtxd.reserveIn; | |
1118 | } | |
0cb91a8d | 1119 | BOOST_FOREACH(const CTxIn& txin, tx.vin) |
d247a5d1 | 1120 | { |
41f170fd MT |
1121 | CAmount nValueIn = 0, nReserveValueIn = 0; |
1122 | ||
0cb91a8d SS |
1123 | // Read prev transaction |
1124 | if (!view.HaveCoins(txin.prevout.hash)) | |
d247a5d1 | 1125 | { |
0cb91a8d SS |
1126 | // This should never happen; all transactions in the memory |
1127 | // pool should connect to either transactions in the chain | |
1128 | // or other transactions in the memory pool. | |
1129 | if (!mempool.mapTx.count(txin.prevout.hash)) | |
1130 | { | |
1131 | LogPrintf("ERROR: mempool transaction missing input\n"); | |
1132 | if (fDebug) assert("mempool transaction missing input" == 0); | |
1133 | fMissingInputs = true; | |
1134 | if (porphan) | |
1135 | vOrphan.pop_back(); | |
1136 | break; | |
1137 | } | |
1138 | ||
1139 | // Has to wait for dependencies | |
1140 | if (!porphan) | |
1141 | { | |
1142 | // Use list for automatic deletion | |
1143 | vOrphan.push_back(COrphan(&tx)); | |
1144 | porphan = &vOrphan.back(); | |
1145 | } | |
1146 | mapDependers[txin.prevout.hash].push_back(porphan); | |
1147 | porphan->setDependsOn.insert(txin.prevout.hash); | |
e7e14f44 MT |
1148 | |
1149 | const CTransaction &otx = mempool.mapTx.find(txin.prevout.hash)->GetTx(); | |
e7e14f44 | 1150 | // consider reserve outputs and set priority according to their value here as well |
71a3314d | 1151 | if (!isReserve) |
e7e14f44 | 1152 | { |
71a3314d | 1153 | nTotalIn += otx.vout[txin.prevout.n].nValue; |
e7e14f44 | 1154 | } |
0cb91a8d | 1155 | continue; |
d247a5d1 | 1156 | } |
0cb91a8d SS |
1157 | const CCoins* coins = view.AccessCoins(txin.prevout.hash); |
1158 | assert(coins); | |
1159 | ||
e7e14f44 | 1160 | // consider reserve outputs and set priority according to their value here as well |
41f170fd | 1161 | if (isReserve) |
e7e14f44 | 1162 | { |
41f170fd | 1163 | nReserveValueIn = coins->vout[txin.prevout.n].ReserveOutValue(); |
e7e14f44 | 1164 | } |
0cb91a8d | 1165 | |
41f170fd | 1166 | nValueIn = coins->vout[txin.prevout.n].nValue; |
0cb91a8d SS |
1167 | int nConf = nHeight - coins->nHeight; |
1168 | ||
41f170fd | 1169 | dPriority += ((double)((nReserveValueIn ? currencyState.ReserveToNative(nReserveValueIn) : 0) + nValueIn)) * nConf; |
71a3314d | 1170 | |
1171 | // reserve is totaled differently | |
1172 | if (!isReserve) | |
1173 | { | |
1174 | nTotalIn += nValueIn; | |
1175 | nTotalReserveIn += nReserveValueIn; | |
1176 | } | |
d247a5d1 | 1177 | } |
9feb4b9e | 1178 | nTotalIn += tx.GetShieldedValueIn(); |
d247a5d1 | 1179 | } |
0cb91a8d | 1180 | |
d247a5d1 | 1181 | if (fMissingInputs) continue; |
e9e70b95 | 1182 | |
d6eb2599 | 1183 | // Priority is sum(valuein * age) / modified_txsize |
d247a5d1 | 1184 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
4d707d51 | 1185 | dPriority = tx.ComputePriority(dPriority, nTxSize); |
e9e70b95 | 1186 | |
41f170fd MT |
1187 | CAmount nDeltaValueIn = nTotalIn + (nTotalReserveIn ? currencyState.ReserveToNative(nTotalReserveIn) : 0); |
1188 | CAmount nFeeValueIn = nDeltaValueIn; | |
1189 | mempool.ApplyDeltas(hash, dPriority, nDeltaValueIn); | |
e7e14f44 | 1190 | |
71a3314d | 1191 | CAmount nativeEquivalentOut = 0; |
e7e14f44 MT |
1192 | |
1193 | // if there is reserve in, or this is a reserveexchange transaction, calculate fee properly | |
41f170fd | 1194 | if (isReserve & rtxd.reserveOut) |
e7e14f44 MT |
1195 | { |
1196 | // if this has reserve currency out, convert it to native currency for fee calculation | |
71a3314d | 1197 | nativeEquivalentOut = currencyState.ReserveToNative(rtxd.reserveOut); |
e7e14f44 MT |
1198 | } |
1199 | ||
a1a4dc8b | 1200 | CFeeRate feeRate(isReserve ? rtxd.AllFeesAsNative(currencyState) + currencyState.ReserveToNative(rtxd.reserveConversionFees) + rtxd.nativeConversionFees : nFeeValueIn - (tx.GetValueOut() + nativeEquivalentOut), nTxSize); |
e7e14f44 | 1201 | |
d247a5d1 JG |
1202 | if (porphan) |
1203 | { | |
1204 | porphan->dPriority = dPriority; | |
c6cb21d1 | 1205 | porphan->feeRate = feeRate; |
d247a5d1 JG |
1206 | } |
1207 | else | |
e328fa32 | 1208 | vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx()))); |
d247a5d1 | 1209 | } |
df756d24 | 1210 | |
41f170fd MT |
1211 | // |
1212 | // NOW -- REALLY START TO FILL THE BLOCK | |
bb6c3482 | 1213 | // |
41f170fd | 1214 | // estimate number of conversions, staking transaction size, and additional coinbase outputs that will be required |
e7c700b5 | 1215 | |
41f170fd | 1216 | int32_t maxPreLimitOrderBlockSize = nBlockMaxSize - std::min(nBlockMaxSize >> 2, reserveExchangeLimitSize); |
e7e14f44 | 1217 | |
355ca565 | 1218 | int64_t interest; |
d247a5d1 | 1219 | bool fSortedByFee = (nBlockPrioritySize <= 0); |
41f170fd | 1220 | |
d247a5d1 JG |
1221 | TxPriorityCompare comparer(fSortedByFee); |
1222 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
41f170fd MT |
1223 | |
1224 | std::vector<int> reservePositions; | |
1225 | ||
1226 | // now loop and fill the block, leaving space for reserve exchange limit transactions | |
d247a5d1 JG |
1227 | while (!vecPriority.empty()) |
1228 | { | |
1229 | // Take highest priority transaction off the priority queue: | |
1230 | double dPriority = vecPriority.front().get<0>(); | |
c6cb21d1 | 1231 | CFeeRate feeRate = vecPriority.front().get<1>(); |
4d707d51 | 1232 | const CTransaction& tx = *(vecPriority.front().get<2>()); |
e9e70b95 | 1233 | |
d247a5d1 JG |
1234 | std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); |
1235 | vecPriority.pop_back(); | |
e9e70b95 | 1236 | |
d247a5d1 JG |
1237 | // Size limits |
1238 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
41f170fd | 1239 | if (nBlockSize + nTxSize >= maxPreLimitOrderBlockSize - autoTxSize) // room for extra autotx |
61f8caf2 | 1240 | { |
41f170fd | 1241 | //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d maxPreLimitOrderBlockSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)maxPreLimitOrderBlockSize); |
d247a5d1 | 1242 | continue; |
61f8caf2 | 1243 | } |
e9e70b95 | 1244 | |
d247a5d1 JG |
1245 | // Legacy limits on sigOps: |
1246 | unsigned int nTxSigOps = GetLegacySigOpCount(tx); | |
a4a40a38 | 1247 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) |
61f8caf2 | 1248 | { |
51376f3c | 1249 | //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS); |
d247a5d1 | 1250 | continue; |
61f8caf2 | 1251 | } |
d247a5d1 | 1252 | // Skip free transactions if we're past the minimum block size: |
805344dc | 1253 | const uint256& hash = tx.GetHash(); |
2a72d459 | 1254 | double dPriorityDelta = 0; |
a372168e | 1255 | CAmount nFeeDelta = 0; |
2a72d459 | 1256 | mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta); |
13fc83c7 | 1257 | if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) |
61f8caf2 | 1258 | { |
51376f3c | 1259 | //fprintf(stderr,"fee rate skip\n"); |
d247a5d1 | 1260 | continue; |
61f8caf2 | 1261 | } |
41f170fd | 1262 | |
2a72d459 | 1263 | // Prioritise by fee once past the priority size or we run out of high-priority |
d247a5d1 JG |
1264 | // transactions: |
1265 | if (!fSortedByFee && | |
1266 | ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority))) | |
1267 | { | |
1268 | fSortedByFee = true; | |
1269 | comparer = TxPriorityCompare(fSortedByFee); | |
1270 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
1271 | } | |
e9e70b95 | 1272 | |
d247a5d1 | 1273 | if (!view.HaveInputs(tx)) |
61f8caf2 | 1274 | { |
51376f3c | 1275 | //fprintf(stderr,"dont have inputs\n"); |
d247a5d1 | 1276 | continue; |
61f8caf2 | 1277 | } |
41f170fd MT |
1278 | CAmount nTxFees; |
1279 | CReserveTransactionDescriptor txDesc; | |
1280 | bool isReserve = mempool.IsKnownReserveTransaction(hash, txDesc); | |
1281 | ||
88bc6df5 | 1282 | nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut(); |
e9e70b95 | 1283 | |
d247a5d1 | 1284 | nTxSigOps += GetP2SHSigOpCount(tx, view); |
a4a40a38 | 1285 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) |
61f8caf2 | 1286 | { |
51376f3c | 1287 | //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS); |
d247a5d1 | 1288 | continue; |
61f8caf2 | 1289 | } |
41f170fd | 1290 | |
68f7d1d7 PT |
1291 | // Note that flags: we don't want to set mempool/IsStandard() |
1292 | // policy here, but we still have to ensure that the block we | |
1293 | // create only contains transactions that are valid in new blocks. | |
d247a5d1 | 1294 | CValidationState state; |
6514771a | 1295 | PrecomputedTransactionData txdata(tx); |
be126699 | 1296 | if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId)) |
61f8caf2 | 1297 | { |
51376f3c | 1298 | //fprintf(stderr,"context failure\n"); |
d247a5d1 | 1299 | continue; |
61f8caf2 | 1300 | } |
e7e14f44 | 1301 | |
8cb98d91 | 1302 | UpdateCoins(tx, view, nHeight); |
d247a5d1 | 1303 | |
41f170fd MT |
1304 | if (isReserve) |
1305 | { | |
88bc6df5 | 1306 | nTxFees = 0; // we will adjust all reserve transaction fees when we get an accurate conversion rate |
41f170fd MT |
1307 | reservePositions.push_back(nBlockTx); |
1308 | haveReserveTransactions = true; | |
1309 | } | |
1310 | ||
31a04d28 SB |
1311 | BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) { |
1312 | sapling_tree.append(outDescription.cm); | |
1313 | } | |
1314 | ||
d247a5d1 JG |
1315 | // Added |
1316 | pblock->vtx.push_back(tx); | |
1317 | pblocktemplate->vTxFees.push_back(nTxFees); | |
1318 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
1319 | nBlockSize += nTxSize; | |
1320 | ++nBlockTx; | |
1321 | nBlockSigOps += nTxSigOps; | |
1322 | nFees += nTxFees; | |
e9e70b95 | 1323 | |
d247a5d1 JG |
1324 | if (fPrintPriority) |
1325 | { | |
3f0813b3 | 1326 | LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString()); |
d247a5d1 | 1327 | } |
e9e70b95 | 1328 | |
d247a5d1 JG |
1329 | // Add transactions that depend on this one to the priority queue |
1330 | if (mapDependers.count(hash)) | |
1331 | { | |
1332 | BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) | |
1333 | { | |
1334 | if (!porphan->setDependsOn.empty()) | |
1335 | { | |
1336 | porphan->setDependsOn.erase(hash); | |
1337 | if (porphan->setDependsOn.empty()) | |
1338 | { | |
c6cb21d1 | 1339 | vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx)); |
d247a5d1 JG |
1340 | std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); |
1341 | } | |
1342 | } | |
1343 | } | |
1344 | } | |
1345 | } | |
135fa24e | 1346 | |
41f170fd MT |
1347 | // if we have reserve transactions or limit transactions to add: |
1348 | // 1. collect all the reserve transactions from the block and add them to the reserveFills vector | |
1349 | // 2. add all limit transactions to the orders vector | |
1350 | // 3. match orders to include all limit transactions that qualify and will fit | |
a1a4dc8b | 1351 | CAmount conversionFees = 0; |
86e31e3d | 1352 | |
41f170fd | 1353 | if (haveReserveTransactions) |
a4a40a38 | 1354 | { |
41f170fd MT |
1355 | std::vector<CReserveTransactionDescriptor> reserveFills; |
1356 | std::vector<const CTransaction *> expiredFillOrKills; | |
1357 | std::vector<const CTransaction *> noFills; | |
1358 | std::vector<const CTransaction *> rejects; | |
1f722359 | 1359 | |
41f170fd MT |
1360 | // identify all reserve transactions in the block to calculate fees |
1361 | for (int i = 0; i < reservePositions.size(); i++) | |
1f722359 | 1362 | { |
41f170fd | 1363 | CReserveTransactionDescriptor txDesc; |
0059e3a5 | 1364 | if (mempool.IsKnownReserveTransaction(pblock->vtx[reservePositions[i]].GetHash(), txDesc)) |
41f170fd MT |
1365 | { |
1366 | reserveFills.push_back(txDesc); | |
1367 | } | |
1368 | } | |
17d0160a | 1369 | |
41f170fd MT |
1370 | // now, we need to have room for the transaction which will spend the coinbase |
1371 | // and output all conversions mined/staked | |
1372 | newConversionOutputTx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight); | |
9e87ac50 | 1373 | newConversionOutputTx.vin.resize(1); // placeholder for size calculation |
cd230e37 | 1374 | |
41f170fd | 1375 | int64_t newBlockSize = nBlockSize; |
88bc6df5 | 1376 | |
47aecf2f | 1377 | // TODO:PBAAS - NEED TO ADD SIGOPS LIMIT TO THIS FOR HARDENING |
1378 | CCoinbaseCurrencyState newState = currencyState.MatchOrders(limitOrders, | |
1379 | reserveFills, | |
1380 | expiredFillOrKills, | |
1381 | noFills, | |
1382 | rejects, | |
1383 | exchangeRate, nHeight, conversionInputs, | |
1384 | nBlockMaxSize - autoTxSize, &newBlockSize, &newConversionOutputTx); | |
88bc6df5 | 1385 | |
a1a4dc8b | 1386 | // TODO:PBAAS - account for the edge case where we have too large expected fills and have no room |
1387 | // for transactions that we would otherwise take | |
88bc6df5 | 1388 | assert(reserveFills.size() >= reservePositions.size()); |
41f170fd MT |
1389 | |
1390 | // create the conversion transaction and all outputs indicated by every single mined transaction | |
41f170fd MT |
1391 | if (reserveFills.size()) |
1392 | { | |
607402ba | 1393 | currencyState = newState; |
1f722359 | 1394 | } |
86e31e3d | 1395 | |
88bc6df5 | 1396 | int oldRPSize = reservePositions.size(); |
41f170fd | 1397 | |
88bc6df5 MT |
1398 | // add the rest of the reserve fills that have not yet been added to the block, |
1399 | for (int i = oldRPSize; i < reserveFills.size(); i++) | |
1f722359 | 1400 | { |
88bc6df5 MT |
1401 | // add these transactions to the block |
1402 | reservePositions.push_back(nBlockTx); | |
1403 | pblock->vtx.push_back(*reserveFills[i].ptx); | |
1404 | const CTransaction &tx = pblock->vtx.back(); | |
cd230e37 | 1405 | |
88bc6df5 | 1406 | UpdateCoins(tx, view, nHeight); |
41f170fd | 1407 | |
88bc6df5 MT |
1408 | BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) { |
1409 | sapling_tree.append(outDescription.cm); | |
1410 | } | |
41f170fd | 1411 | |
88bc6df5 MT |
1412 | CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate); |
1413 | uint32_t nTxSigOps = GetLegacySigOpCount(tx); | |
41f170fd | 1414 | |
88bc6df5 MT |
1415 | // size was already updated |
1416 | pblocktemplate->vTxFees.push_back(nTxFees); | |
1417 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
1418 | ++nBlockTx; | |
1419 | nBlockSigOps += nTxSigOps; | |
1420 | nFees += nTxFees; | |
1f722359 MT |
1421 | } |
1422 | ||
88bc6df5 MT |
1423 | // update block size with the calculation from the function called, which includes all additional transactions, |
1424 | // but does not include the conversion transaction, since its final size is still unknown | |
1425 | nBlockSize = newBlockSize; | |
41f170fd | 1426 | |
88bc6df5 MT |
1427 | // fixup the transaction block template fees that were added before we knew the correct exchange rate and |
1428 | // add them to the block fee total | |
1429 | for (int i = 0; i < oldRPSize; i++) | |
a4a40a38 | 1430 | { |
88bc6df5 MT |
1431 | assert(pblocktemplate->vTxFees.size() > reservePositions[i]); |
1432 | CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate); | |
1433 | pblocktemplate->vTxFees[reservePositions[i]] = nTxFees; | |
1434 | nFees += nTxFees; | |
1f722359 | 1435 | } |
86e31e3d | 1436 | |
88bc6df5 | 1437 | // remake the newConversionOutputTx, right now, it has dummy inputs and placeholder outputs, just remake it correctly |
9e87ac50 | 1438 | newConversionOutputTx.vin.resize(1); |
88bc6df5 | 1439 | newConversionOutputTx.vout.clear(); |
0574c740 | 1440 | conversionInputs.clear(); |
86e31e3d | 1441 | |
9e87ac50 | 1442 | // keep one placeholder for txCoinbase output as input and remake with the correct exchange rate |
88bc6df5 | 1443 | for (auto fill : reserveFills) |
a4a40a38 | 1444 | { |
0574c740 | 1445 | fill.AddConversionInOuts(newConversionOutputTx, conversionInputs, exchangeRate, ¤cyState); |
41f170fd | 1446 | } |
a4a40a38 | 1447 | } |
abb90a89 | 1448 | |
05ece4c3 | 1449 | // first calculate and distribute block rewards, including fees in the minerOutputs vector |
88bc6df5 | 1450 | CAmount rewardTotalShareAmount = 0; |
a1a4dc8b | 1451 | CAmount rewardTotal = blockSubsidy + currencyState.ConversionFees + nFees; |
1452 | ||
d6f7d693 | 1453 | CAmount rewardLeft = notarizationTxIndex ? rewardTotal - notarizationOut.nValue : rewardTotal; |
41f170fd | 1454 | |
88bc6df5 | 1455 | for (auto &outputShare : minerOutputs) |
06f41160 | 1456 | { |
88bc6df5 MT |
1457 | rewardTotalShareAmount += outputShare.first; |
1458 | } | |
41f170fd | 1459 | |
88bc6df5 MT |
1460 | int cbOutIdx; |
1461 | for (cbOutIdx = 0; cbOutIdx < minerOutputs.size(); cbOutIdx++) | |
1462 | { | |
1463 | CAmount amount = (arith_uint256(rewardTotal) * arith_uint256(minerOutputs[cbOutIdx].first) / arith_uint256(rewardTotalShareAmount)).GetLow64(); | |
1464 | if (rewardLeft <= amount || (cbOutIdx + 1) == minerOutputs.size()) | |
06f41160 | 1465 | { |
88bc6df5 MT |
1466 | amount = rewardLeft; |
1467 | } | |
1468 | rewardLeft -= amount; | |
1469 | coinbaseTx.vout[cbOutIdx].nValue = amount; | |
1470 | // the only valid CC output we currently support on coinbases is stake guard, which does not need to be modified for this | |
1471 | } | |
41f170fd | 1472 | |
88bc6df5 MT |
1473 | // premineOut - done |
1474 | if (premineOut.scriptPubKey.size()) | |
1475 | { | |
1476 | cbOutIdx++; | |
1477 | } | |
41f170fd | 1478 | |
88bc6df5 MT |
1479 | // chainDefinitionOut - done |
1480 | if (chainDefinitionOut.scriptPubKey.size()) | |
1481 | { | |
1482 | cbOutIdx++; | |
1483 | } | |
41f170fd | 1484 | |
88bc6df5 MT |
1485 | // importThreadOut - done |
1486 | if (importThreadOut.scriptPubKey.size()) | |
1487 | { | |
1488 | cbOutIdx++; | |
1489 | } | |
41f170fd | 1490 | |
88bc6df5 | 1491 | // exportThreadOut - done |
40951949 | 1492 | if (exportThreadOut.scriptPubKey.size()) |
88bc6df5 MT |
1493 | { |
1494 | cbOutIdx++; | |
1495 | } | |
1496 | ||
90888b8a | 1497 | // currencyStateOut - update currency state, output is present whether or not there is a conversion transaction |
88bc6df5 | 1498 | // the transaction itself pays no fees, but all conversion fees are included for each conversion transaction between its input and this output |
90888b8a | 1499 | if (currencyStateOut.scriptPubKey.size()) |
88bc6df5 | 1500 | { |
19f01561 | 1501 | COptCCParams p; |
1502 | currencyStateOut.scriptPubKey.IsPayToCryptoCondition(p); | |
1503 | p.vData[0] = currencyState.AsVector(); | |
1504 | currencyStateOut.scriptPubKey.ReplaceCCParams(p); | |
1505 | ||
05ece4c3 | 1506 | if (conversionInputs.size()) |
90888b8a | 1507 | { |
90888b8a | 1508 | CTransaction convertTx(newConversionOutputTx); |
93440330 | 1509 | currencyStateOut.nValue = convertTx.GetValueOut(); |
1510 | currencyState.ReserveOut.nValue = convertTx.GetReserveValueOut(); | |
45d7e5d5 | 1511 | |
90888b8a | 1512 | // the coinbase is not finished, store index placeholder here now and fixup hash later |
1513 | newConversionOutputTx.vin[0] = CTxIn(uint256(), cbOutIdx); | |
86e31e3d | 1514 | } |
1515 | else | |
1516 | { | |
05ece4c3 | 1517 | newConversionOutputTx.vin.clear(); |
1518 | newConversionOutputTx.vout.clear(); | |
06f41160 | 1519 | } |
88bc6df5 MT |
1520 | |
1521 | coinbaseTx.vout[cbOutIdx] = currencyStateOut; | |
88bc6df5 | 1522 | cbOutIdx++; |
06f41160 | 1523 | } |
06f41160 | 1524 | |
88bc6df5 MT |
1525 | // notarizationOut - update currencyState in notarization |
1526 | if (notarizationTxIndex) | |
ebee7b5b | 1527 | { |
88bc6df5 MT |
1528 | COptCCParams p; |
1529 | int i; | |
1530 | for (i = 0; i < newNotarizationTx.vout.size(); i++) | |
06f41160 | 1531 | { |
88bc6df5 | 1532 | if (newNotarizationTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.evalCode == EVAL_EARNEDNOTARIZATION) |
86e31e3d | 1533 | { |
88bc6df5 | 1534 | break; |
86e31e3d | 1535 | } |
1536 | } | |
88bc6df5 | 1537 | if (i >= newNotarizationTx.vout.size()) |
ebee7b5b | 1538 | { |
88bc6df5 MT |
1539 | LogPrintf("CreateNewBlock: bad notarization\n"); |
1540 | fprintf(stderr,"CreateNewBlock: bad notarization\n"); | |
1541 | return NULL; | |
ebee7b5b | 1542 | } |
88bc6df5 MT |
1543 | CPBaaSNotarization nz(p.vData[0]); |
1544 | nz.currencyState = currencyState; | |
1545 | p.vData[0] = nz.AsVector(); | |
1546 | newNotarizationTx.vout[i].scriptPubKey.ReplaceCCParams(p); | |
1547 | ||
1548 | notarizationOut.scriptPubKey.IsPayToCryptoCondition(p); | |
1549 | p.vData[0] = nz.AsVector(); | |
1550 | notarizationOut.scriptPubKey.ReplaceCCParams(p); | |
1551 | ||
1552 | coinbaseTx.vout[cbOutIdx] = notarizationOut; | |
1553 | ||
1554 | // now that the coinbase is finished, finish and place conversion transaction before the stake transaction | |
1555 | newNotarizationTx.vin.push_back(CTxIn(uint256(), cbOutIdx)); | |
1556 | ||
1557 | cbOutIdx++; | |
1558 | ||
1559 | pblock->vtx[notarizationTxIndex] = newNotarizationTx; | |
ebee7b5b | 1560 | } |
06f41160 | 1561 | |
88bc6df5 MT |
1562 | // this should be the end of the outputs |
1563 | assert(cbOutIdx == coinbaseTx.vout.size()); | |
1564 | ||
1565 | nLastBlockTx = nBlockTx; | |
1566 | nLastBlockSize = nBlockSize; | |
1567 | ||
1568 | blocktime = std::max(pindexPrev->GetMedianTimePast(), GetAdjustedTime()); | |
1569 | ||
1570 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); | |
1571 | ||
41f170fd | 1572 | coinbaseTx.nExpiryHeight = 0; |
88bc6df5 | 1573 | coinbaseTx.nLockTime = blocktime; |
abb90a89 | 1574 | |
e0bc68e6 | 1575 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
41f170fd | 1576 | coinbaseTx.vout[0].nValue += 5000; |
5034d1c1 | 1577 | |
88bc6df5 | 1578 | /* |
29bd53a1 | 1579 | // check if coinbase transactions must be time locked at current subsidy and prepend the time lock |
a0dd01bc | 1580 | // to transaction if so, cast for GTE operator |
ebee7b5b | 1581 | CAmount cbValueOut = 0; |
41f170fd | 1582 | for (auto txout : coinbaseTx.vout) |
ebee7b5b MT |
1583 | { |
1584 | cbValueOut += txout.nValue; | |
1585 | } | |
1586 | if (cbValueOut >= ASSETCHAINS_TIMELOCKGTE) | |
abb90a89 MT |
1587 | { |
1588 | int32_t opretlen, p2shlen, scriptlen; | |
29bd53a1 | 1589 | CScriptExt opretScript = CScriptExt(); |
abb90a89 | 1590 | |
41f170fd | 1591 | coinbaseTx.vout.push_back(CTxOut()); |
abb90a89 | 1592 | |
29bd53a1 MT |
1593 | // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins |
1594 | // protected only by the time lock rather than 100% inaccessible | |
1595 | opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight)); | |
06f41160 | 1596 | if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition()) |
1597 | { | |
514fde1b | 1598 | LogPrintf("CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n"); |
86e31e3d | 1599 | fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n"); |
06f41160 | 1600 | return 0; |
1601 | } | |
1602 | ||
1603 | opretScript += scriptPubKeyIn; | |
abb90a89 | 1604 | |
41f170fd MT |
1605 | coinbaseTx.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript)); |
1606 | coinbaseTx.vout.back().scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK); | |
1607 | coinbaseTx.vout.back().nValue = 0; | |
48d800c2 | 1608 | } // timelocks and commissions are currently incompatible due to validation complexity of the combination |
5034d1c1 | 1609 | else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 ) |
c9b1071d | 1610 | { |
c000c9ca | 1611 | int32_t i; uint8_t *ptr; |
41f170fd MT |
1612 | coinbaseTx.vout.resize(2); |
1613 | coinbaseTx.vout[1].nValue = commission; | |
1614 | coinbaseTx.vout[1].scriptPubKey.resize(35); | |
1615 | ptr = (uint8_t *)&coinbaseTx.vout[1].scriptPubKey[0]; | |
c000c9ca | 1616 | ptr[0] = 33; |
1617 | for (i=0; i<33; i++) | |
1618 | ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i]; | |
1619 | ptr[34] = OP_CHECKSIG; | |
146d2aa2 | 1620 | //printf("autocreate commision vout\n"); |
c9b1071d | 1621 | } |
88bc6df5 | 1622 | */ |
48d800c2 | 1623 | |
ebee7b5b | 1624 | // finalize input of coinbase |
41f170fd MT |
1625 | coinbaseTx.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(0)) + COINBASE_FLAGS; |
1626 | assert(coinbaseTx.vin[0].scriptSig.size() <= 100); | |
ebee7b5b | 1627 | |
88bc6df5 MT |
1628 | // coinbase is done |
1629 | pblock->vtx[0] = coinbaseTx; | |
1630 | uint256 cbHash = coinbaseTx.GetHash(); | |
ebee7b5b | 1631 | |
88bc6df5 | 1632 | // if there is a conversion, update the correct coinbase hash and add it to the block |
34d1aa13 MT |
1633 | // we also need to sign the conversion transaction |
1634 | if (newConversionOutputTx.vin.size() > 1) | |
68b309c0 | 1635 | { |
a6b1eaf9 | 1636 | // put the coinbase into the updated coins, since we will spend from it |
1637 | UpdateCoins(pblock->vtx[0], view, nHeight); | |
1638 | ||
88bc6df5 | 1639 | newConversionOutputTx.vin[0].prevout.hash = cbHash; |
0574c740 | 1640 | |
1641 | CTransaction ncoTx(newConversionOutputTx); | |
68b309c0 | 1642 | |
0574c740 | 1643 | // sign transaction for cb output and conversions |
1644 | for (int i = 0; i < ncoTx.vin.size(); i++) | |
1645 | { | |
1646 | bool signSuccess; | |
1647 | SignatureData sigdata; | |
1648 | CAmount value; | |
1649 | const CScript *pScriptPubKey; | |
68b309c0 | 1650 | |
0574c740 | 1651 | // if this is our coinbase input, different signing |
1652 | if (i) | |
1653 | { | |
1654 | pScriptPubKey = &conversionInputs[i - 1].scriptPubKey; | |
1655 | value = conversionInputs[i - 1].nValue; | |
1656 | } | |
1657 | else | |
1658 | { | |
1659 | pScriptPubKey = &coinbaseTx.vout[ncoTx.vin[i].prevout.n].scriptPubKey; | |
1660 | value = coinbaseTx.vout[ncoTx.vin[i].prevout.n].nValue; | |
1661 | } | |
68b309c0 | 1662 | |
0574c740 | 1663 | signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ncoTx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId); |
eb0a6550 | 1664 | |
0574c740 | 1665 | if (!signSuccess) |
1666 | { | |
1667 | if (ncoTx.vin[i].prevout.hash == coinbaseTx.GetHash()) | |
1668 | { | |
1669 | LogPrintf("Coinbase conversion source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); | |
1670 | printf("Coinbase conversion source tx - amount: %lu, n: %d, id: %s\n", coinbaseTx.vout[ncoTx.vin[i].prevout.n].nValue, ncoTx.vin[i].prevout.n, coinbaseTx.GetHash().GetHex().c_str()); | |
1671 | } | |
1672 | LogPrintf("CreateNewBlock: failure to sign conversion tx for input %d from output %d of %s\n", i, ncoTx.vin[i].prevout.n, ncoTx.vin[i].prevout.hash.GetHex().c_str()); | |
1673 | printf("CreateNewBlock: failure to sign conversion tx for input %d from output %d of %s\n", i, ncoTx.vin[i].prevout.n, ncoTx.vin[i].prevout.hash.GetHex().c_str()); | |
1674 | return NULL; | |
1675 | } else { | |
1676 | UpdateTransaction(newConversionOutputTx, i, sigdata); | |
1677 | } | |
1678 | } | |
68b309c0 | 1679 | |
88bc6df5 MT |
1680 | UpdateCoins(newConversionOutputTx, view, nHeight); |
1681 | pblock->vtx.push_back(newConversionOutputTx); | |
93440330 | 1682 | pblocktemplate->vTxFees.push_back(0); |
88bc6df5 MT |
1683 | int txSigOps = GetLegacySigOpCount(newConversionOutputTx); |
1684 | pblocktemplate->vTxSigOps.push_back(txSigOps); | |
1685 | nBlockSize += GetSerializeSize(newConversionOutputTx, SER_NETWORK, PROTOCOL_VERSION); | |
1686 | ++nBlockTx; | |
1687 | nBlockSigOps += txSigOps; | |
1688 | } | |
68b309c0 | 1689 | |
88bc6df5 MT |
1690 | // if there is a stake transaction, add it to the very end |
1691 | if (isStake) | |
1692 | { | |
1693 | UpdateCoins(txStaked, view, nHeight); | |
1694 | pblock->vtx.push_back(txStaked); | |
1695 | pblocktemplate->vTxFees.push_back(0); | |
1696 | int txSigOps = GetLegacySigOpCount(txStaked); | |
1697 | pblocktemplate->vTxSigOps.push_back(txSigOps); | |
1698 | // already added to the block size above | |
1699 | ++nBlockTx; | |
1700 | nBlockSigOps += txSigOps; | |
1701 | } | |
68b309c0 | 1702 | |
88bc6df5 | 1703 | extern CWallet *pwalletMain; |
8577896f | 1704 | |
88bc6df5 MT |
1705 | // add final notarization and instant spend coinbase output hash fixup |
1706 | if (notarizationTxIndex) | |
1707 | { | |
1708 | LOCK(pwalletMain->cs_wallet); | |
eb0a6550 | 1709 | |
88bc6df5 | 1710 | newNotarizationTx.vin.back().prevout.hash = cbHash; |
68b309c0 | 1711 | |
88bc6df5 | 1712 | CTransaction ntx(newNotarizationTx); |
68b309c0 | 1713 | |
13ed2980 | 1714 | for (int i = 0; i < ntx.vin.size(); i++) |
68b309c0 MT |
1715 | { |
1716 | bool signSuccess; | |
68b309c0 | 1717 | SignatureData sigdata; |
eb0a6550 | 1718 | CAmount value; |
1719 | const CScript *pScriptPubKey; | |
8577896f | 1720 | |
13ed2980 MT |
1721 | // if this is our coinbase input, we won't find it elsewhere |
1722 | if (i < notarizationInputs.size()) | |
eb0a6550 | 1723 | { |
13ed2980 MT |
1724 | pScriptPubKey = ¬arizationInputs[i].scriptPubKey; |
1725 | value = notarizationInputs[i].nValue; | |
eb0a6550 | 1726 | } |
1727 | else | |
1728 | { | |
41f170fd MT |
1729 | pScriptPubKey = &coinbaseTx.vout[ntx.vin[i].prevout.n].scriptPubKey; |
1730 | value = coinbaseTx.vout[ntx.vin[i].prevout.n].nValue; | |
eb0a6550 | 1731 | } |
8577896f | 1732 | |
eb0a6550 | 1733 | signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ntx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId); |
68b309c0 MT |
1734 | |
1735 | if (!signSuccess) | |
1736 | { | |
41f170fd | 1737 | if (ntx.vin[i].prevout.hash == coinbaseTx.GetHash()) |
4edfdbb0 | 1738 | { |
41f170fd MT |
1739 | LogPrintf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); |
1740 | printf("Coinbase source tx - amount: %lu, n: %d, id: %s\n", coinbaseTx.vout[ntx.vin[i].prevout.n].nValue, ntx.vin[i].prevout.n, coinbaseTx.GetHash().GetHex().c_str()); | |
4edfdbb0 MT |
1741 | } |
1742 | LogPrintf("CreateNewBlock: failure to sign earned notarization for input %d from output %d of %s\n", i, ntx.vin[i].prevout.n, ntx.vin[i].prevout.hash.GetHex().c_str()); | |
1743 | printf("CreateNewBlock: failure to sign earned notarization for input %d from output %d of %s\n", i, ntx.vin[i].prevout.n, ntx.vin[i].prevout.hash.GetHex().c_str()); | |
68b309c0 MT |
1744 | return NULL; |
1745 | } else { | |
88bc6df5 | 1746 | UpdateTransaction(newNotarizationTx, i, sigdata); |
68b309c0 MT |
1747 | } |
1748 | } | |
88bc6df5 | 1749 | pblocktemplate->vTxSigOps[notarizationTxIndex] = GetLegacySigOpCount(newNotarizationTx); |
13ed2980 MT |
1750 | |
1751 | // put now signed notarization back in the block | |
88bc6df5 | 1752 | pblock->vtx[notarizationTxIndex] = newNotarizationTx; |
f3be524a | 1753 | |
41f170fd MT |
1754 | LogPrintf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); |
1755 | //printf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); | |
88bc6df5 | 1756 | LogPrintf("adding notarization tx at height %d, index %d, id: %s\n", nHeight, notarizationTxIndex, newNotarizationTx.GetHash().GetHex().c_str()); |
989b1de1 | 1757 | //printf("adding notarization tx at height %d, index %d, id: %s\n", nHeight, notarizationTxIndex, mntx.GetHash().GetHex().c_str()); |
f3be524a MT |
1758 | { |
1759 | LOCK(cs_main); | |
88bc6df5 | 1760 | for (auto input : newNotarizationTx.vin) |
f3be524a | 1761 | { |
1026ac58 | 1762 | LogPrintf("Earned notarization input n: %d, hash: %s, HaveCoins: %s\n", input.prevout.n, input.prevout.hash.GetHex().c_str(), pcoinsTip->HaveCoins(input.prevout.hash) ? "true" : "false"); |
514fde1b | 1763 | //printf("Earned notarization input n: %d, hash: %s, HaveCoins: %s\n", input.prevout.n, input.prevout.hash.GetHex().c_str(), pcoinsTip->HaveCoins(input.prevout.hash) ? "true" : "false"); |
f3be524a MT |
1764 | } |
1765 | } | |
68b309c0 MT |
1766 | } |
1767 | ||
41f170fd | 1768 | pblock->vtx[0] = coinbaseTx; |
d247a5d1 | 1769 | pblocktemplate->vTxFees[0] = -nFees; |
88bc6df5 | 1770 | pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); |
48d800c2 | 1771 | |
1fae37f6 MT |
1772 | // if not Verus stake, setup nonce, otherwise, leave it alone |
1773 | if (!isStake || ASSETCHAINS_LWMAPOS == 0) | |
1774 | { | |
eb0a6550 | 1775 | // Randomize nonce |
1fae37f6 | 1776 | arith_uint256 nonce = UintToArith256(GetRandHash()); |
48d800c2 | 1777 | |
1fae37f6 MT |
1778 | // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters) |
1779 | nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO]; | |
1780 | nonce >>= 16; | |
1781 | pblock->nNonce = ArithToUint256(nonce); | |
1782 | } | |
e9e70b95 | 1783 | |
d247a5d1 JG |
1784 | // Fill in header |
1785 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); | |
31a04d28 | 1786 | pblock->hashFinalSaplingRoot = sapling_tree.root(); |
0c8fa56a MT |
1787 | |
1788 | // all Verus PoS chains need this data in the block at all times | |
1789 | if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 ) | |
9a0f2798 | 1790 | { |
1791 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); | |
1fae37f6 | 1792 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
9a0f2798 | 1793 | } |
12217420 | 1794 | |
4d068367 | 1795 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
af805d53 | 1796 | { |
28a62b60 | 1797 | uint32_t r; |
496f1fd2 | 1798 | CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1); |
fa04bcf3 | 1799 | if ( pblock->nTime < pindexPrev->nTime+60 ) |
1800 | pblock->nTime = pindexPrev->nTime + 60; | |
16593898 | 1801 | if ( gpucount < 33 ) |
28a62b60 | 1802 | { |
55566f16 | 1803 | uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals; |
28a62b60 | 1804 | memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid); |
1805 | memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height); | |
1806 | memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock); | |
9a146fef | 1807 | vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n); |
55566f16 | 1808 | memcpy(&r,&randvals,sizeof(r)); |
1809 | pblock->nTime += (r % (33 - gpucount)*(33 - gpucount)); | |
28a62b60 | 1810 | } |
a893e994 | 1811 | if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 ) |
496f1fd2 | 1812 | { |
2d79309f | 1813 | CAmount txfees = 5000; |
496f1fd2 | 1814 | pblock->vtx.push_back(txNotary); |
1815 | pblocktemplate->vTxFees.push_back(txfees); | |
1816 | pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary)); | |
1817 | nFees += txfees; | |
2d79309f | 1818 | pblocktemplate->vTxFees[0] = -nFees; |
c881e52b | 1819 | //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees; |
f31815fc | 1820 | //fprintf(stderr,"added notaryvin\n"); |
0857c3d5 | 1821 | } |
1822 | else | |
1823 | { | |
1824 | fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n"); | |
1825 | return(0); | |
1826 | } | |
707b061c | 1827 | } |
809f2e25 | 1828 | else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) ) |
af805d53 | 1829 | { |
8fc79ac9 | 1830 | CValidationState state; |
809f2e25 | 1831 | //fprintf(stderr,"check validity\n"); |
88d014d0 | 1832 | if ( !TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) // invokes CC checks |
8fc79ac9 | 1833 | { |
9feb4b9e | 1834 | throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed"); |
8fc79ac9 | 1835 | } |
809f2e25 | 1836 | //fprintf(stderr,"valid\n"); |
af805d53 | 1837 | } |
d247a5d1 | 1838 | } |
2a6a442a | 1839 | //fprintf(stderr,"done new block\n"); |
1685bba0 MT |
1840 | |
1841 | // setup the header and buid the Merkle tree | |
1842 | unsigned int extraNonce; | |
88d014d0 | 1843 | IncrementExtraNonce(pblock, pindexPrev, extraNonce, true); |
1685bba0 | 1844 | |
d247a5d1 JG |
1845 | return pblocktemplate.release(); |
1846 | } | |
32b915c9 | 1847 | |
1a31463b | 1848 | /* |
e9e70b95 | 1849 | #ifdef ENABLE_WALLET |
1850 | boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey) | |
1851 | #else | |
1852 | boost::optional<CScript> GetMinerScriptPubKey() | |
1853 | #endif | |
1854 | { | |
1855 | CKeyID keyID; | |
1856 | CBitcoinAddress addr; | |
1857 | if (addr.SetString(GetArg("-mineraddress", ""))) { | |
1858 | addr.GetKeyID(keyID); | |
1859 | } else { | |
1860 | #ifdef ENABLE_WALLET | |
1861 | CPubKey pubkey; | |
1862 | if (!reservekey.GetReservedKey(pubkey)) { | |
1863 | return boost::optional<CScript>(); | |
1864 | } | |
1865 | keyID = pubkey.GetID(); | |
1866 | #else | |
1867 | return boost::optional<CScript>(); | |
1868 | #endif | |
1869 | } | |
1870 | ||
1871 | CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; | |
1872 | return scriptPubKey; | |
1873 | } | |
1874 | ||
1875 | #ifdef ENABLE_WALLET | |
1876 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) | |
1877 | { | |
1878 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey); | |
1879 | #else | |
1880 | CBlockTemplate* CreateNewBlockWithKey() | |
1881 | { | |
1882 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(); | |
1883 | #endif | |
1884 | ||
1885 | if (!scriptPubKey) { | |
1886 | return NULL; | |
1887 | } | |
1888 | return CreateNewBlock(*scriptPubKey); | |
1889 | }*/ | |
acfa0333 | 1890 | |
c1de826f JG |
1891 | ////////////////////////////////////////////////////////////////////////////// |
1892 | // | |
1893 | // Internal miner | |
1894 | // | |
1895 | ||
2cc0a252 | 1896 | #ifdef ENABLE_MINING |
c1de826f | 1897 | |
88d014d0 | 1898 | class MinerAddressScript : public CReserveScript |
1899 | { | |
1900 | // CReserveScript requires implementing this function, so that if an | |
1901 | // internal (not-visible) wallet address is used, the wallet can mark it as | |
1902 | // important when a block is mined (so it then appears to the user). | |
1903 | // If -mineraddress is set, the user already knows about and is managing the | |
1904 | // address, so we don't need to do anything here. | |
1905 | void KeepScript() {} | |
1906 | }; | |
1907 | ||
1908 | void GetScriptForMinerAddress(boost::shared_ptr<CReserveScript> &script) | |
1909 | { | |
1910 | CTxDestination addr = DecodeDestination(GetArg("-mineraddress", "")); | |
1911 | if (!IsValidDestination(addr)) { | |
1912 | return; | |
1913 | } | |
1914 | ||
1915 | boost::shared_ptr<MinerAddressScript> mAddr(new MinerAddressScript()); | |
1916 | CKeyID keyID = boost::get<CKeyID>(addr); | |
1917 | ||
1918 | script = mAddr; | |
1919 | script->reserveScript = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; | |
1920 | } | |
1921 | ||
4a85e067 | 1922 | #ifdef ENABLE_WALLET |
acfa0333 WL |
1923 | ////////////////////////////////////////////////////////////////////////////// |
1924 | // | |
1925 | // Internal miner | |
1926 | // | |
acfa0333 | 1927 | |
5034d1c1 | 1928 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake) |
acfa0333 | 1929 | { |
9feb4b9e | 1930 | CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i; |
d9f176ac | 1931 | if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 ) |
1932 | { | |
1933 | scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG; | |
1934 | } | |
1935 | else if ( USE_EXTERNAL_PUBKEY != 0 ) | |
998397aa | 1936 | { |
7bfc207a | 1937 | //fprintf(stderr,"use notary pubkey\n"); |
c95fd5e0 | 1938 | scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG; |
f6c647ed | 1939 | } |
1940 | else | |
1941 | { | |
f1f6dfbb | 1942 | if (!isStake) |
1b5b89ba | 1943 | { |
f1f6dfbb | 1944 | if (!reservekey.GetReservedKey(pubkey)) |
1945 | { | |
1946 | return NULL; | |
1947 | } | |
1948 | scriptPubKey.resize(35); | |
1949 | ptr = (uint8_t *)pubkey.begin(); | |
1950 | scriptPubKey[0] = 33; | |
1951 | for (i=0; i<33; i++) | |
1952 | scriptPubKey[i+1] = ptr[i]; | |
1953 | scriptPubKey[34] = OP_CHECKSIG; | |
1954 | //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; | |
1b5b89ba | 1955 | } |
f6c647ed | 1956 | } |
88d014d0 | 1957 | return CreateNewBlock(Params(), scriptPubKey, gpucount, isStake); |
acfa0333 WL |
1958 | } |
1959 | ||
88d014d0 | 1960 | void komodo_broadcast(const CBlock *pblock,int32_t limit) |
395f10cf | 1961 | { |
1962 | int32_t n = 1; | |
1963 | //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
1964 | { | |
1965 | LOCK(cs_vNodes); | |
1966 | BOOST_FOREACH(CNode* pnode, vNodes) | |
1967 | { | |
1968 | if ( pnode->hSocket == INVALID_SOCKET ) | |
1969 | continue; | |
1970 | if ( (rand() % n) == 0 ) | |
1971 | { | |
1972 | pnode->PushMessage("block", *pblock); | |
1973 | if ( n++ > limit ) | |
1974 | break; | |
1975 | } | |
1976 | } | |
1977 | } | |
1978 | //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
1979 | } | |
945f015d | 1980 | |
269d8ba0 | 1981 | static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) |
8e8b6d70 JG |
1982 | #else |
1983 | static bool ProcessBlockFound(CBlock* pblock) | |
1984 | #endif // ENABLE_WALLET | |
d247a5d1 | 1985 | { |
572c763f | 1986 | int32_t height = chainActive.LastTip()->GetHeight()+1; |
81212588 | 1987 | LogPrintf("%s\n", pblock->ToString()); |
572c763f | 1988 | LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue), height); |
e9e70b95 | 1989 | |
d247a5d1 JG |
1990 | // Found a solution |
1991 | { | |
86131275 | 1992 | if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash()) |
ba8419c7 | 1993 | { |
1994 | uint256 hash; int32_t i; | |
1995 | hash = pblock->hashPrevBlock; | |
92266e99 | 1996 | for (i=31; i>=0; i--) |
ba8419c7 | 1997 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 1998 | fprintf(stderr," <- prev (stale)\n"); |
86131275 | 1999 | hash = chainActive.LastTip()->GetBlockHash(); |
92266e99 | 2000 | for (i=31; i>=0; i--) |
ba8419c7 | 2001 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 2002 | fprintf(stderr," <- chainTip (stale)\n"); |
e9e70b95 | 2003 | |
ffde1589 | 2004 | return error("VerusMiner: generated block is stale"); |
ba8419c7 | 2005 | } |
18e72167 | 2006 | } |
e9e70b95 | 2007 | |
8e8b6d70 | 2008 | #ifdef ENABLE_WALLET |
18e72167 | 2009 | // Remove key from key pool |
998397aa | 2010 | if ( IS_KOMODO_NOTARY == 0 ) |
945f015d | 2011 | { |
2012 | if (GetArg("-mineraddress", "").empty()) { | |
2013 | // Remove key from key pool | |
2014 | reservekey.KeepKey(); | |
2015 | } | |
8e8b6d70 | 2016 | } |
18e72167 | 2017 | // Track how many getdata requests this block gets |
438ba9c1 | 2018 | //if ( 0 ) |
18e72167 | 2019 | { |
d1bc3a75 | 2020 | //fprintf(stderr,"lock cs_wallet\n"); |
18e72167 PW |
2021 | LOCK(wallet.cs_wallet); |
2022 | wallet.mapRequestCount[pblock->GetHash()] = 0; | |
d247a5d1 | 2023 | } |
8e8b6d70 | 2024 | #endif |
d1bc3a75 | 2025 | //fprintf(stderr,"process new block\n"); |
194ad5b8 | 2026 | |
c871d47f | 2027 | // Process this block (almost) the same as if we had received it from another node |
18e72167 | 2028 | CValidationState state; |
88d014d0 | 2029 | if (!ProcessNewBlock(1, chainActive.LastTip()->GetHeight()+1, state, Params(), NULL, pblock, true, NULL)) |
ffde1589 | 2030 | return error("VerusMiner: ProcessNewBlock, block not accepted"); |
e9e70b95 | 2031 | |
d793f94b | 2032 | TrackMinedBlock(pblock->GetHash()); |
395f10cf | 2033 | komodo_broadcast(pblock,16); |
d247a5d1 JG |
2034 | return true; |
2035 | } | |
2036 | ||
078f6af1 | 2037 | int32_t komodo_baseid(char *origbase); |
a30dd993 | 2038 | int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height); |
13691369 | 2039 | arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); |
8ee93080 | 2040 | int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; |
99ba67a0 | 2041 | extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC; |
8b51b9e4 | 2042 | int32_t roundrobin_delay; |
18443f69 | 2043 | arith_uint256 HASHTarget,HASHTarget_POW; |
3363d1c0 | 2044 | int32_t komodo_longestchain(); |
078f6af1 | 2045 | |
5642c96c | 2046 | // wait for peers to connect |
12217420 | 2047 | void waitForPeers(const CChainParams &chainparams) |
5642c96c | 2048 | { |
2049 | if (chainparams.MiningRequiresPeers()) | |
2050 | { | |
3da69a31 MT |
2051 | bool fvNodesEmpty; |
2052 | { | |
00a7120e | 2053 | boost::this_thread::interruption_point(); |
3da69a31 MT |
2054 | LOCK(cs_vNodes); |
2055 | fvNodesEmpty = vNodes.empty(); | |
2056 | } | |
3363d1c0 | 2057 | int longestchain = komodo_longestchain(); |
2058 | int lastlongest = 0; | |
2059 | if (fvNodesEmpty || IsNotInSync() || (longestchain != 0 && longestchain > chainActive.LastTip()->GetHeight())) | |
3da69a31 | 2060 | { |
af2e212d | 2061 | int loops = 0, blockDiff = 0, newDiff = 0; |
2062 | ||
3da69a31 | 2063 | do { |
64d6048f | 2064 | if (fvNodesEmpty) |
3da69a31 | 2065 | { |
69fa3d0e | 2066 | MilliSleep(1000 + rand() % 4000); |
00a7120e | 2067 | boost::this_thread::interruption_point(); |
3da69a31 MT |
2068 | LOCK(cs_vNodes); |
2069 | fvNodesEmpty = vNodes.empty(); | |
af2e212d | 2070 | loops = 0; |
2071 | blockDiff = 0; | |
3363d1c0 | 2072 | lastlongest = 0; |
af2e212d | 2073 | } |
3363d1c0 | 2074 | else if ((newDiff = IsNotInSync()) > 0) |
af2e212d | 2075 | { |
2076 | if (blockDiff != newDiff) | |
2077 | { | |
2078 | blockDiff = newDiff; | |
2079 | } | |
2080 | else | |
2081 | { | |
3363d1c0 | 2082 | if (++loops <= 5) |
af2e212d | 2083 | { |
2084 | MilliSleep(1000); | |
2085 | } | |
2086 | else break; | |
2087 | } | |
3363d1c0 | 2088 | lastlongest = 0; |
2089 | } | |
2090 | else if (!fvNodesEmpty && !IsNotInSync() && longestchain > chainActive.LastTip()->GetHeight()) | |
2091 | { | |
2092 | // the only thing may be that we are seeing a long chain that we'll never get | |
2093 | // don't wait forever | |
2094 | if (lastlongest == 0) | |
2095 | { | |
2096 | MilliSleep(3000); | |
2097 | lastlongest = longestchain; | |
2098 | } | |
3da69a31 | 2099 | } |
af2e212d | 2100 | } while (fvNodesEmpty || IsNotInSync()); |
0ba20651 | 2101 | MilliSleep(100 + rand() % 400); |
3da69a31 | 2102 | } |
5642c96c | 2103 | } |
2104 | } | |
2105 | ||
42181656 | 2106 | #ifdef ENABLE_WALLET |
d7e6718d MT |
2107 | CBlockIndex *get_chainactive(int32_t height) |
2108 | { | |
3c40a9a6 | 2109 | if ( chainActive.LastTip() != 0 ) |
d7e6718d | 2110 | { |
4b729ec5 | 2111 | if ( height <= chainActive.LastTip()->GetHeight() ) |
3c40a9a6 MT |
2112 | { |
2113 | LOCK(cs_main); | |
d7e6718d | 2114 | return(chainActive[height]); |
3c40a9a6 | 2115 | } |
4b729ec5 | 2116 | // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight()); |
d7e6718d MT |
2117 | } |
2118 | //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height); | |
2119 | return(0); | |
2120 | } | |
2121 | ||
135fa24e | 2122 | /* |
2123 | * A separate thread to stake, while the miner threads mine. | |
2124 | */ | |
2125 | void static VerusStaker(CWallet *pwallet) | |
2126 | { | |
2127 | LogPrintf("Verus staker thread started\n"); | |
2128 | RenameThread("verus-staker"); | |
2129 | ||
2130 | const CChainParams& chainparams = Params(); | |
2d02c19e | 2131 | auto consensusParams = chainparams.GetConsensus(); |
135fa24e | 2132 | |
2133 | // Each thread has its own key | |
2134 | CReserveKey reservekey(pwallet); | |
2135 | ||
2136 | // Each thread has its own counter | |
2137 | unsigned int nExtraNonce = 0; | |
12217420 | 2138 | |
135fa24e | 2139 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; |
2140 | ||
4b729ec5 | 2141 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && |
135fa24e | 2142 | { |
2143 | sleep(1); | |
2144 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
2145 | break; | |
2146 | } | |
2147 | ||
2148 | // try a nice clean peer connection to start | |
bf9c36f4 MT |
2149 | CBlockIndex *pindexPrev, *pindexCur; |
2150 | do { | |
2151 | pindexPrev = chainActive.LastTip(); | |
2152 | MilliSleep(5000 + rand() % 5000); | |
2153 | waitForPeers(chainparams); | |
2154 | pindexCur = chainActive.LastTip(); | |
2155 | } while (pindexPrev != pindexCur); | |
c132b91a | 2156 | |
135fa24e | 2157 | try { |
0fc0dc56 | 2158 | static int32_t lastStakingHeight = 0; |
2159 | ||
135fa24e | 2160 | while (true) |
2161 | { | |
135fa24e | 2162 | waitForPeers(chainparams); |
4ca6678c | 2163 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
135fa24e | 2164 | |
2165 | // Create new block | |
2166 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
0fc0dc56 | 2167 | |
4b729ec5 | 2168 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
135fa24e | 2169 | { |
4b729ec5 | 2170 | Mining_height = pindexPrev->GetHeight()+1; |
135fa24e | 2171 | Mining_start = (uint32_t)time(NULL); |
2172 | } | |
2173 | ||
1fae37f6 MT |
2174 | // Check for stop or if block needs to be rebuilt |
2175 | boost::this_thread::interruption_point(); | |
2176 | ||
135fa24e | 2177 | // try to stake a block |
1fae37f6 MT |
2178 | CBlockTemplate *ptr = NULL; |
2179 | if (Mining_height > VERUS_MIN_STAKEAGE) | |
5034d1c1 | 2180 | ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true); |
135fa24e | 2181 | |
a73ab4b4 | 2182 | // TODO - putting this output here tends to help mitigate announcing a staking height earlier than |
2183 | // announcing the last block win when we start staking before a block's acceptance has been | |
2184 | // acknowledged by the mining thread - a better solution may be to put the output on the submission | |
2185 | // thread. | |
2186 | if ( ptr == 0 && Mining_height != lastStakingHeight ) | |
2187 | { | |
2188 | printf("Staking height %d for %s\n", Mining_height, ASSETCHAINS_SYMBOL); | |
2189 | } | |
2190 | lastStakingHeight = Mining_height; | |
2191 | ||
135fa24e | 2192 | if ( ptr == 0 ) |
2193 | { | |
1fae37f6 | 2194 | // wait to try another staking block until after the tip moves again |
37ad6886 | 2195 | while ( chainActive.LastTip() == pindexPrev ) |
bab13dd2 | 2196 | MilliSleep(250); |
135fa24e | 2197 | continue; |
2198 | } | |
2199 | ||
2200 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); | |
2201 | if (!pblocktemplate.get()) | |
2202 | { | |
2203 | if (GetArg("-mineraddress", "").empty()) { | |
1fae37f6 | 2204 | LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
135fa24e | 2205 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
2206 | } else { | |
2207 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
1fae37f6 | 2208 | LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
135fa24e | 2209 | } |
2210 | return; | |
2211 | } | |
2212 | ||
2213 | CBlock *pblock = &pblocktemplate->block; | |
1fae37f6 | 2214 | LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); |
135fa24e | 2215 | // |
2216 | // Search | |
2217 | // | |
1fae37f6 MT |
2218 | int64_t nStart = GetTime(); |
2219 | ||
1fae37f6 MT |
2220 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) |
2221 | { | |
2222 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2223 | { | |
2224 | fprintf(stderr,"no nodes, attempting reconnect\n"); | |
2225 | continue; | |
2226 | } | |
2227 | } | |
2228 | ||
2229 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) | |
2230 | { | |
2231 | fprintf(stderr,"timeout, retrying\n"); | |
2232 | continue; | |
2233 | } | |
135fa24e | 2234 | |
37ad6886 | 2235 | if ( pindexPrev != chainActive.LastTip() ) |
135fa24e | 2236 | { |
4b729ec5 | 2237 | printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight()); |
135fa24e | 2238 | MilliSleep(250); |
2239 | continue; | |
2240 | } | |
2241 | ||
1fae37f6 MT |
2242 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); |
2243 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); | |
135fa24e | 2244 | |
1fae37f6 | 2245 | uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits)); |
135fa24e | 2246 | |
df756d24 | 2247 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); |
b9956efc | 2248 | |
df756d24 | 2249 | UpdateTime(pblock, consensusParams, pindexPrev); |
b9956efc | 2250 | |
ed47e5ec MT |
2251 | if (ProcessBlockFound(pblock, *pwallet, reservekey)) |
2252 | { | |
2253 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); | |
2254 | LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex()); | |
2255 | printf("Found block %d \n", Mining_height ); | |
2256 | printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); | |
2257 | arith_uint256 post; | |
2258 | post.SetCompact(pblock->GetVerusPOSTarget()); | |
2259 | pindexPrev = get_chainactive(Mining_height - 100); | |
2260 | CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1]; | |
2261 | printf("POS hash: %s \ntarget: %s\n", | |
2262 | CTransaction::_GetVerusPOSHash(&(pblock->nNonce), sTx.vin[0].prevout.hash, sTx.vin[0].prevout.n, Mining_height, pindexPrev->GetBlockHeader().GetVerusEntropyHash(Mining_height - 100), sTx.vout[0].nValue).GetHex().c_str(), ArithToUint256(post).GetHex().c_str()); | |
2263 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) | |
2264 | printf("- timelocked until block %i\n", unlockTime); | |
2265 | else | |
2266 | printf("\n"); | |
2267 | } | |
1fae37f6 | 2268 | else |
ed47e5ec MT |
2269 | { |
2270 | LogPrintf("Found block rejected at staking height: %d\n", Mining_height); | |
2271 | printf("Found block rejected at staking height: %d\n", Mining_height); | |
2272 | } | |
135fa24e | 2273 | |
1fae37f6 MT |
2274 | // Check for stop or if block needs to be rebuilt |
2275 | boost::this_thread::interruption_point(); | |
135fa24e | 2276 | |
bf9c36f4 | 2277 | sleep(3); |
3da69a31 | 2278 | |
1fae37f6 MT |
2279 | // In regression test mode, stop mining after a block is found. |
2280 | if (chainparams.MineBlocksOnDemand()) { | |
2281 | throw boost::thread_interrupted(); | |
135fa24e | 2282 | } |
2283 | } | |
2284 | } | |
2285 | catch (const boost::thread_interrupted&) | |
2286 | { | |
135fa24e | 2287 | LogPrintf("VerusStaker terminated\n"); |
2288 | throw; | |
2289 | } | |
2290 | catch (const std::runtime_error &e) | |
2291 | { | |
135fa24e | 2292 | LogPrintf("VerusStaker runtime error: %s\n", e.what()); |
2293 | return; | |
2294 | } | |
135fa24e | 2295 | } |
2296 | ||
1e435b54 | 2297 | typedef bool (*minefunction)(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint32_t solutionVersion, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); |
2298 | bool mine_verus_v2(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint32_t solutionVersion, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); | |
2299 | bool mine_verus_v2_port(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint32_t solutionVersion, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); | |
fa7fdbc6 | 2300 | |
42181656 | 2301 | void static BitcoinMiner_noeq(CWallet *pwallet) |
2302 | #else | |
2303 | void static BitcoinMiner_noeq() | |
2304 | #endif | |
2305 | { | |
05f6e633 | 2306 | LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
05f6e633 | 2307 | RenameThread("verushash-miner"); |
42181656 | 2308 | |
2309 | #ifdef ENABLE_WALLET | |
2310 | // Each thread has its own key | |
2311 | CReserveKey reservekey(pwallet); | |
2312 | #endif | |
2313 | ||
2910478b | 2314 | const CChainParams& chainparams = Params(); |
42181656 | 2315 | // Each thread has its own counter |
2316 | unsigned int nExtraNonce = 0; | |
12217420 | 2317 | |
42181656 | 2318 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; |
2319 | ||
4b729ec5 | 2320 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && |
42181656 | 2321 | { |
2322 | sleep(1); | |
2323 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
2324 | break; | |
2325 | } | |
9f3e2213 | 2326 | |
3da69a31 MT |
2327 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2328 | ||
5642c96c | 2329 | // try a nice clean peer connection to start |
c132b91a | 2330 | CBlockIndex *pindexPrev, *pindexCur; |
9f3e2213 | 2331 | do { |
37ad6886 | 2332 | pindexPrev = chainActive.LastTip(); |
3da69a31 | 2333 | MilliSleep(5000 + rand() % 5000); |
bf9c36f4 | 2334 | waitForPeers(chainparams); |
37ad6886 | 2335 | pindexCur = chainActive.LastTip(); |
c132b91a | 2336 | } while (pindexPrev != pindexCur); |
6176a421 | 2337 | |
a9f18272 | 2338 | // make sure that we have checked for PBaaS availability |
2339 | ConnectedChains.CheckVerusPBaaSAvailable(); | |
2340 | ||
dbe656fe MT |
2341 | // this will not stop printing more than once in all cases, but it will allow us to print in all cases |
2342 | // and print duplicates rarely without having to synchronize | |
2343 | static CBlockIndex *lastChainTipPrinted; | |
90198f71 | 2344 | static int32_t lastMiningHeight = 0; |
9f3e2213 | 2345 | |
42181656 | 2346 | miningTimer.start(); |
2347 | ||
2348 | try { | |
dbe656fe | 2349 | printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
08d46b7f | 2350 | |
08d46b7f | 2351 | // v2 hash writer |
2352 | CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION); | |
2353 | ||
42181656 | 2354 | while (true) |
2355 | { | |
68334c8d | 2356 | miningTimer.stop(); |
2357 | waitForPeers(chainparams); | |
dfcf8255 | 2358 | |
37ad6886 | 2359 | pindexPrev = chainActive.LastTip(); |
dfcf8255 | 2360 | |
f8f61a6d | 2361 | // prevent forking on startup before the diff algorithm kicks in, |
2362 | // but only for a startup Verus test chain. PBaaS chains have the difficulty inherited from | |
2363 | // their parent | |
57055854 | 2364 | if (chainparams.MiningRequiresPeers() && ((IsVerusActive() && pindexPrev->GetHeight() < 50) || pindexPrev != chainActive.LastTip())) |
dfcf8255 MT |
2365 | { |
2366 | do { | |
37ad6886 | 2367 | pindexPrev = chainActive.LastTip(); |
2830db29 | 2368 | MilliSleep(2000 + rand() % 2000); |
37ad6886 | 2369 | } while (pindexPrev != chainActive.LastTip()); |
dfcf8255 | 2370 | } |
42181656 | 2371 | |
2372 | // Create new block | |
2373 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
4b729ec5 | 2374 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
42181656 | 2375 | { |
4b729ec5 | 2376 | Mining_height = pindexPrev->GetHeight()+1; |
90198f71 | 2377 | if (lastMiningHeight != Mining_height) |
2378 | { | |
2379 | lastMiningHeight = Mining_height; | |
dc74c06d | 2380 | printf("Mining %s at height %d\n", ASSETCHAINS_SYMBOL, Mining_height); |
90198f71 | 2381 | } |
42181656 | 2382 | Mining_start = (uint32_t)time(NULL); |
2383 | } | |
2384 | ||
dbe656fe | 2385 | miningTimer.start(); |
42181656 | 2386 | |
2387 | #ifdef ENABLE_WALLET | |
5034d1c1 | 2388 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0); |
42181656 | 2389 | #else |
2390 | CBlockTemplate *ptr = CreateNewBlockWithKey(); | |
2391 | #endif | |
2392 | if ( ptr == 0 ) | |
2393 | { | |
2394 | static uint32_t counter; | |
f6084562 MT |
2395 | if ( counter++ % 40 == 0 ) |
2396 | { | |
2397 | if (!IsVerusActive() && | |
2398 | ConnectedChains.IsVerusPBaaSAvailable() && | |
2399 | ConnectedChains.notaryChainHeight < ConnectedChains.ThisChain().startBlock) | |
2400 | { | |
2401 | fprintf(stderr,"Waiting for block %d on %s chain to start. Current block is %d\n", ConnectedChains.ThisChain().startBlock, | |
2402 | ConnectedChains.notaryChain.chainDefinition.name.c_str(), | |
2403 | ConnectedChains.notaryChainHeight); | |
2404 | } | |
2405 | else | |
2406 | { | |
2407 | fprintf(stderr,"Unable to create valid block... will continue to try\n"); | |
2408 | } | |
2409 | } | |
2830db29 | 2410 | MilliSleep(2000); |
42181656 | 2411 | continue; |
2412 | } | |
dbe656fe | 2413 | |
42181656 | 2414 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
2415 | if (!pblocktemplate.get()) | |
2416 | { | |
2417 | if (GetArg("-mineraddress", "").empty()) { | |
05f6e633 | 2418 | LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
2419 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); | |
42181656 | 2420 | } else { |
2421 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
05f6e633 | 2422 | LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
42181656 | 2423 | } |
2424 | return; | |
2425 | } | |
2426 | CBlock *pblock = &pblocktemplate->block; | |
f8f61a6d | 2427 | |
2428 | uint32_t savebits; | |
2429 | bool mergeMining = false; | |
2430 | savebits = pblock->nBits; | |
2431 | ||
1e435b54 | 2432 | uint32_t solutionVersion = CConstVerusSolutionVector::Version(pblock->nSolution); |
f8f61a6d | 2433 | bool verusHashV2 = pblock->nVersion == CBlockHeader::VERUS_V2; |
1e435b54 | 2434 | bool verusSolutionGTEV3 = solutionVersion >= CActivationHeight::SOLUTION_VERUSV3; |
2435 | bool verusSolutionV4 = solutionVersion >= CActivationHeight::SOLUTION_VERUSV4; | |
f8f61a6d | 2436 | |
42181656 | 2437 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
2438 | { | |
2439 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) | |
2440 | { | |
2441 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2442 | { | |
2443 | static uint32_t counter; | |
2444 | if ( counter++ < 10 ) | |
2445 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
2446 | sleep(10); | |
2447 | continue; | |
2448 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
2449 | } | |
2450 | } | |
b2a98c42 | 2451 | |
c871d47f | 2452 | // set our easiest target, if V3+, no need to rebuild the merkle tree |
598ba98b | 2453 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, verusSolutionV4 ? false : true, &savebits); |
b2a98c42 MT |
2454 | |
2455 | // update PBaaS header | |
598ba98b | 2456 | if (verusSolutionV4) |
b2a98c42 | 2457 | { |
2fd1f0fb | 2458 | if (!IsVerusActive() && ConnectedChains.IsVerusPBaaSAvailable()) |
f8f61a6d | 2459 | { |
b2a98c42 | 2460 | |
2fd1f0fb | 2461 | UniValue params(UniValue::VARR); |
2462 | UniValue error(UniValue::VARR); | |
2463 | params.push_back(EncodeHexBlk(*pblock)); | |
2464 | params.push_back(ASSETCHAINS_SYMBOL); | |
2465 | params.push_back(ASSETCHAINS_RPCHOST); | |
2466 | params.push_back(ASSETCHAINS_RPCPORT); | |
2467 | params.push_back(ASSETCHAINS_RPCCREDENTIALS); | |
2468 | try | |
b2a98c42 | 2469 | { |
be17c611 | 2470 | ConnectedChains.lastSubmissionFailed = false; |
2fd1f0fb | 2471 | params = RPCCallRoot("addmergedblock", params); |
2472 | params = find_value(params, "result"); | |
2473 | error = find_value(params, "error"); | |
2474 | } catch (std::exception e) | |
2475 | { | |
2476 | printf("Failed to connect to %s chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str()); | |
2477 | params = UniValue(e.what()); | |
b2a98c42 | 2478 | } |
2fd1f0fb | 2479 | if (mergeMining = (params.isNull() && error.isNull())) |
f8f61a6d | 2480 | { |
a1d91f89 | 2481 | printf("Merge mining %s with %s as the hashing chain\n", ASSETCHAINS_SYMBOL, ConnectedChains.notaryChain.chainDefinition.name.c_str()); |
2482 | LogPrintf("Merge mining with %s as the hashing chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str()); | |
f8f61a6d | 2483 | } |
b2a98c42 MT |
2484 | } |
2485 | } | |
2486 | ||
42181656 | 2487 | LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], |
2488 | pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); | |
2489 | // | |
2490 | // Search | |
2491 | // | |
f8f61a6d | 2492 | int64_t nStart = GetTime(); |
42181656 | 2493 | |
f8f61a6d | 2494 | arith_uint256 hashTarget = arith_uint256().SetCompact(savebits); |
fa7fdbc6 | 2495 | uint256 uintTarget = ArithToUint256(hashTarget); |
f8f61a6d | 2496 | arith_uint256 ourTarget; |
2497 | ourTarget.SetCompact(pblock->nBits); | |
2498 | ||
42181656 | 2499 | Mining_start = 0; |
ef70c5b2 | 2500 | |
37ad6886 | 2501 | if ( pindexPrev != chainActive.LastTip() ) |
05f6e633 | 2502 | { |
37ad6886 | 2503 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 2504 | { |
37ad6886 | 2505 | lastChainTipPrinted = chainActive.LastTip(); |
4b729ec5 | 2506 | printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); |
dbe656fe | 2507 | } |
f8f61a6d | 2508 | MilliSleep(100); |
05f6e633 | 2509 | continue; |
2510 | } | |
ef70c5b2 | 2511 | |
135fa24e | 2512 | if ( ASSETCHAINS_STAKED != 0 ) |
2513 | { | |
2514 | int32_t percPoS,z; | |
2515 | hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED); | |
2516 | for (z=31; z>=0; z--) | |
2517 | fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); | |
2518 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
2519 | } | |
2520 | ||
2830db29 | 2521 | uint64_t count; |
2522 | uint64_t hashesToGo = 0; | |
2523 | uint64_t totalDone = 0; | |
2524 | ||
fa7fdbc6 | 2525 | if (!verusHashV2) |
458bfcab | 2526 | { |
fa7fdbc6 | 2527 | // must not be in sync |
2528 | printf("Mining on incorrect block version.\n"); | |
2529 | sleep(2); | |
2530 | continue; | |
458bfcab | 2531 | } |
2532 | ||
e29b5dd5 | 2533 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); |
fa7fdbc6 | 2534 | count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; |
db027133 | 2535 | CVerusHashV2 *vh2 = &ss2.GetState(); |
3b500530 | 2536 | u128 *hashKey; |
2537 | verusclhasher &vclh = vh2->vclh; | |
fa7fdbc6 | 2538 | minefunction mine_verus; |
2539 | mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port; | |
f21fad6a | 2540 | |
42181656 | 2541 | while (true) |
2542 | { | |
4dcb64c0 | 2543 | uint256 hashResult = uint256(); |
458bfcab | 2544 | |
e5fb645e | 2545 | unsigned char *curBuf; |
2546 | ||
f8f61a6d | 2547 | if (mergeMining) |
42181656 | 2548 | { |
c89d86ee | 2549 | // loop for a few minutes before refreshing the block |
e771a884 | 2550 | while (true) |
12217420 | 2551 | { |
93ff475b | 2552 | uint256 ourMerkle = pblock->hashMerkleRoot; |
a1d91f89 | 2553 | if ( pindexPrev != chainActive.LastTip() ) |
2554 | { | |
2555 | if (lastChainTipPrinted != chainActive.LastTip()) | |
2556 | { | |
2557 | lastChainTipPrinted = chainActive.LastTip(); | |
2558 | printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight()); | |
2559 | arith_uint256 target; | |
2560 | target.SetCompact(lastChainTipPrinted->nBits); | |
93ff475b MT |
2561 | if (ourMerkle == lastChainTipPrinted->hashMerkleRoot) |
2562 | { | |
2563 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str()); | |
607402ba | 2564 | printf("Found block %d \n", lastChainTipPrinted->GetHeight()); |
93ff475b MT |
2565 | printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); |
2566 | printf(" hash: %s\ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str()); | |
2567 | } | |
a1d91f89 | 2568 | } |
2569 | break; | |
2570 | } | |
2571 | ||
e771a884 | 2572 | // if PBaaS is no longer available, we can't count on merge mining |
2573 | if (!ConnectedChains.IsVerusPBaaSAvailable()) | |
2574 | { | |
2575 | break; | |
2576 | } | |
f8f61a6d | 2577 | |
2578 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
458bfcab | 2579 | { |
f8f61a6d | 2580 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) |
fa7fdbc6 | 2581 | { |
f8f61a6d | 2582 | fprintf(stderr,"no nodes, attempting reconnect\n"); |
2583 | break; | |
fa7fdbc6 | 2584 | } |
f8f61a6d | 2585 | } |
2586 | ||
a82942e4 | 2587 | // update every few minutes, regardless |
2588 | int64_t elapsed = GetTime() - nStart; | |
f8f61a6d | 2589 | |
a9663647 | 2590 | if ((mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && elapsed > 60) || elapsed > 60 || ConnectedChains.lastSubmissionFailed) |
458bfcab | 2591 | { |
f8f61a6d | 2592 | break; |
458bfcab | 2593 | } |
a1d91f89 | 2594 | |
dc74c06d | 2595 | boost::this_thread::interruption_point(); |
a1d91f89 | 2596 | MilliSleep(500); |
458bfcab | 2597 | } |
ffde1589 | 2598 | break; |
f8f61a6d | 2599 | } |
2600 | else | |
2601 | { | |
2602 | // check NONCEMASK at a time | |
2603 | for (uint64_t i = 0; i < count; i++) | |
42181656 | 2604 | { |
2fd1f0fb | 2605 | // this is the actual mining loop, which enables us to drop out and queue a header anytime we earn a block that is good enough for a |
f8f61a6d | 2606 | // merge mined block, but not our own |
f8f61a6d | 2607 | bool blockFound; |
2608 | arith_uint256 arithHash; | |
2830db29 | 2609 | totalDone = 0; |
f8f61a6d | 2610 | do |
2611 | { | |
2fd1f0fb | 2612 | // pickup/remove any new/deleted headers |
71f97948 | 2613 | if (ConnectedChains.dirty || (pblock->NumPBaaSHeaders() < ConnectedChains.mergeMinedChains.size() + 1)) |
2fd1f0fb | 2614 | { |
598ba98b | 2615 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, verusSolutionV4 ? false : true, &savebits); |
1fa4454d | 2616 | |
2fd1f0fb | 2617 | hashTarget.SetCompact(savebits); |
2618 | uintTarget = ArithToUint256(hashTarget); | |
2619 | } | |
2620 | ||
f8f61a6d | 2621 | // hashesToGo gets updated with actual number run for metrics |
2622 | hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; | |
2830db29 | 2623 | uint64_t start = i * hashesToGo + totalDone; |
f8f61a6d | 2624 | hashesToGo -= totalDone; |
2625 | ||
598ba98b | 2626 | if (verusSolutionV4) |
f8f61a6d | 2627 | { |
2628 | // mine on canonical header for merge mining | |
2629 | CPBaaSPreHeader savedHeader(*pblock); | |
da97aa5c | 2630 | |
f8f61a6d | 2631 | pblock->ClearNonCanonicalData(); |
1e435b54 | 2632 | blockFound = (*mine_verus)(*pblock, ss2, solutionVersion, hashResult, uintTarget, start, &hashesToGo); |
f8f61a6d | 2633 | savedHeader.SetBlockData(*pblock); |
2634 | } | |
2635 | else | |
2636 | { | |
1e435b54 | 2637 | blockFound = (*mine_verus)(*pblock, ss2, solutionVersion, hashResult, uintTarget, start, &hashesToGo); |
f8f61a6d | 2638 | } |
2639 | ||
2640 | arithHash = UintToArith256(hashResult); | |
249e20e4 | 2641 | totalDone += hashesToGo + 1; |
f8f61a6d | 2642 | if (blockFound && IsVerusActive()) |
2643 | { | |
2644 | ConnectedChains.QueueNewBlockHeader(*pblock); | |
2645 | if (arithHash > ourTarget) | |
2646 | { | |
2647 | // all blocks qualified with this hash will be submitted | |
2648 | // until we redo the block, we might as well not try again with anything over this hash | |
2649 | hashTarget = arithHash; | |
2650 | uintTarget = ArithToUint256(hashTarget); | |
2651 | } | |
2652 | } | |
2fd1f0fb | 2653 | } while (blockFound && arithHash > ourTarget); |
c98efb5a | 2654 | |
f8f61a6d | 2655 | if (!blockFound || arithHash > ourTarget) |
4dcb64c0 | 2656 | { |
f8f61a6d | 2657 | // Check for stop or if block needs to be rebuilt |
2658 | boost::this_thread::interruption_point(); | |
ce40cf2e | 2659 | if ( pindexPrev != chainActive.LastTip() ) |
f8f61a6d | 2660 | { |
2661 | if (lastChainTipPrinted != chainActive.LastTip()) | |
2662 | { | |
2663 | lastChainTipPrinted = chainActive.LastTip(); | |
2664 | printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); | |
2665 | } | |
2666 | break; | |
2667 | } | |
a1d91f89 | 2668 | else if ((i + 1) < count) |
f8f61a6d | 2669 | { |
a1d91f89 | 2670 | // if we'll not drop through, update hashcount |
f8f61a6d | 2671 | { |
2672 | LOCK(cs_metrics); | |
2830db29 | 2673 | nHashCount += totalDone; |
2674 | totalDone = 0; | |
f8f61a6d | 2675 | } |
f8f61a6d | 2676 | } |
4dcb64c0 | 2677 | } |
f8f61a6d | 2678 | else |
2679 | { | |
2680 | // Check for stop or if block needs to be rebuilt | |
2681 | boost::this_thread::interruption_point(); | |
4dcb64c0 | 2682 | |
f8f61a6d | 2683 | if (pblock->nSolution.size() != 1344) |
2684 | { | |
2685 | LogPrintf("ERROR: Block solution is not 1344 bytes as it should be"); | |
2686 | break; | |
2687 | } | |
42181656 | 2688 | |
f8f61a6d | 2689 | SetThreadPriority(THREAD_PRIORITY_NORMAL); |
2690 | ||
2691 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); | |
ef70c5b2 | 2692 | |
3363d1c0 | 2693 | #ifdef VERUSHASHDEBUG |
f8f61a6d | 2694 | std::string validateStr = hashResult.GetHex(); |
2695 | std::string hashStr = pblock->GetHash().GetHex(); | |
2696 | uint256 *bhalf1 = (uint256 *)vh2->CurBuffer(); | |
2697 | uint256 *bhalf2 = bhalf1 + 1; | |
3363d1c0 | 2698 | #else |
f8f61a6d | 2699 | std::string hashStr = hashResult.GetHex(); |
3363d1c0 | 2700 | #endif |
3af22e67 | 2701 | |
f8f61a6d | 2702 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
2703 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hashStr, ArithToUint256(ourTarget).GetHex()); | |
2704 | printf("Found block %d \n", Mining_height ); | |
2705 | printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); | |
3363d1c0 | 2706 | #ifdef VERUSHASHDEBUG |
f8f61a6d | 2707 | printf(" hash: %s\n val: %s \ntarget: %s\n\n", hashStr.c_str(), validateStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str()); |
2708 | printf("intermediate %lx\n", intermediate); | |
2709 | printf("Curbuf: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str()); | |
2710 | bhalf1 = (uint256 *)verusclhasher_key.get(); | |
2711 | bhalf2 = bhalf1 + ((vh2->vclh.keyMask + 1) >> 5); | |
2712 | printf(" Key: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str()); | |
3363d1c0 | 2713 | #else |
f8f61a6d | 2714 | printf(" hash: %s\ntarget: %s", hashStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str()); |
3363d1c0 | 2715 | #endif |
f8f61a6d | 2716 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) |
2717 | printf(" - timelocked until block %i\n", unlockTime); | |
2718 | else | |
2719 | printf("\n"); | |
42181656 | 2720 | #ifdef ENABLE_WALLET |
f8f61a6d | 2721 | ProcessBlockFound(pblock, *pwallet, reservekey); |
42181656 | 2722 | #else |
f8f61a6d | 2723 | ProcessBlockFound(pblock); |
42181656 | 2724 | #endif |
f8f61a6d | 2725 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2726 | break; | |
2727 | } | |
42181656 | 2728 | } |
42181656 | 2729 | |
f8f61a6d | 2730 | { |
2731 | LOCK(cs_metrics); | |
2830db29 | 2732 | nHashCount += totalDone; |
f8f61a6d | 2733 | } |
69767347 | 2734 | } |
f8f61a6d | 2735 | |
69767347 | 2736 | |
42181656 | 2737 | // Check for stop or if block needs to be rebuilt |
2738 | boost::this_thread::interruption_point(); | |
2739 | ||
2740 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
2741 | { | |
2742 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2743 | { | |
ef70c5b2 | 2744 | fprintf(stderr,"no nodes, attempting reconnect\n"); |
42181656 | 2745 | break; |
2746 | } | |
2747 | } | |
2748 | ||
dbe656fe | 2749 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
42181656 | 2750 | { |
dbe656fe | 2751 | fprintf(stderr,"timeout, retrying\n"); |
42181656 | 2752 | break; |
2753 | } | |
2754 | ||
37ad6886 | 2755 | if ( pindexPrev != chainActive.LastTip() ) |
42181656 | 2756 | { |
37ad6886 | 2757 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 2758 | { |
37ad6886 | 2759 | lastChainTipPrinted = chainActive.LastTip(); |
90198f71 | 2760 | printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight()); |
dbe656fe | 2761 | } |
42181656 | 2762 | break; |
2763 | } | |
2764 | ||
2830db29 | 2765 | // totalDone now has the number of hashes actually done since starting on one nonce mask worth |
ce40cf2e | 2766 | uint64_t hashesPerNonceMask = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3; |
2830db29 | 2767 | if (!(totalDone < hashesPerNonceMask)) |
ce40cf2e | 2768 | { |
52cf66e1 | 2769 | #ifdef _WIN32 |
ce40cf2e | 2770 | printf("%llu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576); |
52cf66e1 | 2771 | #else |
ce40cf2e | 2772 | printf("%lu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576); |
52cf66e1 | 2773 | #endif |
ce40cf2e | 2774 | } |
4dcb64c0 | 2775 | break; |
8682e17a | 2776 | |
42181656 | 2777 | } |
2778 | } | |
2779 | } | |
2780 | catch (const boost::thread_interrupted&) | |
2781 | { | |
2782 | miningTimer.stop(); | |
5034d1c1 | 2783 | LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
42181656 | 2784 | throw; |
2785 | } | |
2786 | catch (const std::runtime_error &e) | |
2787 | { | |
2788 | miningTimer.stop(); | |
5034d1c1 | 2789 | LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what()); |
42181656 | 2790 | return; |
2791 | } | |
2792 | miningTimer.stop(); | |
2793 | } | |
2794 | ||
d247a5d1 JG |
2795 | void static BitcoinMiner(CWallet *pwallet) |
2796 | { | |
2e500f50 | 2797 | LogPrintf("KomodoMiner started\n"); |
d247a5d1 | 2798 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2e500f50 | 2799 | RenameThread("komodo-miner"); |
8e8b6d70 | 2800 | |
bebe7282 | 2801 | const CChainParams& chainparams = Params(); |
88d014d0 | 2802 | |
8e8b6d70 JG |
2803 | #ifdef ENABLE_WALLET |
2804 | // Each thread has its own key | |
d247a5d1 | 2805 | CReserveKey reservekey(pwallet); |
8e8b6d70 | 2806 | #endif |
e9e70b95 | 2807 | |
8e8b6d70 | 2808 | // Each thread has its own counter |
d247a5d1 | 2809 | unsigned int nExtraNonce = 0; |
e9e70b95 | 2810 | |
88d014d0 | 2811 | unsigned int n = chainparams.GetConsensus().EquihashN(); |
2812 | unsigned int k = chainparams.GetConsensus().EquihashK(); | |
16593898 | 2813 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1; |
99ba67a0 | 2814 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) |
755ead98 | 2815 | { |
2816 | sleep(1); | |
4e624c04 | 2817 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) |
2818 | break; | |
755ead98 | 2819 | } |
32b0978b | 2820 | if ( ASSETCHAINS_SYMBOL[0] == 0 ) |
4b729ec5 | 2821 | komodo_chosennotary(¬aryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime()); |
28a62b60 | 2822 | if ( notaryid != My_notaryid ) |
2823 | My_notaryid = notaryid; | |
755ead98 | 2824 | std::string solver; |
e1e65cef | 2825 | //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 ) |
e9e70b95 | 2826 | solver = "tromp"; |
e1e65cef | 2827 | //else solver = "default"; |
5f0009b2 | 2828 | assert(solver == "tromp" || solver == "default"); |
c7aaab7a | 2829 | LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k); |
9ee43671 | 2830 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
25f7ef8c | 2831 | fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str()); |
5a360a5c JG |
2832 | std::mutex m_cs; |
2833 | bool cancelSolver = false; | |
2834 | boost::signals2::connection c = uiInterface.NotifyBlockTip.connect( | |
e9e70b95 | 2835 | [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable { |
2836 | std::lock_guard<std::mutex> lock{m_cs}; | |
2837 | cancelSolver = true; | |
2838 | } | |
2839 | ); | |
07be8f7e | 2840 | miningTimer.start(); |
e9e70b95 | 2841 | |
0655fac0 | 2842 | try { |
ad84148d | 2843 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
c96df8ec | 2844 | fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str()); |
e725f1cb | 2845 | while (true) |
2846 | { | |
4b729ec5 | 2847 | if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 && |
e725f1cb | 2848 | { |
4b729ec5 | 2849 | //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 ) |
a96fd7b5 | 2850 | // break; |
0655fac0 PK |
2851 | // Busy-wait for the network to come online so we don't waste time mining |
2852 | // on an obsolete chain. In regtest mode we expect to fly solo. | |
07be8f7e | 2853 | miningTimer.stop(); |
bba7c249 GM |
2854 | do { |
2855 | bool fvNodesEmpty; | |
2856 | { | |
373668be | 2857 | //LOCK(cs_vNodes); |
bba7c249 GM |
2858 | fvNodesEmpty = vNodes.empty(); |
2859 | } | |
3ffc29b8 | 2860 | if (!fvNodesEmpty && !IsInitialBlockDownload(chainparams)) |
bba7c249 | 2861 | break; |
6e78d3df | 2862 | MilliSleep(15000); |
ad84148d | 2863 | //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload()); |
e9e70b95 | 2864 | |
bba7c249 | 2865 | } while (true); |
ad84148d | 2866 | //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL); |
07be8f7e | 2867 | miningTimer.start(); |
0655fac0 | 2868 | } |
0655fac0 PK |
2869 | // |
2870 | // Create new block | |
2871 | // | |
2872 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
86131275 | 2873 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
4b729ec5 | 2874 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
4940066c | 2875 | { |
4b729ec5 | 2876 | Mining_height = pindexPrev->GetHeight()+1; |
4940066c | 2877 | Mining_start = (uint32_t)time(NULL); |
2878 | } | |
8e9ef91c | 2879 | if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 ) |
2825c0b5 | 2880 | { |
40304479 | 2881 | //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height); |
5a7fd132 | 2882 | //sleep(3); |
2825c0b5 | 2883 | } |
135fa24e | 2884 | |
8e8b6d70 | 2885 | #ifdef ENABLE_WALLET |
135fa24e | 2886 | // notaries always default to staking |
4b729ec5 | 2887 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0); |
8e8b6d70 | 2888 | #else |
945f015d | 2889 | CBlockTemplate *ptr = CreateNewBlockWithKey(); |
8e8b6d70 | 2890 | #endif |
08d0b73c | 2891 | if ( ptr == 0 ) |
2892 | { | |
d0f7ead0 | 2893 | static uint32_t counter; |
5bb3d0fe | 2894 | if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) |
1b5b89ba | 2895 | fprintf(stderr,"created illegal block, retry\n"); |
8fc79ac9 | 2896 | sleep(1); |
d0f7ead0 | 2897 | continue; |
08d0b73c | 2898 | } |
2a6a442a | 2899 | //fprintf(stderr,"get template\n"); |
08d0b73c | 2900 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
0655fac0 | 2901 | if (!pblocktemplate.get()) |
6c37f7fd | 2902 | { |
8e8b6d70 | 2903 | if (GetArg("-mineraddress", "").empty()) { |
945f015d | 2904 | LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); |
8e8b6d70 JG |
2905 | } else { |
2906 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
945f015d | 2907 | LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n"); |
8e8b6d70 | 2908 | } |
0655fac0 | 2909 | return; |
6c37f7fd | 2910 | } |
0655fac0 | 2911 | CBlock *pblock = &pblocktemplate->block; |
16c7bf6b | 2912 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
2913 | { | |
42181656 | 2914 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) |
16c7bf6b | 2915 | { |
8683bd8d | 2916 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) |
2917 | { | |
2918 | static uint32_t counter; | |
2919 | if ( counter++ < 10 ) | |
2920 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
2921 | sleep(10); | |
2922 | continue; | |
2923 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
2924 | } | |
16c7bf6b | 2925 | } |
0655fac0 | 2926 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); |
2a6a442a | 2927 | //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size()); |
2e500f50 | 2928 | LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); |
0655fac0 PK |
2929 | // |
2930 | // Search | |
2931 | // | |
2ba9de01 | 2932 | uint8_t pubkeys[66][33]; arith_uint256 bnMaxPoSdiff; uint32_t blocktimes[66]; int mids[256],nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime(); |
d5614a76 | 2933 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
404391b5 | 2934 | savebits = pblock->nBits; |
d5614a76 | 2935 | HASHTarget = arith_uint256().SetCompact(savebits); |
f0100e72 | 2936 | roundrobin_delay = ROUNDROBIN_DELAY; |
3e7e3109 | 2937 | if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 ) |
5203fc4b | 2938 | { |
fda5f849 | 2939 | j = 65; |
67df454d | 2940 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 ) |
fb6c7505 | 2941 | { |
4fff8a63 | 2942 | int32_t dispflag = 0; |
ef70c5b2 | 2943 | if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 ) |
4fff8a63 | 2944 | dispflag = 1; |
4b729ec5 | 2945 | komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight()); |
29e60e48 | 2946 | if ( nonzpkeys > 0 ) |
2947 | { | |
ccb71a6e | 2948 | for (i=0; i<33; i++) |
2949 | if( pubkeys[0][i] != 0 ) | |
2950 | break; | |
2951 | if ( i == 33 ) | |
2952 | externalflag = 1; | |
2953 | else externalflag = 0; | |
4d068367 | 2954 | if ( IS_KOMODO_NOTARY != 0 ) |
b176c125 | 2955 | { |
345e545e | 2956 | for (i=1; i<66; i++) |
2957 | if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 ) | |
2958 | break; | |
6494f040 | 2959 | if ( externalflag == 0 && i != 66 && mids[i] >= 0 ) |
2960 | printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]); | |
2c7ad758 | 2961 | for (j=gpucount=0; j<65; j++) |
2962 | { | |
4fff8a63 | 2963 | if ( dispflag != 0 ) |
e4a383e3 | 2964 | { |
2965 | if ( mids[j] >= 0 ) | |
2966 | fprintf(stderr,"%d ",mids[j]); | |
2967 | else fprintf(stderr,"GPU "); | |
2968 | } | |
2c7ad758 | 2969 | if ( mids[j] == -1 ) |
2970 | gpucount++; | |
2971 | } | |
4fff8a63 | 2972 | if ( dispflag != 0 ) |
4b729ec5 | 2973 | fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\n",pindexPrev->GetHeight(),notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL)); |
b176c125 | 2974 | } |
29e60e48 | 2975 | for (j=0; j<65; j++) |
2976 | if ( mids[j] == notaryid ) | |
2977 | break; | |
49b49585 | 2978 | if ( j == 65 ) |
2979 | KOMODO_LASTMINED = 0; | |
965f0f7e | 2980 | } else fprintf(stderr,"no nonz pubkeys\n"); |
49b49585 | 2981 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) ) |
fda5f849 | 2982 | { |
88287857 | 2983 | HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS); |
4b729ec5 | 2984 | fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1); |
fda5f849 | 2985 | } //else fprintf(stderr,"duplicate at j.%d\n",j); |
fb6c7505 | 2986 | } else Mining_start = 0; |
d7d27bb3 | 2987 | } else Mining_start = 0; |
2ba9de01 | 2988 | if ( ASSETCHAINS_STAKED != 0 ) |
e725f1cb | 2989 | { |
ed3d0a05 | 2990 | int32_t percPoS,z; bool fNegative,fOverflow; |
18443f69 | 2991 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
f108acf9 | 2992 | HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); |
f2c1ac06 | 2993 | if ( ASSETCHAINS_STAKED < 100 ) |
2994 | { | |
2995 | for (z=31; z>=0; z--) | |
2996 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); | |
2997 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
2998 | } | |
deba7f20 | 2999 | } |
e725f1cb | 3000 | while (true) |
3001 | { | |
99ba67a0 | 3002 | if ( KOMODO_INSYNC == 0 ) |
3003 | { | |
e9d56b2c | 3004 | fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height); |
3005 | if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN ) | |
a02c45db | 3006 | KOMODO_INSYNC = 1; |
99ba67a0 | 3007 | sleep(3); |
3008 | } | |
7213c0b1 | 3009 | // Hash state |
8c22eb46 | 3010 | KOMODO_CHOSEN_ONE = 0; |
42181656 | 3011 | |
7213c0b1 | 3012 | crypto_generichash_blake2b_state state; |
e9574728 | 3013 | EhInitialiseState(n, k, state); |
7213c0b1 JG |
3014 | // I = the block header minus nonce and solution. |
3015 | CEquihashInput I{*pblock}; | |
3016 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
3017 | ss << I; | |
7213c0b1 JG |
3018 | // H(I||... |
3019 | crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size()); | |
8e165d57 JG |
3020 | // H(I||V||... |
3021 | crypto_generichash_blake2b_state curr_state; | |
3022 | curr_state = state; | |
7a4c01c9 | 3023 | crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size()); |
8e165d57 | 3024 | // (x_1, x_2, ...) = A(I, V, n, k) |
7a4c01c9 | 3025 | LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString()); |
18443f69 | 3026 | arith_uint256 hashTarget; |
6e78d3df | 3027 | if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 ) |
18443f69 | 3028 | hashTarget = HASHTarget_POW; |
3029 | else hashTarget = HASHTarget; | |
5be6abbf | 3030 | std::function<bool(std::vector<unsigned char>)> validBlock = |
8e8b6d70 | 3031 | #ifdef ENABLE_WALLET |
e9e70b95 | 3032 | [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 3033 | #else |
e9e70b95 | 3034 | [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 3035 | #endif |
e9e70b95 | 3036 | (std::vector<unsigned char> soln) { |
c21c6306 | 3037 | int32_t z; arith_uint256 h; CBlock B; |
51eb5273 JG |
3038 | // Write the solution to the hash and compute the result. |
3039 | LogPrint("pow", "- Checking solution against target\n"); | |
8e165d57 | 3040 | pblock->nSolution = soln; |
e7d59bbc | 3041 | solutionTargetChecks.increment(); |
eff2c3a3 | 3042 | B = *pblock; |
3043 | h = UintToArith256(B.GetHash()); | |
eff2c3a3 | 3044 | /*for (z=31; z>=16; z--) |
02c30aac | 3045 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); |
aea2d1aa | 3046 | fprintf(stderr," mined "); |
3047 | for (z=31; z>=16; z--) | |
18443f69 | 3048 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); |
aea2d1aa | 3049 | fprintf(stderr," hashTarget "); |
3050 | for (z=31; z>=16; z--) | |
18443f69 | 3051 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); |
eff2c3a3 | 3052 | fprintf(stderr," POW\n");*/ |
265f4e96 | 3053 | if ( h > hashTarget ) |
40df8d84 | 3054 | { |
6e78d3df | 3055 | //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 ) |
afa90f17 | 3056 | // sleep(1); |
265f4e96 | 3057 | return false; |
40df8d84 | 3058 | } |
41e9c815 | 3059 | if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() ) |
d7d27bb3 | 3060 | { |
45ee62cb | 3061 | //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime())); |
596b05ba | 3062 | while ( GetAdjustedTime() < B.nTime-2 ) |
8e9ef91c | 3063 | { |
eb1ba5a0 | 3064 | sleep(1); |
4b729ec5 | 3065 | if ( chainActive.LastTip()->GetHeight() >= Mining_height ) |
4cc387ec | 3066 | { |
3067 | fprintf(stderr,"new block arrived\n"); | |
3068 | return(false); | |
3069 | } | |
8e9ef91c | 3070 | } |
eb1ba5a0 | 3071 | } |
8e9ef91c | 3072 | if ( ASSETCHAINS_STAKED == 0 ) |
d7d27bb3 | 3073 | { |
4d068367 | 3074 | if ( IS_KOMODO_NOTARY != 0 ) |
8e9ef91c | 3075 | { |
26810a26 | 3076 | int32_t r; |
9703f8a0 | 3077 | if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 ) |
596b05ba | 3078 | MilliSleep((rand() % (r * 1000)) + 1000); |
ef70c5b2 | 3079 | } |
e5430f52 | 3080 | } |
8e9ef91c | 3081 | else |
d7d27bb3 | 3082 | { |
0c35569b | 3083 | while ( B.nTime-57 > GetAdjustedTime() ) |
deba7f20 | 3084 | { |
afa90f17 | 3085 | sleep(1); |
4b729ec5 | 3086 | if ( chainActive.LastTip()->GetHeight() >= Mining_height ) |
afa90f17 | 3087 | return(false); |
68d0354d | 3088 | } |
4d068367 | 3089 | uint256 tmp = B.GetHash(); |
3090 | int32_t z; for (z=31; z>=0; z--) | |
3091 | fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]); | |
01e50e73 | 3092 | fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height); |
d7d27bb3 | 3093 | } |
8fc79ac9 | 3094 | CValidationState state; |
88d014d0 | 3095 | if ( !TestBlockValidity(state, Params(), B, chainActive.LastTip(), true, false)) |
d2d3c766 | 3096 | { |
8fc79ac9 | 3097 | h = UintToArith256(B.GetHash()); |
3098 | for (z=31; z>=0; z--) | |
3099 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); | |
3100 | fprintf(stderr," Invalid block mined, try again\n"); | |
3101 | return(false); | |
d2d3c766 | 3102 | } |
b3183e3e | 3103 | KOMODO_CHOSEN_ONE = 1; |
8e165d57 JG |
3104 | // Found a solution |
3105 | SetThreadPriority(THREAD_PRIORITY_NORMAL); | |
2e500f50 | 3106 | LogPrintf("KomodoMiner:\n"); |
eff2c3a3 | 3107 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex()); |
8e8b6d70 | 3108 | #ifdef ENABLE_WALLET |
eff2c3a3 | 3109 | if (ProcessBlockFound(&B, *pwallet, reservekey)) { |
8e8b6d70 | 3110 | #else |
eff2c3a3 | 3111 | if (ProcessBlockFound(&B)) { |
8e8b6d70 | 3112 | #endif |
e9e70b95 | 3113 | // Ignore chain updates caused by us |
3114 | std::lock_guard<std::mutex> lock{m_cs}; | |
3115 | cancelSolver = false; | |
3116 | } | |
3117 | KOMODO_CHOSEN_ONE = 0; | |
3118 | SetThreadPriority(THREAD_PRIORITY_LOWEST); | |
3119 | // In regression test mode, stop mining after a block is found. | |
3120 | if (chainparams.MineBlocksOnDemand()) { | |
3121 | // Increment here because throwing skips the call below | |
3122 | ehSolverRuns.increment(); | |
3123 | throw boost::thread_interrupted(); | |
3124 | } | |
e9e70b95 | 3125 | return true; |
3126 | }; | |
3127 | std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) { | |
a6a0d913 | 3128 | std::lock_guard<std::mutex> lock{m_cs}; |
e9e70b95 | 3129 | return cancelSolver; |
3130 | }; | |
3131 | ||
3132 | // TODO: factor this out into a function with the same API for each solver. | |
3133 | if (solver == "tromp" ) { //&& notaryid >= 0 ) { | |
3134 | // Create solver and initialize it. | |
3135 | equi eq(1); | |
3136 | eq.setstate(&curr_state); | |
3137 | ||
3138 | // Initialization done, start algo driver. | |
3139 | eq.digit0(0); | |
c7aaab7a | 3140 | eq.xfull = eq.bfull = eq.hfull = 0; |
e9e70b95 | 3141 | eq.showbsizes(0); |
3142 | for (u32 r = 1; r < WK; r++) { | |
3143 | (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0); | |
3144 | eq.xfull = eq.bfull = eq.hfull = 0; | |
3145 | eq.showbsizes(r); | |
c7aaab7a | 3146 | } |
e9e70b95 | 3147 | eq.digitK(0); |
3148 | ehSolverRuns.increment(); | |
3149 | ||
3150 | // Convert solution indices to byte array (decompress) and pass it to validBlock method. | |
3151 | for (size_t s = 0; s < eq.nsols; s++) { | |
3152 | LogPrint("pow", "Checking solution %d\n", s+1); | |
3153 | std::vector<eh_index> index_vector(PROOFSIZE); | |
3154 | for (size_t i = 0; i < PROOFSIZE; i++) { | |
3155 | index_vector[i] = eq.sols[s][i]; | |
3156 | } | |
3157 | std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS); | |
3158 | ||
3159 | if (validBlock(sol_char)) { | |
3160 | // If we find a POW solution, do not try other solutions | |
3161 | // because they become invalid as we created a new block in blockchain. | |
3162 | break; | |
3163 | } | |
3164 | } | |
3165 | } else { | |
3166 | try { | |
3167 | // If we find a valid block, we rebuild | |
3168 | bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); | |
3169 | ehSolverRuns.increment(); | |
3170 | if (found) { | |
997ddd92 | 3171 | int32_t i; uint256 hash = pblock->GetHash(); |
e9e70b95 | 3172 | for (i=0; i<32; i++) |
3173 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); | |
3174 | fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); | |
3175 | FOUND_BLOCK = 1; | |
3176 | KOMODO_MAYBEMINED = Mining_height; | |
3177 | break; | |
3178 | } | |
3179 | } catch (EhSolverCancelledException&) { | |
3180 | LogPrint("pow", "Equihash solver cancelled\n"); | |
3181 | std::lock_guard<std::mutex> lock{m_cs}; | |
3182 | cancelSolver = false; | |
c7aaab7a DH |
3183 | } |
3184 | } | |
e9e70b95 | 3185 | |
3186 | // Check for stop or if block needs to be rebuilt | |
3187 | boost::this_thread::interruption_point(); | |
3188 | // Regtest mode doesn't require peers | |
3189 | if ( FOUND_BLOCK != 0 ) | |
3190 | { | |
3191 | FOUND_BLOCK = 0; | |
3192 | fprintf(stderr,"FOUND_BLOCK!\n"); | |
3193 | //sleep(2000); | |
3194 | } | |
3195 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
3196 | { | |
3197 | if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT ) | |
3198 | { | |
3199 | fprintf(stderr,"no nodes, break\n"); | |
c7aaab7a | 3200 | break; |
a6df7ab5 | 3201 | } |
c7aaab7a | 3202 | } |
997ddd92 | 3203 | if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) |
10694486 | 3204 | { |
e9e70b95 | 3205 | //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
3206 | fprintf(stderr,"0xffff, break\n"); | |
d90cef0b | 3207 | break; |
10694486 | 3208 | } |
e9e70b95 | 3209 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
3210 | { | |
3211 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
3212 | fprintf(stderr,"timeout, break\n"); | |
3213 | break; | |
3214 | } | |
86131275 | 3215 | if ( pindexPrev != chainActive.LastTip() ) |
e9e70b95 | 3216 | { |
3217 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
3218 | fprintf(stderr,"Tip advanced, break\n"); | |
3219 | break; | |
3220 | } | |
3221 | // Update nNonce and nTime | |
3222 | pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); | |
3223 | pblock->nBits = savebits; | |
18dd6a3b | 3224 | /*if ( NOTARY_PUBKEY33[0] == 0 ) |
e9e70b95 | 3225 | { |
f8f740a9 | 3226 | int32_t percPoS; |
df756d24 MT |
3227 | UpdateTime(pblock, consensusParams, pindexPrev); |
3228 | if (consensusParams.fPowAllowMinDifficultyBlocks) | |
23fc88bb | 3229 | { |
3230 | // Changing pblock->nTime can change work required on testnet: | |
3231 | HASHTarget.SetCompact(pblock->nBits); | |
18443f69 | 3232 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
23fc88bb | 3233 | } |
18dd6a3b | 3234 | }*/ |
48265f3c | 3235 | } |
d247a5d1 JG |
3236 | } |
3237 | } | |
e9e70b95 | 3238 | catch (const boost::thread_interrupted&) |
3239 | { | |
3240 | miningTimer.stop(); | |
3241 | c.disconnect(); | |
3242 | LogPrintf("KomodoMiner terminated\n"); | |
3243 | throw; | |
3244 | } | |
3245 | catch (const std::runtime_error &e) | |
3246 | { | |
3247 | miningTimer.stop(); | |
3248 | c.disconnect(); | |
3249 | LogPrintf("KomodoMiner runtime error: %s\n", e.what()); | |
3250 | return; | |
3251 | } | |
07be8f7e | 3252 | miningTimer.stop(); |
5e9b555f | 3253 | c.disconnect(); |
bba7c249 | 3254 | } |
88d014d0 | 3255 | |
3256 | ||
8e8b6d70 | 3257 | #ifdef ENABLE_WALLET |
e9e70b95 | 3258 | void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) |
8e8b6d70 | 3259 | #else |
e9e70b95 | 3260 | void GenerateBitcoins(bool fGenerate, int nThreads) |
8e8b6d70 | 3261 | #endif |
d247a5d1 | 3262 | { |
f8f61a6d | 3263 | if (!AreParamsInitialized()) |
3264 | { | |
3265 | return; | |
3266 | } | |
3267 | ||
10214558 | 3268 | // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at |
3269 | // initialization, and this is the first time we can get it. store the Sapling address here | |
3270 | extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher; | |
3271 | extern std::string VERUS_CHEATCATCHER; | |
3272 | libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER); | |
3273 | if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr)) | |
3274 | { | |
99c94fc3 | 3275 | try |
3276 | { | |
3277 | cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr); | |
3278 | } | |
3279 | catch (...) | |
3280 | { | |
3281 | } | |
10214558 | 3282 | } |
bd6639fd | 3283 | |
b20c38cc | 3284 | VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0); |
bd6639fd | 3285 | |
89cd7b59 | 3286 | if (fGenerate == true || VERUS_MINTBLOCKS) |
10214558 | 3287 | { |
89cd7b59 MT |
3288 | mapArgs["-gen"] = "1"; |
3289 | ||
3290 | if (VERUS_CHEATCATCHER.size() > 0) | |
99c94fc3 | 3291 | { |
89cd7b59 MT |
3292 | if (cheatCatcher == boost::none) |
3293 | { | |
3294 | LogPrintf("ERROR: -cheatcatcher parameter is invalid Sapling payment address\n"); | |
3295 | fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n"); | |
3296 | } | |
3297 | else | |
3298 | { | |
3299 | LogPrintf("StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str()); | |
3300 | fprintf(stderr, "StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str()); | |
3301 | } | |
99c94fc3 | 3302 | } |
3303 | } | |
10214558 | 3304 | |
e9e70b95 | 3305 | static boost::thread_group* minerThreads = NULL; |
28424e9f | 3306 | |
e9e70b95 | 3307 | if (nThreads < 0) |
3308 | nThreads = GetNumCores(); | |
3309 | ||
3310 | if (minerThreads != NULL) | |
3311 | { | |
3312 | minerThreads->interrupt_all(); | |
88d014d0 | 3313 | minerThreads->join_all(); |
e9e70b95 | 3314 | delete minerThreads; |
3315 | minerThreads = NULL; | |
3316 | } | |
135fa24e | 3317 | |
afaeb54b | 3318 | //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate); |
5034d1c1 | 3319 | if ( nThreads == 0 && ASSETCHAINS_STAKED ) |
3a446d9f | 3320 | nThreads = 1; |
5034d1c1 | 3321 | |
28424e9f | 3322 | if (!fGenerate) |
e9e70b95 | 3323 | return; |
135fa24e | 3324 | |
e9e70b95 | 3325 | minerThreads = new boost::thread_group(); |
135fa24e | 3326 | |
85c51d62 | 3327 | // add the PBaaS thread when mining or staking |
3328 | minerThreads->create_thread(boost::bind(&CConnectedChains::SubmissionThreadStub)); | |
3329 | ||
135fa24e | 3330 | #ifdef ENABLE_WALLET |
b20c38cc | 3331 | if (VERUS_MINTBLOCKS && pwallet != NULL) |
135fa24e | 3332 | { |
3333 | minerThreads->create_thread(boost::bind(&VerusStaker, pwallet)); | |
3334 | } | |
3335 | #endif | |
3336 | ||
e9e70b95 | 3337 | for (int i = 0; i < nThreads; i++) { |
135fa24e | 3338 | |
8e8b6d70 | 3339 | #ifdef ENABLE_WALLET |
135fa24e | 3340 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
3341 | minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); | |
3342 | else | |
3343 | minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet)); | |
8e8b6d70 | 3344 | #else |
135fa24e | 3345 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
3346 | minerThreads->create_thread(&BitcoinMiner); | |
3347 | else | |
3348 | minerThreads->create_thread(&BitcoinMiner_noeq); | |
8e8b6d70 | 3349 | #endif |
e9e70b95 | 3350 | } |
8e8b6d70 | 3351 | } |
e9e70b95 | 3352 | |
2cc0a252 | 3353 | #endif // ENABLE_MINING |