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