void DiskService::ServiceWork() { debug("Disk service work"); if (g_Options->GetDiskSpace() > 0 && g_WorkState->GetDownloading()) { // check free disk space every 1 second CheckDiskSpace(); } if (m_waitingRequiredDir) { CheckRequiredDir(); } }
static int check_for_mem(int stored_at, long howmuch) { // This function returns an adjusted stored_at value. // This is where the memory requested can be allocated. long maxmem; BYTE *temp; int use_this_type; maxmem = (long)USHRT_MAX; if (debugflag == debug_flags::force_memory_from_disk) stored_at = DISK; if (debugflag == debug_flags::force_memory_from_memory) stored_at = MEMORY; switch (stored_at) { case MEMORY: // check_for_mem if (maxmem > howmuch) { temp = (BYTE *)malloc(howmuch + FAR_RESERVE); if (temp != nullptr) { // minimum free space + requested amount free(temp); use_this_type = MEMORY; break; } } case DISK: // check_for_mem default: // just in case a nonsense number gets used if (CheckDiskSpace(howmuch)) { use_this_type = DISK; break; } // failed, fall through, no memory available case NOWHERE: // check_for_mem use_this_type = NOWHERE; break; } // end of switch return (use_this_type); }
int KHttpFile::OnProgress(int nFileSize, int nDownloadedSize, int nRecved) { int nRetCode = false; m_nFileSize = nFileSize; m_nDownloadedSize = nDownloadedSize; if (m_nCheckDiskFlag) { nRetCode = CheckDiskSpace(); if (!nRetCode) m_Downloader.StopDownload(); m_nCheckDiskFlag = false; } if (m_pCallback) { m_pCallback->OnProgress(this, nRecved); } return true; }
void PrePostProcessor::Run() { debug("Entering PrePostProcessor-loop"); if (g_pOptions->GetServerMode() && g_pOptions->GetSaveQueue() && g_pOptions->GetReloadQueue() && g_pOptions->GetReloadPostQueue()) { DownloadQueue* pDownloadQueue = g_pQueueCoordinator->LockQueue(); SanitisePostQueue(pDownloadQueue->GetPostQueue()); g_pQueueCoordinator->UnlockQueue(); } g_pScheduler->FirstCheck(); ApplySchedulerState(); int iDiskSpaceInterval = 1000; int iSchedulerInterval = 1000; int iHistoryInterval = 60000; const int iStepMSec = 200; while (!IsStopped()) { // check incoming nzb directory g_pScanner->Check(); if (!(g_pOptions->GetPauseDownload() || g_pOptions->GetPauseDownload2()) && g_pOptions->GetDiskSpace() > 0 && !g_pQueueCoordinator->GetStandBy() && iDiskSpaceInterval >= 1000) { // check free disk space every 1 second CheckDiskSpace(); iDiskSpaceInterval = 0; } iDiskSpaceInterval += iStepMSec; // check post-queue every 200 msec CheckPostQueue(); if (iSchedulerInterval >= 1000) { // check scheduler tasks every 1 second g_pScheduler->IntervalCheck(); ApplySchedulerState(); iSchedulerInterval = 0; CheckScheduledResume(); } iSchedulerInterval += iStepMSec; if (iHistoryInterval >= 60000) { // check history (remove old entries) every 1 minute CheckHistory(); iHistoryInterval = 0; } iHistoryInterval += iStepMSec; usleep(iStepMSec * 1000); } Cleanup(); debug("Exiting PrePostProcessor-loop"); }
void CPopsTestHarness::FillDiskL() // // Fill all available space on C: drive leaving aLeaveFreeByes free. // { TInt leaveFreeBytes = KTestDiskSpace; // Check that there is a C-drive and that it is less than 10MB in size. TestAvailableSpaceOnDriveL(); // NOTE: This test harness should be used with a dedicated small partition or // subst'ed floppy drive as the EPOC C: drive. As a safety precaution, it // tests the free space on the partition to ensure that it does not attempt // to eat 20 GB of free space and either crash Windows or at least cause a // headache of some sort... // Delete any old dummy fill files - if there is one to delete. iTestUtils->FileSession().Delete(KMsvTestFillDiskFile); // Create the delay timer CDelayTimer* delayTimer = new(ELeave)CDelayTimer; CleanupStack::PushL(delayTimer); delayTimer->ConstructL(); // Check that available disk space does not exceed the max free space to fill. // See above... TInt64 freeSpace; TInt64 freeSpaceLeft; TInt error = CheckDiskSpace(freeSpace); TInt reclaimActive = 0; do { delayTimer->Delay(KMsvTestBackgroundDeleteInitialWait); error = CheckDiskSpace(freeSpaceLeft); if (freeSpaceLeft == freeSpace) reclaimActive++; freeSpace = freeSpaceLeft; } while (!error && reclaimActive<3); User::LeaveIfError(error); CleanupStack::PopAndDestroy(); //delayTimer // Free space in kb. freeSpace/=KFillDiskOneKByte; // Check free space on C: drive is not too big. TInt freeSpaceInKb = I64INT(freeSpace); if (freeSpaceInKb>KFillDiskTooBigFreeSize) User::Leave(KErrTooBig); // Fill disk with large file. TBuf8<KFillDiskMaxBlockSize> dummy; dummy.SetMax(); dummy.Fill('?'); // Open dummy file. RFile fillDiskFile; User::LeaveIfError(fillDiskFile.Replace(iTestUtils->FileSession(), KMsvTestFillDiskFile, EFileWrite)); // Establish required dummy file size. freeSpaceLeft-=leaveFreeBytes; if (freeSpaceLeft<0) // Uh oh, we have less space available than what was asked for... User::Leave(KErrDiskFull); // Write dummy file. while (freeSpaceLeft>0 && error==KErrNone) { dummy.SetLength(Min(KFillDiskMaxBlockSize,I64INT(freeSpaceLeft))); error=fillDiskFile.Write(dummy); freeSpaceLeft-=KFillDiskMaxBlockSize; } fillDiskFile.Close(); if (error==KErrDiskFull) error=KErrNone; User::LeaveIfError(error); }
/** Initialize bitcoin. * @pre Parameters should be parsed and config file should be read. */ bool AppInit2(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); #endif #ifndef WIN32 umask(077); // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); #endif if (!CheckDiskSpace()) return false; // ********************************************************* Step 2: parameter interactions nNodeLifespan = GetArg("-addrlifespan", 7); nMinStakeInterval = GetArg("-minstakeinterval", 0); nMinerSleep = GetArg("-minersleep", 500); // Largest block you're willing to create. // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2); nBlockMaxSize = std::max((unsigned int)1000, std::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 nBlockPrioritySize = GetArg("-blockprioritysize", 27000); nBlockPrioritySize = std::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: nBlockMinSize = GetArg("-blockminsize", 0); nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); // Fee-per-kilobyte amount considered the same as "free" // Be careful setting this: if you set it to zero then // a transaction spammer can cheaply fill blocks using // 1-satoshi-fee transactions. It should be set above the real // cost to you of processing a transaction. if (mapArgs.count("-mintxfee")) ParseMoney(mapArgs["-mintxfee"], nMinTxFee); if (fDebug) LogPrintf("nMinerSleep %u\n", nMinerSleep); CheckpointsMode = Checkpoints::STRICT; std::string strCpMode = GetArg("-cppolicy", "strict"); if (strCpMode == "strict") CheckpointsMode = Checkpoints::STRICT; if (strCpMode == "advisory") CheckpointsMode = Checkpoints::ADVISORY; if (strCpMode == "permissive") CheckpointsMode = Checkpoints::PERMISSIVE; nDerivationMethodIndex = 0; fTestNet = GetBoolArg("-testnet"); if (!SelectParamsFromCommandLine()) return InitError("Invalid combination of -testnet and -regtest."); if (GetBoolArg("-thinmode")) nNodeMode = NT_THIN; if (fTestNet) { SoftSetBoolArg("-irc", true); } if (mapArgs.count("-bind")) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified SoftSetBoolArg("-listen", true); } if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default SoftSetBoolArg("-dnsseed", false); SoftSetBoolArg("-listen", false); } if (mapArgs.count("-proxy")) { // to protect privacy, do not listen by default if a proxy server is specified SoftSetBoolArg("-listen", false); } if (!GetBoolArg("-listen", true)) { // do not map ports or try to retrieve public IP when not listening (pointless) SoftSetBoolArg("-upnp", false); SoftSetBoolArg("-discover", false); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others SoftSetBoolArg("-discover", false); } if (GetBoolArg("-salvagewallet")) { // Rewrite just private keys: rescan to find transactions SoftSetBoolArg("-rescan", true); } if (fTestNet) { nStakeMinAge = 1 * 60 * 60; // test net min age is 1 hour nCoinbaseMaturity = 10; // test maturity is 10 blocks }; // ********************************************************* Step 3: parameter-to-internal-flags fDebug = !mapMultiArgs["-debug"].empty(); // Special-case: if -debug=0/-nodebug is set, turn off debugging messages const std::vector<std::string>& categories = mapMultiArgs["-debug"]; if (GetBoolArg("-nodebug", false) || std::find(categories.begin(), categories.end(), std::string("0")) != categories.end()) fDebug = false; // -debug implies fDebug*, unless otherwise specified if (fDebug) { SoftSetBoolArg("-debugnet", true); SoftSetBoolArg("-debugsmsg", true); SoftSetBoolArg("-debugchain", true); SoftSetBoolArg("-debugringsig", true); }; fDebugNet = GetBoolArg("-debugnet"); fDebugSmsg = GetBoolArg("-debugsmsg"); fDebugChain = GetBoolArg("-debugchain"); fDebugRingSig = GetBoolArg("-debugringsig"); fDebugPoS = GetBoolArg("-debugpos"); fNoSmsg = GetBoolArg("-nosmsg"); // Check for -socks - as this is a privacy risk to continue, exit here if (mapArgs.count("-socks")) return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.")); bitdb.SetDetach(GetBoolArg("-detachdb", false)); if (fDaemon) fServer = true; else fServer = GetBoolArg("-server", false); /* force fServer when running without GUI */ if (!fHaveGUI) fServer = true; fPrintToConsole = GetBoolArg("-printtoconsole"); fPrintToDebugLog = SoftSetBoolArg("-printtodebuglog", true); fLogTimestamps = GetBoolArg("-logtimestamps"); if (mapArgs.count("-timeout")) { int nNewTimeout = GetArg("-timeout", 5000); if (nNewTimeout > 0 && nNewTimeout < 600000) nConnectTimeout = nNewTimeout; }; if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str())); if (nTransactionFee > 0.25 * COIN) InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); }; fConfChange = GetBoolArg("-confchange", false); fEnforceCanonical = GetBoolArg("-enforcecanonical", true); if (mapArgs.count("-mininput")) { if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue)) return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str())); }; // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log // Sanity check if (!InitSanityCheck()) return InitError(_("Initialization sanity check failed. PerfectCoin is shutting down.")); std::string strDataDir = GetDataDir().string(); std::string strWalletFileName = GetArg("-wallet", "wallet.dat"); // strWalletFileName must be a plain filename without a directory if (strWalletFileName != fs::basename(strWalletFileName) + fs::extension(strWalletFileName)) return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str())); // Make sure only a single Bitcoin process is using the data directory. fs::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) return InitError(strprintf(_("Cannot obtain a lock on data directory %s. PerfectCoin is probably already running."), strDataDir.c_str())); if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); LogPrintf("PerfectCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str()); LogPrintf("Operating in %s mode.\n", GetNodeModeName(nNodeMode)); LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); if (!fLogTimestamps) LogPrintf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str()); LogPrintf("Default data directory %s\n", GetDefaultDataDir().string().c_str()); LogPrintf("Used data directory %s\n", strDataDir.c_str()); std::ostringstream strErrors; if (fDaemon) { fprintf(stdout, "PerfectCoin server starting\n"); fflush(stdout); }; int64_t nStart; /* ********************************************************* Step 4.5: adjust parameters for nNodeMode ********************************************************* */ switch (nNodeMode) { case NT_FULL: if (GetBoolArg("-nothinssupport")) { LogPrintf("Thin support disabled.\n"); nLocalServices &= ~(THIN_SUPPORT); }; if (GetBoolArg("-nothinstealth")) { LogPrintf("Thin stealth support disabled.\n"); nLocalServices &= ~(THIN_STEALTH); }; break; case NT_THIN: SetBoolArg("-staking", false); // -- clear services nLocalServices &= ~(NODE_NETWORK); nLocalServices &= ~(THIN_SUPPORT); nLocalServices &= ~(THIN_STAKE); nLocalServices &= ~(THIN_STEALTH); nLocalRequirements |= (THIN_SUPPORT); if (GetBoolArg("-thinfullindex")) { LogPrintf("Thin full index enabled.\n"); fThinFullIndex = true; } else { nThinIndexWindow = GetArg("-thinindexmax", 4096); if (nThinIndexWindow < 4096) { LogPrintf("Thin index window minimum size is %d.\n", 4096); nThinIndexWindow = 4096; }; LogPrintf("Thin index window size %d.\n", nThinIndexWindow); }; if (GetBoolArg("-nothinstealth")) { LogPrintf("Thin stealth disabled.\n"); } else { nLocalRequirements |= (THIN_STEALTH); }; break; default: break; }; // -- thin and full if (fNoSmsg) nLocalServices &= ~(SMSG_RELAY); if (initialiseRingSigs() != 0) return InitError("initialiseRingSigs() failed."); // ********************************************************* Step 5: verify database integrity uiInterface.InitMessage(_("Verifying database integrity...")); if (!bitdb.Open(GetDataDir())) { std::string msg = strprintf(_("Error initializing database environment %s!" " To recover, BACKUP THAT DIRECTORY, then remove" " everything from it except for wallet.dat."), strDataDir.c_str()); return InitError(msg); }; if (GetBoolArg("-salvagewallet")) { // Recover readable keypairs: if (!CWalletDB::Recover(bitdb, strWalletFileName, true)) return false; }; if (fs::exists(GetDataDir() / strWalletFileName)) { CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { std::string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if" " your balance or transactions are incorrect you should" " restore from a backup."), strDataDir.c_str()); uiInterface.ThreadSafeMessageBox(msg, _("PerfectCoin"), CClientUIInterface::BTN_OK | CClientUIInterface::ICON_WARNING | CClientUIInterface::MODAL); }; if (r == CDBEnv::RECOVER_FAIL) return InitError(_("wallet.dat corrupt, salvage failed")); }; // ********************************************************* Step 6: network initialization nMaxThinPeers = GetArg("-maxthinpeers", 8); nBloomFilterElements = GetArg("-bloomfilterelements", 1536); if (mapArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str())); nets.insert(net); }; for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); }; };
// ----------------------------------------------------------------------------- // CSdDisk::FillDisk() // Fills the diskspace // // ----------------------------------------------------------------------------- void CSdDisk::FillDisk(RFs& aFs, TInt& aFreeDiskSpaceToLeave) { RFile iEaterFile; TInt fileSize(0); TInt err(KErrNone); TReal64 diskFree = CheckDiskSpace(aFs); // RDebug::Print(_L("Shareddatatest ## Eat disk space") ); // For loop to create eaterfiles for ( TInt i = 0 ; diskFree != 0 ; i++ ) { TBuf16<30> str; str.Copy(KFileName); str.AppendNum(i,EDecimal); // RDebug::Print(_L("Shareddatatest ## Open file %s"), &str); err = iEaterFile.Open( aFs, str, EFileShareAny | EFileWrite ); if ( err == KErrNotFound ) // file does not exist - create it { err = iEaterFile.Create( aFs, str, EFileShareAny | EFileWrite ); } if ( err == KErrNone ) { // Create maximum size eaterfile if there is more disk space available than the maximum file size if ( diskFree > TReal64(KMaxTInt) ) { // RDebug::Print( _L("Shareddatatest ## Creating %d. EaterFile"), i+1); err = iEaterFile.SetSize( KMaxTInt ); diskFree = diskFree - TReal64(KMaxTInt); } // ... And if available disk space is less than maximum file size else { // If aFreeDiskSpaceToLeave parameter says we have to leave some free disk if ( aFreeDiskSpaceToLeave != 0 ) { // RDebug::Print( _L("Shareddatatest ## Creating %d. EaterFile"), i+1); TInt sizeToSet = STATIC_CAST(TInt, I64INT(diskFree)); err = iEaterFile.SetSize( sizeToSet - aFreeDiskSpaceToLeave * 1024 ); iEaterFile.Size( fileSize ); // RDebug::Print( _L("Shareddatatest ## Last EaterFileSize: %d"), fileSize); diskFree = 0; } // Otherwise try to eat all the disk space else { // RDebug::Print( _L("Shareddatatest ## Creating %d. EaterFile"), i+1); TInt sizeToSet = STATIC_CAST(TInt, I64INT(diskFree)); // RDebug::Print( _L("Shareddatatest ## Filesize in the end should be around %d bytes"), sizeToSet); for ( TInt j = 64 ; err != KErrDiskFull ; j-- ) { err = iEaterFile.SetSize( sizeToSet - j * 1024 ); } iEaterFile.Size( fileSize ); // RDebug::Print( _L("Shareddatatest ## Last EaterFileSize: %d bytes"), fileSize); // RDebug::Print( _L("Shareddatatest ## There should be %d bytes of free disk"),sizeToSet - fileSize); diskFree = 0; } } } else { RDebug::Print(_L("Shareddatatest ## Error = %d"), err); diskFree = 0; } // RDebug::Print(_L("Shareddatatest ## Close file")); iEaterFile.Close(); } }
bool CBlock::AcceptBlock() { AssertLockHeld(cs_main); if (nVersion > CURRENT_VERSION) return DoS(100, error("AcceptBlock() : reject unknown block version %d", nVersion)); // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; if (IsProofOfStake() && nHeight < Params().FirstPOSBlock()) return DoS(100, error("AcceptBlock() : reject proof-of-stake at height <= %d", nHeight)); // Check coinbase timestamp if (GetBlockTime() > FutureDrift((int64_t)vtx[0].nTime, IsProofOfStake())) return DoS(50, error("AcceptBlock() : coinbase timestamp is too early")); // Check coinstake timestamp if (IsProofOfStake() && !CheckCoinStakeTimestamp(nHeight, GetBlockTime(), (int64_t)vtx[1].nTime)) return DoS(50, error("AcceptBlock() : coinstake timestamp violation nTimeBlock=%d nTimeTx=%u", GetBlockTime(), vtx[1].nTime)); // Check proof-of-work or proof-of-stake if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake())) return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake")); // Check timestamp against prev LogPrintf("GetBlockTime(): %d, <=? pindexPrev->GetPastTimeLimit(): %d\nFutureDrift(GetBlockTime()): %d, <?pindexPrev->GetBlockTime(): %d\n",GetBlockTime(),pindexPrev->GetPastTimeLimit(),FutureDrift(GetBlockTime()),pindexPrev->GetBlockTime()); if (GetBlockTime() <= pindexPrev->GetPastTimeLimit() || FutureDrift(GetBlockTime(), IsProofOfStake()) < pindexPrev->GetBlockTime()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!IsFinalTx(tx, nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckHardened(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight)); uint256 hashProof; // Verify hash target and signature of coinstake tx if (IsProofOfStake()) { uint256 targetProofOfStake; if (!CheckProofOfStake(pindexPrev, vtx[1], nBits, hashProof, targetProofOfStake)) { return error("AcceptBlock() : check proof-of-stake failed for block %s", hash.ToString()); } } // PoW is checked in CheckBlock() if (IsProofOfWork()) { hashProof = GetPoWHash(); } // Check that the block satisfies synchronized checkpoint if (!Checkpoints::CheckSync(nHeight)) return error("AcceptBlock() : rejected by synchronized checkpoint"); // Enforce rule that the coinbase starts with serialized block height CScript expect = CScript() << nHeight; if (vtx[0].vin[0].scriptSig.size() < expect.size() || !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin())) return DoS(100, error("AcceptBlock() : block height mismatch in coinbase")); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos, hashProof)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); }
void CFileEngine::PasteFile(const TDesC& aFilaName) { if(NULL == iCopiedFile) { iControlFactory.CreateTipDialog(iMainEngine.GetDesById(ETurkeyTextRes_Copy_NotSelect),*this,ECmdNull); } else { if(!BaflUtils::FileExists(iFs,*iCopiedFile)) { iControlFactory.CreateTipDialog(iMainEngine.GetDesById(ETurkeyTextRes_FilePaste_SourceNotExist),*this,ECmdCancelCopy); } else { TParse parse; parse.Set(*iCopiedFile,NULL,NULL); const TDesC& driveAndPath = parse.DriveAndPath(); const TDesC& nameAndExt = parse.NameAndExt(); TFileName desFileName; TBool isFolder = EFalse; TInt err = BaflUtils::IsFolder(iFs,aFilaName,isFolder); if(KErrNone == err && isFolder) { desFileName.Append(aFilaName); if(desFileName.Right(1).Compare(_L("\\"))!=0) { desFileName.Append(_L("\\")); } desFileName.Append(nameAndExt); } else { TParse parseDes; parseDes.Set(aFilaName,NULL,NULL); desFileName.Append(parseDes.DriveAndPath()); if(parseDes.DriveAndPath().Right(1).Compare(_L("\\"))!=0) { desFileName.Append(_L("\\")); } desFileName.Append(nameAndExt); } iMainEngine.WriteLog16(*iCopiedFile); iMainEngine.WriteLog16(desFileName); TInt result = CheckDiskSpace(*iCopiedFile,desFileName); if(1 == result) { iControlFactory.CreateTipDialog(iMainEngine.GetDesById(ETurkeyTextRes_SaveAs_NoSpace),*this,ECmdCancelCopy); } else if(2 == result) { iControlFactory.CreateTipDialog(iMainEngine.GetDesById(ETurkeyTextRes_FilePaste_OtherError),*this,ECmdCancelCopy); } else { if(BaflUtils::FileExists(iFs,desFileName)) { TParse parseTemp; parseTemp.Set(desFileName,NULL,NULL); desFileName.Zero(); desFileName.Append(parseTemp.DriveAndPath()); desFileName.Append(iMainEngine.GetDesById(ETurkeyTextRes_Copy_SameName)); desFileName.Append(parseTemp.NameAndExt()); } iFileActiveEngine.CopyFile(*iCopiedFile,desFileName,this); iDialog = iControlFactory.CreateWaitDialog(iMainEngine.GetDesById(ETurkeyTextRes_NewSearch_SaveFile),*this,ECmdCopying); delete iCopiedFile; iCopiedFile = NULL; } //CleanupStack::PopAndDestroy(); //desFileName } } }
//------------------------------------------------------------------------- // freed_main() //------------------------------------------------------------------------- void freed_main() { // Setup for APOGEECD thingie. // InitDestPath(); // Make sure there's room to play the game // CheckDiskSpace(DISK_SPACE_NEEDED,CANT_PLAY_TXT,cds_dos_print); // Which version is this? (SHAREWARE? 1-3? 1-6?) // CheckForEpisodes(); std::string arg; switch (::g_args.check_argument(MainStrs, arg)) { #if IN_DEVELOPMENT || TECH_SUPPORT_VERSION case 0: // quick run gamestate.flags |= GS_QUICKRUN; case 1: // no wait gamestate.flags |= GS_NOWAIT; break; #endif case 2: // starting level gamestate.flags |= GS_STARTLEVEL; starting_level=scan_atoi(arg.c_str()); break; case 3: gamestate.flags |= GS_STARTLEVEL; starting_episode=scan_atoi(arg.c_str())-1; break; case 4: fprint(cinfo_text); printf("\n" " Version: %s\n" "COMPILE DATE: %s\n\n", __BLAKE_VERSION__,__DATE__); exit(0); break; case 5: ShowSystem(); exit(0); break; #if IN_DEVELOPMENT #ifdef DEBUG_VALUE case 6: debug_value=scan_atoi(g_argv[i]); break; #endif #endif case 7: gamestate.flags |= GS_TICS_FOR_SCORE; break; case 8: // gamestate.flags |= GS_MEM_FOR_SCORE; break; case 9: PowerBall = 1; break; case 11: gamestate.flags |= GS_STARTLEVEL; starting_difficulty=scan_atoi(arg.c_str())-1; break; case 10: gamestate.flags |= GS_MUSIC_TEST; break; case 12: gamestate.flags |= GS_SHOW_OVERHEAD; break; } #if BETA_TEST // // THIS IS FOR BETA ONLY! // _dos_getdate(&d); if ((d.year > BETA_YEAR) || ((d.year == BETA_YEAR) && (d.month > BETA_MONTH)) || ((d.year == BETA_YEAR) && (d.month == BETA_MONTH) && (d.day >= BETA_DAY))) { FILE *out; char name[20]="VSWAP."; strcat(name,extension); out = fopen(name,"w"); fprintf(out,"\n\n SELF DESTRUCTED \n"); fclose(out); remove("vswap.bs1"); fprint(dver_text); exit(0); } #endif InitGame (); bufferofs=SCREENSIZE; PreDemo(); }
void CheckKeys (void) { boolean one_eighty=false; Uint8 scan; static boolean Plus_KeyReleased; static boolean Minus_KeyReleased; static boolean I_KeyReleased; static boolean S_KeyReleased; #if IN_DEVELOPMENT || BETA_TEST // if (DebugOk && (Keyboard[sc_p] || PP_step)) // PicturePause (); #endif if (screenfaded || demoplayback) // don't do anything with a faded screen return; scan = LastScan; #if IN_DEVELOPMENT #ifdef ACTIVATE_TERMINAL if (Keyboard[sc_9] && Keyboard[sc_0]) ActivateTerminal(true); #endif #endif // // SECRET CHEAT CODE: 'JAM' // #if GAME_VERSION != SHAREWARE_VERSION if (Keyboard[sc_j] || Keyboard[sc_a] || Keyboard[sc_m]) { if (jam_buff[sizeof(jam_buff_cmp)-1] != LastScan) { memcpy(jam_buff,jam_buff+1,sizeof(jam_buff_cmp)-1); jam_buff[sizeof(jam_buff_cmp)-1] = LastScan; } } #endif CheckMusicToggle(); if (gamestate.rpower) { if (in_is_binding_pressed(e_bi_radar_magnify)) { if (Plus_KeyReleased && gamestate.rzoom<2) { UpdateRadarGuage(); gamestate.rzoom++; Plus_KeyReleased=false; } } else Plus_KeyReleased=true; if (in_is_binding_pressed(e_bi_radar_minify)) { if (Minus_KeyReleased && gamestate.rzoom) { UpdateRadarGuage(); gamestate.rzoom--; Minus_KeyReleased=false; } } else Minus_KeyReleased=true; } if (in_is_binding_pressed(e_bi_sfx)) { if (S_KeyReleased) { if ((SoundMode != sdm_Off) || (DigiMode!=sds_Off)) { if (SoundMode != sdm_Off) { SD_WaitSoundDone(); SD_SetSoundMode(sdm_Off); } if (DigiMode!=sds_Off) SD_SetDigiDevice(sds_Off); memcpy((char *)&SoundOn[55],"OFF.",4); } else { ClearMemory(); if (SoundBlasterPresent || AdLibPresent) SD_SetSoundMode(sdm_AdLib); else SD_SetSoundMode(sdm_Off); if (SoundBlasterPresent) SD_SetDigiDevice(sds_SoundBlaster); else if (SoundSourcePresent) SD_SetDigiDevice(sds_SoundSource); else SD_SetDigiDevice(sds_Off); CA_LoadAllSounds(); memcpy((char *)&SoundOn[55],"ON. ",4); } DISPLAY_TIMED_MSG(SoundOn,MP_BONUS,MT_GENERAL); S_KeyReleased=false; } } else S_KeyReleased=true; if (Keyboard[sc_return]) { #if (GAME_VERSION != SHAREWARE_VERSION) || GEORGE_CHEAT char loop; if ((!memcmp(jam_buff,jam_buff_cmp,sizeof(jam_buff_cmp)))) { jam_buff[0]=0; for (loop=0; loop<NUMKEYS; loop++) if (gamestate.numkeys[static_cast<int>(loop)] < MAXKEYS) gamestate.numkeys[static_cast<int>(loop)]=1; gamestate.health = 100; gamestate.ammo = MAX_AMMO; gamestate.rpower = MAX_RADAR_ENERGY; if (!DebugOk) { gamestate.score = 0; gamestate.nextextra = EXTRAPOINTS; } gamestate.TimeCount += 42000L; for (loop=0; loop<NUMWEAPONS-1; loop++) GiveWeapon(loop); DrawWeapon(); DrawHealth(); DrawKeys(); DrawScore(); DISPLAY_TIMED_MSG("\r\r YOU CHEATER!",MP_INTERROGATE,MT_GENERAL); ForceUpdateStatusBar(); ClearMemory (); ClearSplitVWB (); VW_ScreenToScreen (static_cast<Uint16>(displayofs),static_cast<Uint16>(bufferofs),80,160); Message("\n NOW you're jammin'!! \n"); IN_ClearKeysDown(); IN_Ack(); CleanDrawPlayBorder(); } else if (!in_use_modern_bindings) #endif one_eighty=true; } // Handle quick turning! // if (!gamestate.turn_around) { // 90 degrees left // if (in_is_binding_pressed(e_bi_quick_left)) { gamestate.turn_around = -90; gamestate.turn_angle = player->angle + 90; if (gamestate.turn_angle > 359) gamestate.turn_angle -= ANGLES; } // 180 degrees right // if (in_is_binding_pressed(e_bi_turn_around) || one_eighty) { gamestate.turn_around = 180; gamestate.turn_angle = player->angle + 180; if (gamestate.turn_angle > 359) gamestate.turn_angle -= ANGLES; } // 90 degrees right // if (in_is_binding_pressed(e_bi_quick_right)) { gamestate.turn_around = 90; gamestate.turn_angle = player->angle - 90; if (gamestate.turn_angle < 0) gamestate.turn_angle += ANGLES; } } // // pause key weirdness can't be checked as a scan code // if (in_is_binding_pressed(e_bi_pause)) { SD_MusicOff(); fontnumber = 4; BMAmsg(PAUSED_MSG); IN_Ack(); IN_ClearKeysDown(); fontnumber = 2; RedrawStatusAreas(); SD_MusicOn(); Paused = false; ::in_clear_mouse_deltas(); return; } #if IN_DEVELOPMENT if (TestQuickSave) { // TestQuickSave--; scan = sc_f8; } if (TestAutoMapper) PopupAutoMap(); #endif scan = sc_none; if (Keyboard[sc_escape]) scan = sc_escape; else if (in_is_binding_pressed(e_bi_help)) scan = sc_f1; if (in_is_binding_pressed(e_bi_save)) scan = sc_f2; else if (in_is_binding_pressed(e_bi_load)) scan = sc_f3; else if (in_is_binding_pressed(e_bi_sound)) scan = sc_f4; else if (in_is_binding_pressed(e_bi_controls)) scan = sc_f6; else if (in_is_binding_pressed(e_bi_end_game)) scan = sc_f7; else if (in_is_binding_pressed(e_bi_quick_save)) scan = sc_f8; else if (in_is_binding_pressed(e_bi_quick_load)) scan = sc_f9; else if (in_is_binding_pressed(e_bi_quick_exit)) scan = sc_f10; switch (scan) { case sc_f7: // END GAME case sc_f10: // QUIT TO DOS FinishPaletteShifts(); ClearMemory(); US_ControlPanel(scan); CleanDrawPlayBorder(); return; case sc_f2: // SAVE MISSION case sc_f8: // QUICK SAVE // Make sure there's room to save... // ClearMemory(); FinishPaletteShifts(); if (!CheckDiskSpace(DISK_SPACE_NEEDED, CANT_SAVE_GAME_TXT, cds_id_print)) { CleanDrawPlayBorder(); break; } case sc_f1: // HELP case sc_f3: // LOAD MISSION case sc_f4: // SOUND MENU case sc_f5: // RESIZE VIEW case sc_f6: // CONTROLS MENU case sc_f9: // QUICK LOAD case sc_escape: // MAIN MENU refresh_screen = true; if (scan < sc_f8) VW_FadeOut(); StopMusic(); ClearMemory(); ClearSplitVWB(); US_ControlPanel(scan); if (refresh_screen) { boolean old = loadedgame; loadedgame = false; DrawPlayScreen(false); loadedgame = old; } ClearMemory(); if (!sqActive || !loadedgame) StartMusic(false); IN_ClearKeysDown(); if (loadedgame) { PreloadGraphics(); loadedgame = false; DrawPlayScreen(false); } else if (!refresh_screen) CleanDrawPlayBorder(); if (!sqActive) StartMusic(false); return; } scan = sc_none; if (in_is_binding_pressed(e_bi_stats)) PopupAutoMap(); if (Keyboard[sc_back_quote]) { Keyboard[sc_back_quote] = 0; TryDropPlasmaDetonator(); } if ((DebugOk || gamestate.flags & GS_MUSIC_TEST) && (Keyboard[sc_backspace])) { Uint8 old_num=music_num; if (gamestate.flags & GS_MUSIC_TEST) { if (Keyboard[sc_left_arrow]) { if (music_num) music_num--; Keyboard[sc_left_arrow]=false; } else if (Keyboard[sc_right_arrow]) { if (music_num < LASTMUSIC-1) music_num++; Keyboard[sc_right_arrow]=false; } if (old_num != music_num) { ClearMemory(); delete [] audiosegs[STARTMUSIC + old_num]; audiosegs[STARTMUSIC + old_num] = NULL; StartMusic(false); DrawScore(); } } if (old_num == music_num) { fontnumber=4; SETFONTCOLOR(0,15); if (DebugKeys()) { CleanDrawPlayBorder(); } ::in_clear_mouse_deltas(); lasttimecount = TimeCount; return; } } if (in_is_binding_pressed(e_bi_attack_info)) { if (I_KeyReleased) { gamestate.flags ^= GS_ATTACK_INFOAREA; if (gamestate.flags & GS_ATTACK_INFOAREA) DISPLAY_TIMED_MSG(attacker_info_enabled,MP_ATTACK_INFO,MT_GENERAL); else DISPLAY_TIMED_MSG(attacker_info_disabled,MP_ATTACK_INFO,MT_GENERAL); I_KeyReleased = false; } } else I_KeyReleased = true; #ifdef CEILING_FLOOR_COLORS if (in_is_binding_pressed(e_bi_ceiling)) { gamestate.flags ^= GS_DRAW_CEILING; in_reset_binding_state(e_bi_ceiling); } if (in_is_binding_pressed(e_bi_flooring)) { ThreeDRefresh(); ThreeDRefresh(); gamestate.flags ^= GS_DRAW_FLOOR; in_reset_binding_state(e_bi_flooring); #if DUAL_SWAP_FILES ChangeSwapFiles(true); #endif } #endif if (in_is_binding_pressed(e_bi_lightning)) { in_reset_binding_state(e_bi_lightning); gamestate.flags ^= GS_LIGHTING; } }