//base on the last 50 blocks int GetElementForBurn(CBlockIndex* pindex) { if (NULL == pindex) { return INIT_FUEL_RATES; } int nBlock = SysCfg().GetArg("-blocksizeforburn", DEFAULT_BURN_BLOCK_SIZE); if (nBlock * 2 >= pindex->nHeight - 1) { return INIT_FUEL_RATES; } else { int64_t nTotalStep(0); int64_t nAverateStep(0); CBlockIndex * pTemp = pindex; for (int ii = 0; ii < nBlock; ii++) { nTotalStep += pTemp->nFuel / pTemp->nFuelRate * 100; pTemp = pTemp->pprev; } nAverateStep = nTotalStep / nBlock; int newFuelRate(0); if (nAverateStep < MAX_BLOCK_RUN_STEP * 0.75) { newFuelRate = pindex->nFuelRate * 0.9; } else if (nAverateStep > MAX_BLOCK_RUN_STEP * 0.85) { newFuelRate = pindex->nFuelRate * 1.1; } else { newFuelRate = pindex->nFuelRate; } if (newFuelRate < MIN_FUEL_RATES) newFuelRate = MIN_FUEL_RATES; LogPrint("fuel", "preFuelRate=%d fuelRate=%d, nHeight=%d\n", pindex->nFuelRate, newFuelRate, pindex->nHeight); return newFuelRate; } }
int main(int argc, char* argv[]) { std::tuple<bool, boost::thread*> ret = RunSharkfund(argc,argv); boost::thread* detectShutdownThread = std::get<1>(ret); bool fRet = std::get<0>(ret); if (detectShutdownThread) { detectShutdownThread->join(); delete detectShutdownThread; detectShutdownThread = NULL; } Shutdown(); #ifndef WIN32 fDaemon = SysCfg().GetBoolArg("-daemon", false); #endif if (fRet && fDaemon) return 0; return (fRet ? 0 : 1); }
bool AppInit(int argc, char* argv[],boost::thread_group &threadGroup) { bool fRet = false; try { CBaseParams::IntialParams(argc, argv); SysCfg().InitalConfig(); PrintTestNotSetPara(); if (SysCfg().IsArgCount("-?") || SysCfg().IsArgCount("--help")) { // First part of help message is specific to Dacrsd / RPC client std::string strUsage = _("Bitcoin Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " Dacrsd [options] " + _("Start Bitcoin Core Daemon") + "\n" + _("Usage (deprecated, use Dacrs-cli):") + "\n" + " Dacrsd [options] <command> [params] " + _("Send command to Bitcoin Core") + "\n" + " Dacrsd [options] help " + _("List commands") + "\n" + " Dacrsd [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessage(HMM_BITCOIND); strUsage += "\n" + HelpMessageCli(false); fprintf(stdout, "%s", strUsage.c_str()); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "Dacrs:")) fCommandLine = true; if (fCommandLine) { int ret = CommandLineRPC(argc, argv); exit(ret); } SysCfg().SoftSetBoolArg("-server", true); fRet = AppInit2(threadGroup); } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } return fRet; }
bool PrintTestNotSetPara() { bool flag = false; if(1 == SysCfg().GetArg("-listen",flag)) { if (SysCfg().GetDefaultPort() == SysCfg().GetArg("-port", SysCfg().GetDefaultPort())) { cout << "Waring if config file seted the listen param must be true, and port can't be default port" << endl; MilliSleep(500); exit(0); } } string str(""); string strconnect = SysCfg().GetArg("-connect",str); if (str != strconnect) { cout<<"Waring the test of the config file the connect param must be false"<<endl; MilliSleep(500); exit(0); } if(SysCfg().GetArg("-iscutmine",flag)) { cout<<"Waring the test of config file the iscutmine param must be false"<<endl; MilliSleep(500); exit(0); } if(!SysCfg().GetArg("-isdbtraversal",flag)) { cout<<"Waring the test of config file the isdbtraversal param must be true"<<endl; MilliSleep(500); exit(0); } if(!SysCfg().GetArg("-regtest",flag)) { cout<<"Waring the test of config file the regtest param must be 1"<<endl; MilliSleep(500); exit(0); } if (filesystem::exists( GetDataDir() / "blocks")) { cout<<"Waring the test of must del " <<(GetDataDir() / "blocks").string() <<endl; MilliSleep(500); exit(0); } // boost::filesystem::remove_all(p); return true; }
uint256 GetAdjustHash(const uint256 TargetHash, const uint64_t nPos, const int nCurHeight) { uint64_t posacc = nPos/COIN; posacc /= SysCfg().GetIntervalPos(); posacc = max(posacc, (uint64_t) 1); arith_uint256 adjusthash = UintToArith256(TargetHash); //adjust nbits arith_uint256 minhash = SysCfg().ProofOfWorkLimit(); while (posacc) { adjusthash = adjusthash << 1; posacc = posacc >> 1; if (adjusthash > minhash) { adjusthash = minhash; break; } } return std::move(ArithToUint256(adjusthash)); }
bool static MiningBlock(CBlock *pblock,CWallet *pwallet,CBlockIndex* pindexPrev,unsigned int nTransactionsUpdatedLast,CAccountViewCache &view, CTransactionDBCache &txCache, CScriptDBViewCache &scriptCache){ int64_t nStart = GetTime(); unsigned int lasttime = 0xFFFFFFFF; while (true) { // Check for stop or if block needs to be rebuilt boost::this_thread::interruption_point(); if (vNodes.empty() && SysCfg().NetworkID() != CBaseParams::REGTEST) return false; if (pindexPrev != chainActive.Tip()) return false; //获取时间 同时等待下次时间到 auto GetNextTimeAndSleep = [&]() { while(max(pindexPrev->GetMedianTimePast() + 1, GetAdjustedTime()) == lasttime) { ::MilliSleep(800); } return (lasttime = max(pindexPrev->GetMedianTimePast() + 1, GetAdjustedTime())); }; GetNextTimeAndSleep(); // max(pindexPrev->GetMedianTimePast() + 1, GetAdjustedTime()); UpdateTime(*pblock, pindexPrev); if (pindexPrev != chainActive.Tip()) return false; set<CKeyID> setCreateKey; setCreateKey.clear(); int64_t lasttime = GetTimeMillis(); bool increatedfalg =CreatePosTx(pindexPrev, pblock, setCreateKey,view,txCache,scriptCache); LogPrint("MINER","CreatePosTx used time :%d ms\n", GetTimeMillis() - lasttime); if (increatedfalg == true) { SetThreadPriority(THREAD_PRIORITY_NORMAL); { int64_t lasttime1 = GetTimeMillis(); CheckWork(pblock, *pwallet); LogPrint("MINER","CheckWork used time :%d ms\n", GetTimeMillis() - lasttime1); } SetThreadPriority(THREAD_PRIORITY_LOWEST); return true; } if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast || GetTime() - nStart > 60) return false; } return false; }
int main() { SysCfg(); ConfigSystemTLC5940(); DCInputCycle(); while(1) { GSInputCycle(); __bis_SR_register(GIE + LPM0_bits); if (dataGS[cnt]==0x00) dataGS[cnt++]=0xff; else dataGS[cnt++]=0x00; if (cnt==16*TLC5940_N) cnt=0; fDataGSUpd=GS_DATA_UPD_READY; } return 0; }
bool CSharkfundAddress::GetKeyID(CKeyID &keyID) const { uint160 id; if (vchVersion == SysCfg().Base58Prefix(CBaseParams::PUBKEY_ADDRESS) && vchData.size() == 20) { memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } vector<unsigned char> vid; vid.push_back(CBaseParams::ACC_ADDRESS); if (vchData.size() == 26 && vchVersion == vid) { memcpy(keyID.begin(), &vchData[0], 20); return true; } return false; }
bool CSharkfundAddress::IsValid() const { bool bvalid = false; { bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == SysCfg().Base58Prefix(CBaseParams::PUBKEY_ADDRESS); bvalid = fCorrectSize && fKnownVersion; } if (!bvalid) { vector<unsigned char> vid; vid.push_back(CBaseParams::ACC_ADDRESS); if (vchData.size() == 26 && vchVersion == vid) { bvalid = true; } } return bvalid; }
uint256 CreateBlockWithAppointedAddr(CKeyID const &keyID) { if (SysCfg().NetworkID() == CBaseParams::REGTEST) { // unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrev = chainActive.Tip(); CAccountViewCache accview(*pAccountViewTip, true); CTransactionDBCache txCache(*pTxCacheTip, true); CScriptDBViewCache ScriptDbTemp(*pScriptDBTip, true); shared_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(accview,txCache,ScriptDbTemp)); if (!pblocktemplate.get()) return uint256(); CBlock *pblock = &pblocktemplate.get()->block; // int nBlockSize = pblock->GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); pblock->GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); // int64_t nStart = GetTime(); while (true) { pblock->SetTime(max(pindexPrev->GetMedianTimePast() + 1, GetAdjustedTime())); set<CKeyID> setCreateKey; setCreateKey.clear(); setCreateKey.insert(keyID); if (CreatePosTx(pindexPrev, pblock,setCreateKey,accview,txCache,ScriptDbTemp)) { CheckWork(pblock, *pwalletMain); // int nBlockSize = pblock->GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); } if(setCreateKey.empty()) { LogPrint("postx", "%s is not exist in the wallet\r\n",keyID.ToAddress()); break; } ::MilliSleep(1); if (pindexPrev != chainActive.Tip()) { return chainActive.Tip()->GetBlockHash() ; } } } return uint256(); }
CTxDestination CSharkfundAddress::Get() const { if (!IsValid()) return CNoDestination(); if (vchData.size() == 20) { uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == SysCfg().Base58Prefix(CBaseParams::PUBKEY_ADDRESS)) return CKeyID(id); // else if (vchVersion == Params().Base58Prefix(CBaseParams::SCRIPT_ADDRESS)) // return CScriptID(id); else return CNoDestination(); } else { // assert(0); return CNoDestination(); } }
Value SysTestBase::CreateRegAppTx(const string& strAddress, const string& strScript, bool bRigsterScript, int nFee, int nHeight) { string filepath = SysCfg().GetDefaultTestDataPath() + strScript; if (!boost::filesystem::exists(filepath)) { BOOST_CHECK_MESSAGE(0, filepath + " not exist"); return false; } string strFee = strprintf("%d",nFee); string strHeight = strprintf("%d",nHeight); const char *argv[] = { "rpctest", "registerapptx", (char*) strAddress.c_str(), (char*) filepath.c_str(), (char*) strFee.c_str(),(char*) strHeight.c_str(),"this is description"}; int argc = sizeof(argv) / sizeof(char*); Value value; if (CommandLineRPC_GetValue(argc, argv, value)) { LogPrint("test_miners", "RegScriptTx:%s\r\n", write_string(value, true)); return value; } return value; }
void CSharkfundSecret::SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(SysCfg().Base58Prefix(CBaseParams::SECRET_KEY), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); }
bool CSharkfundAddress::IsScript() const { return IsValid() && vchVersion == SysCfg().Base58Prefix(CBaseParams::SCRIPT_ADDRESS); }
bool CSharkfundSecret::IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); bool fCorrectVersion = vchVersion == SysCfg().Base58Prefix(CBaseParams::SECRET_KEY); return fExpectedFormat && fCorrectVersion; }
void static HonghuoMiner(CWallet *pwallet,int targetConter) { LogPrint("INFO","Miner started\n"); SetThreadPriority(THREAD_PRIORITY_LOWEST); RenameThread("Honghuo-miner"); auto CheckIsHaveMinerKey = [&]() { LOCK2(cs_main, pwalletMain->cs_wallet); set<CKeyID> setMineKey; setMineKey.clear(); pwalletMain->GetKeys(setMineKey, true); return !setMineKey.empty(); }; if (!CheckIsHaveMinerKey()) { LogPrint("INFO", "HonghuoMiner terminated\n"); ERRORMSG("ERROR:%s ", "no key for minering\n"); return ; } auto getcurhigh = [&]() { LOCK(cs_main); return chainActive.Height(); }; targetConter = targetConter+getcurhigh(); try { SetMinerStatus(true); while (true) { if (SysCfg().NetworkID() != CBaseParams::REGTEST) { // Busy-wait for the network to come online so we don't waste time mining // on an obsolete chain. In regtest mode we expect to fly solo. while (vNodes.empty() || (chainActive.Tip() && chainActive.Tip()->nHeight>1 && GetAdjustedTime()-chainActive.Tip()->nTime > 60*60)) MilliSleep(1000); } // // Create new block // unsigned int LastTrsa = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrev = chainActive.Tip(); CAccountViewCache accview(*pAccountViewTip, true); CTransactionDBCache txCache(*pTxCacheTip, true); CScriptDBViewCache ScriptDbTemp(*pScriptDBTip, true); int64_t lasttime1 = GetTimeMillis(); shared_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(accview, txCache, ScriptDbTemp)); if (!pblocktemplate.get()){ throw runtime_error("Create new block fail."); } LogPrint("MINER", "CreateNewBlock tx count:%d used time :%d ms\n", pblocktemplate.get()->block.vptx.size(), GetTimeMillis() - lasttime1); CBlock *pblock = &pblocktemplate.get()->block; MiningBlock(pblock, pwallet, pindexPrev, LastTrsa, accview, txCache, ScriptDbTemp); if (SysCfg().NetworkID() != CBaseParams::MAIN) if(targetConter <= getcurhigh()) { throw boost::thread_interrupted(); } } } catch (...) { LogPrint("INFO","HonghuoMiner terminated\n"); SetMinerStatus(false); throw; } }
CBlockTemplate* CreateNewBlock(CAccountViewCache &view, CTransactionDBCache &txCache, CScriptDBViewCache &scriptCache){ // // Create new block auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); if (!pblocktemplate.get()) return NULL; CBlock *pblock = &pblocktemplate->block; // pointer for convenience // Create coinbase tx CRewardTransaction rtx; // Add our coinbase tx as first transaction pblock->vptx.push_back(make_shared<CRewardTransaction>(rtx)); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOps.push_back(-1); // updated at end // Largest block you're willing to create: unsigned int nBlockMaxSize = SysCfg().GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: nBlockMaxSize = max((unsigned int) 1000, min((unsigned int) (MAX_BLOCK_SIZE - 1000), nBlockMaxSize)); // How much of the block should be dedicated to high-priority transactions, // included regardless of the fees they pay unsigned int nBlockPrioritySize = SysCfg().GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); nBlockPrioritySize = min(nBlockMaxSize, nBlockPrioritySize); // Minimum block size you want to create; block will be filled with free transactions // until there are no more or the block reaches this size: unsigned int nBlockMinSize = SysCfg().GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); nBlockMinSize = min(nBlockMaxSize, nBlockMinSize); // Collect memory pool transactions into the block int64_t nFees = 0; { LOCK2(cs_main, mempool.cs); CBlockIndex* pIndexPrev = chainActive.Tip(); pblock->SetFuelRate(GetElementForBurn(pIndexPrev)); // This vector will be sorted into a priority queue: vector<TxPriority> vecPriority; GetPriorityTx(vecPriority, pblock->GetFuelRate()); // Collect transactions into block uint64_t nBlockSize = ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION); uint64_t nBlockTx(0); bool fSortedByFee(true); uint64_t nTotalRunStep(0); int64_t nTotalFuel(0); TxPriorityCompare comparer(fSortedByFee); make_heap(vecPriority.begin(), vecPriority.end(), comparer); while (!vecPriority.empty()) { // Take highest priority transaction off the priority queue: double dPriority = vecPriority.front().get<0>(); double dFeePerKb = vecPriority.front().get<1>(); shared_ptr<CBaseTransaction> stx = vecPriority.front().get<2>(); CBaseTransaction *pBaseTx = stx.get(); //const CTransaction& tx = *(vecPriority.front().get<2>()); pop_heap(vecPriority.begin(), vecPriority.end(), comparer); vecPriority.pop_back(); // Size limits unsigned int nTxSize = ::GetSerializeSize(*pBaseTx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= nBlockMaxSize) continue; // Skip free transactions if we're past the minimum block size: if (fSortedByFee && (dFeePerKb < CTransaction::nMinRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) continue; // Prioritize by fee once past the priority size or we run out of high-priority // transactions: if (!fSortedByFee && ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority))) { fSortedByFee = true; comparer = TxPriorityCompare(fSortedByFee); make_heap(vecPriority.begin(), vecPriority.end(), comparer); } if(uint256() != std::move(txCache.IsContainTx(std::move(pBaseTx->GetHash())))) { LogPrint("INFO","CreatePosTx duplicate tx\n"); continue; } CTxUndo txundo; CValidationState state; if(pBaseTx->IsCoinBase()){ ERRORMSG("TX type is coin base tx error......"); // assert(0); //never come here } if (CONTRACT_TX == pBaseTx->nTxType) { LogPrint("vm", "tx hash=%s CreateNewBlock run contract\n", pBaseTx->GetHash().GetHex()); } CAccountViewCache viewTemp(view, true); CScriptDBViewCache scriptCacheTemp(scriptCache, true); pBaseTx->nFuelRate = pblock->GetFuelRate(); if (!pBaseTx->ExecuteTx(nBlockTx + 1, viewTemp, state, txundo, pIndexPrev->nHeight + 1, txCache, scriptCacheTemp)) { continue; } // Run step limits if(nTotalRunStep + pBaseTx->nRunStep >= MAX_BLOCK_RUN_STEP) continue; assert(viewTemp.Flush()); assert(scriptCacheTemp.Flush()); nFees += pBaseTx->GetFee(); nBlockSize += stx->GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); nTotalRunStep += pBaseTx->nRunStep; nTotalFuel += pBaseTx->GetFuel(pblock->GetFuelRate()); nBlockTx++; pblock->vptx.push_back(stx); LogPrint("fuel", "miner total fuel:%d, tx fuel:%d runStep:%d fuelRate:%d txhash:%s\n",nTotalFuel, pBaseTx->GetFuel(pblock->GetFuelRate()), pBaseTx->nRunStep, pblock->GetFuelRate(), pBaseTx->GetHash().GetHex()); } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; LogPrint("INFO","CreateNewBlock(): total size %u\n", nBlockSize); assert(nFees-nTotalFuel >= 0); ((CRewardTransaction*) pblock->vptx[0].get())->rewardValue = nFees - nTotalFuel + GetBlockSubsidy(pIndexPrev->nHeight + 1); // Fill in header pblock->SetHashPrevBlock(pIndexPrev->GetBlockHash()); UpdateTime(*pblock, pIndexPrev); pblock->SetBits(GetNextWorkRequired(pIndexPrev, pblock)); pblock->SetNonce(0); pblock->SetHeight(pIndexPrev->nHeight + 1); pblock->SetFuel(nTotalFuel); } return pblocktemplate.release(); }
bool VerifyPosTx(CAccountViewCache &accView, const CBlock *pBlock, CTransactionDBCache &txCache, CScriptDBViewCache &scriptCache, bool bNeedRunTx) { // LogPrint("INFO", "VerifyPoxTx begin\n"); uint64_t maxNonce = SysCfg().GetBlockMaxNonce(); //cacul times if (pBlock->GetNonce() > maxNonce) { return ERRORMSG("Nonce is larger than maxNonce"); } if (pBlock->GetHashMerkleRoot() != pBlock->BuildMerkleTree()) { return ERRORMSG("hashMerkleRoot is error"); } CAccountViewCache view(accView, true); CScriptDBViewCache scriptDBView(scriptCache, true); CAccount account; CRewardTransaction *prtx = (CRewardTransaction *) pBlock->vptx[0].get(); if (view.GetAccount(prtx->account, account)) { if(!CheckSignScript(pBlock->SignatureHash(), pBlock->GetSignature(), account.PublicKey)) { if (!CheckSignScript(pBlock->SignatureHash(), pBlock->GetSignature(), account.MinerPKey)) { // LogPrint("ERROR", "block verify fail\r\n"); // LogPrint("ERROR", "block hash:%s\n", pBlock->GetHash().GetHex()); // LogPrint("ERROR", "signature block:%s\n", HexStr(pBlock->vSignature.begin(), pBlock->vSignature.end())); return ERRORMSG("Verify miner publickey signature error"); } } } else { return ERRORMSG("AccountView have no the accountid"); } //校验reward_tx 版本是否正确 if (prtx->nVersion != nTxVersion2) { return ERRORMSG("CTransaction CheckTransction,tx version is not equal current version, (tx version %d: vs current %d)", prtx->nVersion, nTxVersion2); } if (bNeedRunTx) { int64_t nTotalFuel(0); uint64_t nTotalRunStep(0); for (unsigned int i = 1; i < pBlock->vptx.size(); i++) { shared_ptr<CBaseTransaction> pBaseTx = pBlock->vptx[i]; if (uint256() != txCache.IsContainTx(pBaseTx->GetHash())) { return ERRORMSG("VerifyPosTx duplicate tx hash:%s", pBaseTx->GetHash().GetHex()); } CTxUndo txundo; CValidationState state; if (CONTRACT_TX == pBaseTx->nTxType) { LogPrint("vm", "tx hash=%s VerifyPosTx run contract\n", pBaseTx->GetHash().GetHex()); } pBaseTx->nFuelRate = pBlock->GetFuelRate(); if (!pBaseTx->ExecuteTx(i, view, state, txundo, pBlock->GetHeight(), txCache, scriptDBView)) { return ERRORMSG("transaction UpdateAccount account error"); } nTotalRunStep += pBaseTx->nRunStep; if(nTotalRunStep > MAX_BLOCK_RUN_STEP) { return ERRORMSG("block total run steps exceed max run step"); } nTotalFuel += pBaseTx->GetFuel(pBlock->GetFuelRate()); LogPrint("fuel", "VerifyPosTx total fuel:%d, tx fuel:%d runStep:%d fuelRate:%d txhash:%s \n",nTotalFuel, pBaseTx->GetFuel(pBlock->GetFuelRate()), pBaseTx->nRunStep, pBlock->GetFuelRate(), pBaseTx->GetHash().GetHex()); } if(nTotalFuel != pBlock->GetFuel()) { return ERRORMSG("fuel value at block header calculate error"); } if (view.GetAccount(prtx->account, account)) { //available acc // cout << "check block hash:" << pBlock->SignatureHash().GetHex() << endl; // cout << "check signature:" << HexStr(pBlock->vSignature) << endl; // cout <<"account miner"<< account.ToString()<< endl; if(account.GetAccountPos(pBlock->GetHeight()) <= 0 || !account.IsMiner(pBlock->GetHeight())) return ERRORMSG("coindays of account dismatch, can't be miner, account info:%s", account.ToString()); } else { LogPrint("ERROR", "AccountView have no the accountid\r\n"); return false; } } uint256 prevblockhash = pBlock->GetHashPrevBlock(); const uint256 targetHash = CBigNum().SetCompact(pBlock->GetBits()).getuint256(); //target hash difficult uint64_t posacc = account.GetAccountPos(pBlock->GetHeight()); /* arith_uint256 bnNew; bnNew.SetCompact(pBlock->nBits); string timeFormat = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pBlock->nTime); LogPrint("coinday","height:%.10d, account:%-10s, coinday:%.10ld, difficulty=%.8lf, time=%-20s, interval=%d\n", pBlock->nHeight, account.regID.ToString(), posacc/COIN/SysCfg().GetIntervalPos(), CaculateDifficulty(bnNew.GetCompact()), timeFormat, pBlock->nTime-chainActive[pBlock->nHeight-1]->nTime); */ if (posacc == 0) { return ERRORMSG("Account have no pos"); } uint256 adjusthash = GetAdjustHash(targetHash, posacc, pBlock->GetHeight()-1); //adjust nbits //need compute this block proofofwork struct PosTxInfo postxinfo; postxinfo.nVersion = pBlock->GetVersion(); postxinfo.hashPrevBlock = prevblockhash; postxinfo.hashMerkleRoot = account.GetHash(); postxinfo.nValues = account.llValues; postxinfo.nTime = pBlock->GetTime(); postxinfo.nNonce = pBlock->GetNonce(); postxinfo.nHeight = pBlock->GetHeight(); postxinfo.nFuel = pBlock->GetFuel(); postxinfo.nFuelRate = pBlock->GetFuelRate(); uint256 curhash = postxinfo.GetHash(); LogPrint("miner", "Miner account info:%s\n", account.ToString()); LogPrint("miner", "VerifyPosTx block hash:%s, postxinfo:%s\n", pBlock->GetHash().GetHex(), postxinfo.ToString().c_str()); if(pBlock->GetHashPos() != curhash) { return ERRORMSG("PosHash Error: \n" " computer PoS hash:%s \n" " block PoS hash:%s\n", curhash.GetHex(), pBlock->GetHashPos().GetHex()); } if (UintToArith256(curhash) > UintToArith256(adjusthash)) { return ERRORMSG("Account ProofOfWorkLimit error: \n" " pos hash:%s \n" "adjust hash:%s\r\n", curhash.GetHex(), adjusthash.GetHex()); } return true; }
bool CreatePosTx(const CBlockIndex *pPrevIndex, CBlock *pBlock, set<CKeyID>&setCreateKey, CAccountViewCache &view, CTransactionDBCache &txCache, CScriptDBViewCache &scriptCache) { set<CKeyID> setKeyID; setKeyID.clear(); set<CAccount, CAccountComparator> setAcctInfo; { LOCK2(cs_main, pwalletMain->cs_wallet); if((unsigned int)(chainActive.Tip()->nHeight + 1) != pBlock->GetHeight()) return false; pwalletMain->GetKeys(setKeyID, true); // first:get keyID from pwalletMain if (setKeyID.empty()) { return ERRORMSG("CreatePosTx setKeyID empty"); } LogPrint("INFO","CreatePosTx block time:%d\n", pBlock->GetTime()); for(const auto &keyid:setKeyID) { //second:get account by keyID //find CAccount info by keyid if(setCreateKey.size()) { bool bfind = false; for(auto &item: setCreateKey){ if(item == keyid){ bfind = true; break; } } if (!bfind) continue; } CUserID userId = keyid; CAccount acctInfo; if (view.GetAccount(userId, acctInfo)) { // check acctInfo is or not allowed to mining , //available // LogPrint("miner", "account info:regid=%s keyid=%s ncoinday=%lld isMiner=%d\n", acctInfo.regID.ToString(), // acctInfo.keyID.ToString(), acctInfo.GetAccountPos(pBlock->nHeight), acctInfo.IsMiner(pBlock->nHeight)); if (acctInfo.IsRegister() && acctInfo.GetAccountPos(pBlock->GetHeight()) > 0 && acctInfo.IsMiner(pBlock->GetHeight())) { setAcctInfo.insert(std::move(acctInfo)); // LogPrint("miner", "miner account info:%s\n", acctInfo.ToString()); } } } } if (setAcctInfo.empty()) { setCreateKey.clear(); LogPrint("INFO", "CreatePosTx setSecureAcc empty"); return false; } uint64_t maxNonce = SysCfg().GetBlockMaxNonce(); //cacul times uint256 prevblockhash = pPrevIndex->GetBlockHash(); const uint256 targetHash = CBigNum().SetCompact(pBlock->GetBits()).getuint256(); //target hash difficult set<CAccount, CAccountComparator>::iterator iterAcct = setAcctInfo.begin(); for (;iterAcct!=setAcctInfo.end();++iterAcct) { //third: 根据不同的账户 ,去计算挖矿 CAccount &item = const_cast<CAccount&>(*iterAcct); uint64_t posacc = item.GetAccountPos(pBlock->GetHeight()); if (0 == posacc) { //have no pos LogPrint("ERROR", "CreatePosTx posacc zero\n"); continue; } LogPrint("miner", "miner account:%s\n", item.ToString()); // LogPrint("INFO", "target hash:%s\n", targetHash.ToString()); // LogPrint("INFO", "posacc:%d\n", posacc); uint256 adjusthash = GetAdjustHash(targetHash, posacc, pBlock->GetHeight()-1); //adjust nbits // LogPrint("INFO", "adjusthash:%s\n", adjusthash.ToString()); //need compute this block proofofwork struct PosTxInfo postxinfo; postxinfo.nVersion = pBlock->GetVersion(); postxinfo.hashPrevBlock = prevblockhash; postxinfo.hashMerkleRoot = item.GetHash(); postxinfo.nValues = item.llValues; postxinfo.nHeight = pBlock->GetHeight(); postxinfo.nFuel = pBlock->GetFuel(); postxinfo.nFuelRate = pBlock->GetFuelRate(); postxinfo.nTime = pBlock->GetTime(); //max(pPrevIndex->GetMedianTimePast() + 1, GetAdjustedTime()); unsigned int nNonce = 0; for (; nNonce < maxNonce; ++nNonce) { //循环的 更改随机数,计算curhash看是否满足 postxinfo.nNonce = nNonce; pBlock->SetNonce(nNonce); uint256 curhash = postxinfo.GetHash(); if (UintToArith256(curhash) <= UintToArith256(adjusthash)) { CRegID regid; if (pAccountViewTip->GetRegId(item.keyID, regid)) { CRewardTransaction *prtx = (CRewardTransaction *) pBlock->vptx[0].get(); prtx->account = regid; //存矿工的 账户ID prtx->nHeight = pPrevIndex->nHeight+1; pBlock->SetHashMerkleRoot(pBlock->BuildMerkleTree()); pBlock->SetHashPos(curhash); LogPrint("INFO", "find pos tx hash succeed: \n" " pos hash:%s \n" "adjust hash:%s \r\n", curhash.GetHex(), adjusthash.GetHex()); vector<unsigned char> vSign; if (pwalletMain->Sign(item.keyID, pBlock->SignatureHash(), vSign, item.MinerPKey.IsValid())) { LogPrint("INFO", "Create new block hash:%s\n", pBlock->GetHash().GetHex()); LogPrint("miner", "Miner account info:%s\n", item.ToString()); LogPrint("miner", "CreatePosTx block hash:%s, postxinfo:%s\n",pBlock->GetHash().GetHex(), postxinfo.ToString().c_str()); pBlock->SetSignature(vSign); return true; } else { LogPrint("ERROR", "sign fail\r\n"); } } else { LogPrint("ERROR", "GetKey fail or GetVec6 fail\r\n"); } } } } return false; }
CService ip(uint32_t i) { struct in_addr s; s.s_addr = i; return CService(CNetAddr(s), SysCfg().GetDefaultPort());
bool CSharkfundAddress::Set(const CKeyID &id) { SetData(SysCfg().Base58Prefix(CBaseParams::PUBKEY_ADDRESS), &id, 20); return true; }
////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[],boost::thread_group &threadGroup) { // boost::thread* detectShutdownThread = NULL; bool fRet = false; try { // // Parameters // // If Qt is used, parameters/sharkfund.conf are parsed in qt/Sharkfund.cpp's main() CBaseParams::IntialParams(argc, argv); SysCfg().InitalConfig(); if (SysCfg().IsArgCount("-?") || SysCfg().IsArgCount("--help")) { // First part of help message is specific to Dacrsd / RPC client std::string strUsage = _("Sharkfund Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " Dacrsd [options] " + _("Start Sharkfund Core Daemon") + "\n" + _("Usage (deprecated, use Sharkfund-cli):") + "\n" + " sharkfund [options] <command> [params] " + _("Send command to Sharkfund Core") + "\n" + " sharkfund [options] help " + _("List commands") + "\n" + " sharkfund [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessage(HMM_BITCOIND); strUsage += "\n" + HelpMessageCli(false); fprintf(stdout, "%s", strUsage.c_str()); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "Sharkfund:")) fCommandLine = true; if (fCommandLine) { int ret = CommandLineRPC(argc, argv); exit(ret); } #ifndef WIN32 fDaemon = SysCfg().GetBoolArg("-daemon", false); if (fDaemon) { fprintf(stdout, "Sharkfund server starting\n"); // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) // Parent process, pid is child process id { CreatePidFile(GetPidFile(), pid); return true; } // Child process falls through to rest of initialization pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif SysCfg().SoftSetBoolArg("-server", true); fRet = AppInit2(threadGroup); } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } return fRet; }
tuple<bool, uint64_t, string> CVmRunEvn::run(shared_ptr<CBaseTransaction>& Tx, CAccountViewCache& view, CScriptDBViewCache& VmDB, int nHeight, uint64_t nBurnFactor, uint64_t &uRunStep) { if(nBurnFactor == 0) { // assert(0); return std::make_tuple (false, 0, string("VmScript nBurnFactor == 0 \n")); } m_ScriptDBTip = &VmDB; CTransaction* tx = static_cast<CTransaction*>(Tx.get()); if(tx->llFees <= CBaseTransaction::nMinTxFee) { return std::make_tuple (false, 0, string("vm run evn fee too litter\n")); } uint64_t maxstep = ((tx->llFees-CBaseTransaction::nMinTxFee)/ nBurnFactor) * 100; if(maxstep > MAX_BLOCK_RUN_STEP){ maxstep = MAX_BLOCK_RUN_STEP; } LogPrint("vm", "tx hash:%s fees=%lld fuelrate=%lld maxstep:%d\n", Tx->GetHash().GetHex(), tx->llFees, nBurnFactor, maxstep); if (!intial(Tx, view, nHeight)) { return std::make_tuple (false, 0, string("VmScript inital Failed\n")); } int64_t step = pMcu.get()->run(maxstep,this); if (0 == step) { return std::make_tuple(false, 0, string("VmScript run Failed\n")); } else if (-1 == step) { return std::make_tuple(false, 0, string("execure tx contranct run step exceed the max step limit\n")); }else{ uRunStep = step; } LogPrint("vm", "tx:%s,step:%ld\n", tx->ToString(view), uRunStep); if (!CheckOperate(m_output)) { return std::make_tuple (false, 0, string("VmScript CheckOperate Failed \n")); } if (!OpeatorAccount(m_output, view, nHeight)) { return std::make_tuple (false, 0, string("VmScript OpeatorAccount Failed\n")); } LogPrint("vm", "isCheckAccount:%d\n", isCheckAccount); if(isCheckAccount) { LogPrint("vm","isCheckAccount is true\n"); if(!CheckAppAcctOperate(tx)) return std::make_tuple (false, 0, string("VmScript CheckAppAcct Failed\n")); } if(!OpeatorAppAccount(MapAppOperate, *m_ScriptDBTip)) { return std::make_tuple (false, 0, string("OpeatorApp Account Failed\n")); } if(SysCfg().GetOutPutLog() && m_output.size() > 0) { CScriptDBOperLog operlog; uint256 txhash = GetCurTxHash(); if(!m_ScriptDBTip->WriteTxOutPut(txhash, m_output, operlog)) return std::make_tuple (false, 0, string("write tx out put Failed \n")); m_dblog->push_back(operlog); } uint64_t spend = uRunStep * nBurnFactor; if((spend < uRunStep) || (spend < nBurnFactor)){ return std::make_tuple (false, 0, string("mul error\n")); } return std::make_tuple (true, spend, string("VmScript Sucess\n")); }