Merge branch '0.5.x' into 0.6.0.x
[novacoin.git] / src / init.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include "headers.h"
6 #include "db.h"
7 #include "bitcoinrpc.h"
8 #include "net.h"
9 #include "init.h"
10 #include "strlcpy.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
13 #include <boost/filesystem/convenience.hpp>
14 #include <boost/interprocess/sync/file_lock.hpp>
15
16 #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
17 #define _BITCOIN_QT_PLUGINS_INCLUDED
18 #define __INSURE__
19 #include <QtPlugin>
20 Q_IMPORT_PLUGIN(qcncodecs)
21 Q_IMPORT_PLUGIN(qjpcodecs)
22 Q_IMPORT_PLUGIN(qtwcodecs)
23 Q_IMPORT_PLUGIN(qkrcodecs)
24 Q_IMPORT_PLUGIN(qtaccessiblewidgets)
25 #endif
26
27 using namespace std;
28 using namespace boost;
29
30 CWallet* pwalletMain;
31
32 //////////////////////////////////////////////////////////////////////////////
33 //
34 // Shutdown
35 //
36
37 void ExitTimeout(void* parg)
38 {
39 #ifdef WIN32
40     Sleep(5000);
41     ExitProcess(0);
42 #endif
43 }
44
45 void StartShutdown()
46 {
47 #ifdef QT_GUI
48     // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
49     QueueShutdown();
50 #else
51     // Without UI, Shutdown() can simply be started in a new thread
52     CreateThread(Shutdown, NULL);
53 #endif
54 }
55
56 void Shutdown(void* parg)
57 {
58     static CCriticalSection cs_Shutdown;
59     static bool fTaken;
60     bool fFirstThread = false;
61     TRY_CRITICAL_BLOCK(cs_Shutdown)
62     {
63         fFirstThread = !fTaken;
64         fTaken = true;
65     }
66     static bool fExit;
67     if (fFirstThread)
68     {
69         fShutdown = true;
70         nTransactionsUpdated++;
71         DBFlush(false);
72         StopNode();
73         DBFlush(true);
74         boost::filesystem::remove(GetPidFile());
75         UnregisterWallet(pwalletMain);
76         delete pwalletMain;
77         CreateThread(ExitTimeout, NULL);
78         Sleep(50);
79         printf("Bitcoin exiting\n\n");
80         fExit = true;
81 #ifndef QT_GUI
82         // ensure non UI client get's exited here, but let Bitcoin-Qt reach return 0; in bitcoin.cpp
83         exit(0);
84 #endif
85     }
86     else
87     {
88         while (!fExit)
89             Sleep(500);
90         Sleep(100);
91         ExitThread(0);
92     }
93 }
94
95 void HandleSIGTERM(int)
96 {
97     fRequestShutdown = true;
98 }
99
100
101
102
103
104
105 //////////////////////////////////////////////////////////////////////////////
106 //
107 // Start
108 //
109 #if !defined(QT_GUI)
110 int main(int argc, char* argv[])
111 {
112     bool fRet = false;
113     fRet = AppInit(argc, argv);
114
115     if (fRet && fDaemon)
116         return 0;
117
118     return 1;
119 }
120 #endif
121
122 bool AppInit(int argc, char* argv[])
123 {
124     bool fRet = false;
125     try
126     {
127         fRet = AppInit2(argc, argv);
128     }
129     catch (std::exception& e) {
130         PrintException(&e, "AppInit()");
131     } catch (...) {
132         PrintException(NULL, "AppInit()");
133     }
134     if (!fRet)
135         Shutdown(NULL);
136     return fRet;
137 }
138
139 bool AppInit2(int argc, char* argv[])
140 {
141 #ifdef _MSC_VER
142     // Turn off microsoft heap dump noise
143     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
144     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
145 #endif
146 #if _MSC_VER >= 1400
147     // Disable confusing "helpful" text message on abort, ctrl-c
148     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
149 #endif
150 #ifndef WIN32
151     umask(077);
152 #endif
153 #ifndef WIN32
154     // Clean shutdown on SIGTERM
155     struct sigaction sa;
156     sa.sa_handler = HandleSIGTERM;
157     sigemptyset(&sa.sa_mask);
158     sa.sa_flags = 0;
159     sigaction(SIGTERM, &sa, NULL);
160     sigaction(SIGINT, &sa, NULL);
161     sigaction(SIGHUP, &sa, NULL);
162 #endif
163
164     //
165     // Parameters
166     //
167     // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
168 #if !defined(QT_GUI)
169     ParseParameters(argc, argv);
170     if (!ReadConfigFile(mapArgs, mapMultiArgs))
171     {
172         fprintf(stderr, "Error: Specified directory does not exist\n");
173         Shutdown(NULL);
174     }
175 #endif
176
177     if (mapArgs.count("-?") || mapArgs.count("--help"))
178     {
179         string strUsage = string() +
180           _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
181           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
182             "  bitcoind [options]                   \t  " + "\n" +
183             "  bitcoind [options] <command> [params]\t  " + _("Send command to -server or bitcoind") + "\n" +
184             "  bitcoind [options] help              \t\t  " + _("List commands") + "\n" +
185             "  bitcoind [options] help <command>    \t\t  " + _("Get help for a command") + "\n" +
186           _("Options:") + "\n" +
187             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
188             "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
189             "  -gen             \t\t  " + _("Generate coins") + "\n" +
190             "  -gen=0           \t\t  " + _("Don't generate coins") + "\n" +
191             "  -min             \t\t  " + _("Start minimized") + "\n" +
192             "  -splash          \t\t  " + _("Show splash screen on startup (default: 1)") + "\n" +
193             "  -datadir=<dir>   \t\t  " + _("Specify data directory") + "\n" +
194             "  -dbcache=<n>     \t\t  " + _("Set database cache size in megabytes (default: 25)") + "\n" +
195             "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)") + "\n" +
196             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy") + "\n" +
197             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect") + "\n" +
198             "  -port=<port>     \t\t  " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
199             "  -maxconnections=<n>\t  " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
200             "  -addnode=<ip>    \t  "   + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
201             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node") + "\n" +
202             "  -irc             \t  "   + _("Find peers using internet relay chat (default: 0)") + "\n" +
203             "  -listen          \t  "   + _("Accept connections from outside (default: 1)") + "\n" +
204 #ifdef QT_GUI
205             "  -lang=<lang>     \t\t  " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
206 #endif
207             "  -dnsseed         \t  "   + _("Find peers using DNS lookup (default: 1)") + "\n" +
208             "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
209             "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
210             "  -maxreceivebuffer=<n>\t  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
211             "  -maxsendbuffer=<n>\t  "   + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
212 #ifdef USE_UPNP
213 #if USE_UPNP
214             "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
215 #else
216             "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
217 #endif
218 #endif
219             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send") + "\n" +
220 #ifdef QT_GUI
221             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands") + "\n" +
222 #endif
223 #if !defined(WIN32) && !defined(QT_GUI)
224             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands") + "\n" +
225 #endif
226             "  -testnet         \t\t  " + _("Use the test network") + "\n" +
227             "  -debug           \t\t  " + _("Output extra debugging information") + "\n" +
228             "  -logtimestamps   \t  "   + _("Prepend debug output with timestamp") + "\n" +
229             "  -printtoconsole  \t  "   + _("Send trace/debug info to console instead of debug.log file") + "\n" +
230 #ifdef WIN32
231             "  -printtodebugger \t  "   + _("Send trace/debug info to debugger") + "\n" +
232 #endif
233             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections") + "\n" +
234             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections") + "\n" +
235             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
236             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
237             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
238             "  -blocknotify=<cmd> "     + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
239             "  -upgradewallet   \t  "   + _("Upgrade wallet to latest format") + "\n" +
240             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)") + "\n" +
241             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions") + "\n" +
242             "  -checkblocks=<n> \t\t  " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
243             "  -checklevel=<n>  \t\t  " + _("How thorough the block verification is (0-6, default: 1)") + "\n";
244
245 #ifdef USE_SSL
246         strUsage += string() +
247             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
248             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
249             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)") + "\n" +
250             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)") + "\n" +
251             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
252 #endif
253
254         strUsage += string() +
255             "  -?               \t\t  " + _("This help message") + "\n";
256
257         // Remove tabs
258         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
259 #if defined(QT_GUI) && defined(WIN32)
260         // On windows, show a message box, as there is no stderr
261         wxMessageBox(strUsage, "Usage");
262 #else
263         fprintf(stderr, "%s", strUsage.c_str());
264 #endif
265         return false;
266     }
267
268     fTestNet = GetBoolArg("-testnet");
269     if (fTestNet)
270     {
271         SoftSetBoolArg("-irc", true);
272     }
273
274     fDebug = GetBoolArg("-debug");
275
276 #if !defined(WIN32) && !defined(QT_GUI)
277     fDaemon = GetBoolArg("-daemon");
278 #else
279     fDaemon = false;
280 #endif
281
282     if (fDaemon)
283         fServer = true;
284     else
285         fServer = GetBoolArg("-server");
286
287     /* force fServer when running without GUI */
288 #if !defined(QT_GUI)
289     fServer = true;
290 #endif
291     fPrintToConsole = GetBoolArg("-printtoconsole");
292     fPrintToDebugger = GetBoolArg("-printtodebugger");
293     fLogTimestamps = GetBoolArg("-logtimestamps");
294
295 #ifndef QT_GUI
296     for (int i = 1; i < argc; i++)
297         if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
298             fCommandLine = true;
299
300     if (fCommandLine)
301     {
302         int ret = CommandLineRPC(argc, argv);
303         exit(ret);
304     }
305 #endif
306
307 #if !defined(WIN32) && !defined(QT_GUI)
308     if (fDaemon)
309     {
310         // Daemonize
311         pid_t pid = fork();
312         if (pid < 0)
313         {
314             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
315             return false;
316         }
317         if (pid > 0)
318         {
319             CreatePidFile(GetPidFile(), pid);
320             return true;
321         }
322
323         pid_t sid = setsid();
324         if (sid < 0)
325             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
326     }
327 #endif
328
329     if (!fDebug && !pszSetDataDir[0])
330         ShrinkDebugFile();
331     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
332     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
333     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
334
335     if (GetBoolArg("-loadblockindextest"))
336     {
337         CTxDB txdb("r");
338         txdb.LoadBlockIndex();
339         PrintBlockTree();
340         return false;
341     }
342
343     // Make sure only a single bitcoin process is using the data directory.
344     string strLockFile = GetDataDir() + "/.lock";
345     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
346     if (file) fclose(file);
347     static boost::interprocess::file_lock lock(strLockFile.c_str());
348     if (!lock.try_lock())
349     {
350         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
351         return false;
352     }
353
354     std::ostringstream strErrors;
355     //
356     // Load data files
357     //
358     if (fDaemon)
359         fprintf(stdout, "bitcoin server starting\n");
360     int64 nStart;
361
362     InitMessage(_("Loading addresses..."));
363     printf("Loading addresses...\n");
364     nStart = GetTimeMillis();
365     if (!LoadAddresses())
366         strErrors << _("Error loading addr.dat") << "\n";
367     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
368
369     InitMessage(_("Loading block index..."));
370     printf("Loading block index...\n");
371     nStart = GetTimeMillis();
372     if (!LoadBlockIndex())
373         strErrors << _("Error loading blkindex.dat") << "\n";
374     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
375
376     InitMessage(_("Loading wallet..."));
377     printf("Loading wallet...\n");
378     nStart = GetTimeMillis();
379     bool fFirstRun;
380     pwalletMain = new CWallet("wallet.dat");
381     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
382     if (nLoadWalletRet != DB_LOAD_OK)
383     {
384         if (nLoadWalletRet == DB_CORRUPT)
385             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
386         else if (nLoadWalletRet == DB_TOO_NEW)
387             strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
388         else if (nLoadWalletRet == DB_NEED_REWRITE)
389         {
390             strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
391             printf("%s", strErrors.str().c_str());
392             wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
393             return false;
394         }
395         else
396             strErrors << _("Error loading wallet.dat") << "\n";
397     }
398
399     if (GetBoolArg("-upgradewallet", fFirstRun))
400     {
401         int nMaxVersion = GetArg("-upgradewallet", 0);
402         if (nMaxVersion == 0) // the -walletupgrade without argument case
403         {
404             printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
405             nMaxVersion = CLIENT_VERSION;
406             pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
407         }
408         else
409             printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
410         if (nMaxVersion < pwalletMain->GetVersion())
411             strErrors << _("Cannot downgrade wallet") << "\n";
412         pwalletMain->SetMaxVersion(nMaxVersion);
413     }
414
415     if (fFirstRun)
416     {
417         // Create new keyUser and set as default key
418         RandAddSeedPerfmon();
419
420         std::vector<unsigned char> newDefaultKey;
421         if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
422             strErrors << _("Cannot initialize keypool") << "\n";
423         pwalletMain->SetDefaultKey(newDefaultKey);
424         if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
425             strErrors << _("Cannot write default address") << "\n";
426     }
427
428     printf("%s", strErrors.str().c_str());
429     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
430
431     RegisterWallet(pwalletMain);
432
433     CBlockIndex *pindexRescan = pindexBest;
434     if (GetBoolArg("-rescan"))
435         pindexRescan = pindexGenesisBlock;
436     else
437     {
438         CWalletDB walletdb("wallet.dat");
439         CBlockLocator locator;
440         if (walletdb.ReadBestBlock(locator))
441             pindexRescan = locator.GetBlockIndex();
442     }
443     if (pindexBest != pindexRescan)
444     {
445         InitMessage(_("Rescanning..."));
446         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
447         nStart = GetTimeMillis();
448         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
449         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
450     }
451
452     InitMessage(_("Done loading"));
453     printf("Done loading\n");
454
455     //// debug print
456     printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
457     printf("nBestHeight = %d\n",            nBestHeight);
458     printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
459     printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
460     printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
461
462     if (!strErrors.str().empty())
463     {
464         wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
465         return false;
466     }
467
468     // Add wallet transactions that aren't already in a block to mapTransactions
469     pwalletMain->ReacceptWalletTransactions();
470
471     // Note: Bitcoin-QT stores several settings in the wallet, so we want
472     // to load the wallet BEFORE parsing command-line arguments, so
473     // the command-line/bitcoin.conf settings override GUI setting.
474
475     //
476     // Parameters
477     //
478     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
479     {
480         PrintBlockTree();
481         return false;
482     }
483
484     if (mapArgs.count("-timeout"))
485     {
486         int nNewTimeout = GetArg("-timeout", 5000);
487         if (nNewTimeout > 0 && nNewTimeout < 600000)
488             nConnectTimeout = nNewTimeout;
489     }
490
491     if (mapArgs.count("-printblock"))
492     {
493         string strMatch = mapArgs["-printblock"];
494         int nFound = 0;
495         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
496         {
497             uint256 hash = (*mi).first;
498             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
499             {
500                 CBlockIndex* pindex = (*mi).second;
501                 CBlock block;
502                 block.ReadFromDisk(pindex);
503                 block.BuildMerkleTree();
504                 block.print();
505                 printf("\n");
506                 nFound++;
507             }
508         }
509         if (nFound == 0)
510             printf("No blocks matching %s were found\n", strMatch.c_str());
511         return false;
512     }
513
514     if (mapArgs.count("-proxy"))
515     {
516         fUseProxy = true;
517         addrProxy = CService(mapArgs["-proxy"], 9050);
518         if (!addrProxy.IsValid())
519         {
520             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
521             return false;
522         }
523     }
524
525     bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
526     if (fTor)
527     {
528         // Use SoftSetBoolArg here so user can override any of these if they wish.
529         // Note: the GetBoolArg() calls for all of these must happen later.
530         SoftSetBoolArg("-listen", false);
531         SoftSetBoolArg("-irc", false);
532         SoftSetBoolArg("-dnsseed", false);
533         SoftSetBoolArg("-upnp", false);
534         SoftSetBoolArg("-dns", false);
535     }
536
537     fAllowDNS = GetBoolArg("-dns");
538     fNoListen = !GetBoolArg("-listen", true);
539
540     // Continue to put "/P2SH/" in the coinbase to monitor
541     // BIP16 support.
542     // This can be removed eventually...
543     const char* pszP2SH = "/P2SH/";
544     COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
545
546     if (!fNoListen)
547     {
548         std::string strError;
549         if (!BindListenPort(strError))
550         {
551             wxMessageBox(strError, "Bitcoin");
552             return false;
553         }
554     }
555
556     if (mapArgs.count("-addnode"))
557     {
558         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
559         {
560             CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
561             addr.nTime = 0; // so it won't relay unless successfully connected
562             if (addr.IsValid())
563                 addrman.Add(addr, CNetAddr("127.0.0.1"));
564         }
565     }
566
567     if (mapArgs.count("-paytxfee"))
568     {
569         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
570         {
571             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
572             return false;
573         }
574         if (nTransactionFee > 0.25 * COIN)
575             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
576     }
577
578     //
579     // Start the node
580     //
581     if (!CheckDiskSpace())
582         return false;
583
584     RandAddSeedPerfmon();
585
586     if (!CreateThread(StartNode, NULL))
587         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
588
589     if (fServer)
590         CreateThread(ThreadRPCServer, NULL);
591
592 #ifdef QT_GUI
593     if(GetStartOnSystemStartup())
594         SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
595 #endif
596
597 #if !defined(QT_GUI)
598     while (1)
599         Sleep(5000);
600 #endif
601
602     return true;
603 }
604
605 #ifdef WIN32
606 string StartupShortcutPath()
607 {
608     return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
609 }
610
611 bool GetStartOnSystemStartup()
612 {
613     return filesystem::exists(StartupShortcutPath().c_str());
614 }
615
616 bool SetStartOnSystemStartup(bool fAutoStart)
617 {
618     // If the shortcut exists already, remove it for updating
619     remove(StartupShortcutPath().c_str());
620
621     if (fAutoStart)
622     {
623         CoInitialize(NULL);
624
625         // Get a pointer to the IShellLink interface.
626         IShellLink* psl = NULL;
627         HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
628                                 CLSCTX_INPROC_SERVER, IID_IShellLink,
629                                 reinterpret_cast<void**>(&psl));
630
631         if (SUCCEEDED(hres))
632         {
633             // Get the current executable path
634             TCHAR pszExePath[MAX_PATH];
635             GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
636
637             TCHAR pszArgs[5] = TEXT("-min");
638
639             // Set the path to the shortcut target
640             psl->SetPath(pszExePath);
641             PathRemoveFileSpec(pszExePath);
642             psl->SetWorkingDirectory(pszExePath);
643             psl->SetShowCmd(SW_SHOWMINNOACTIVE);
644             psl->SetArguments(pszArgs);
645
646             // Query IShellLink for the IPersistFile interface for
647             // saving the shortcut in persistent storage.
648             IPersistFile* ppf = NULL;
649             hres = psl->QueryInterface(IID_IPersistFile,
650                                        reinterpret_cast<void**>(&ppf));
651             if (SUCCEEDED(hres))
652             {
653                 WCHAR pwsz[MAX_PATH];
654                 // Ensure that the string is ANSI.
655                 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
656                 // Save the link by calling IPersistFile::Save.
657                 hres = ppf->Save(pwsz, TRUE);
658                 ppf->Release();
659                 psl->Release();
660                 CoUninitialize();
661                 return true;
662             }
663             psl->Release();
664         }
665         CoUninitialize();
666         return false;
667     }
668     return true;
669 }
670
671 #elif defined(LINUX)
672
673 // Follow the Desktop Application Autostart Spec:
674 //  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
675
676 boost::filesystem::path GetAutostartDir()
677 {
678     namespace fs = boost::filesystem;
679
680     char* pszConfigHome = getenv("XDG_CONFIG_HOME");
681     if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
682     char* pszHome = getenv("HOME");
683     if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
684     return fs::path();
685 }
686
687 boost::filesystem::path GetAutostartFilePath()
688 {
689     return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
690 }
691
692 bool GetStartOnSystemStartup()
693 {
694     boost::filesystem::ifstream optionFile(GetAutostartFilePath());
695     if (!optionFile.good())
696         return false;
697     // Scan through file for "Hidden=true":
698     string line;
699     while (!optionFile.eof())
700     {
701         getline(optionFile, line);
702         if (line.find("Hidden") != string::npos &&
703             line.find("true") != string::npos)
704             return false;
705     }
706     optionFile.close();
707
708     return true;
709 }
710
711 bool SetStartOnSystemStartup(bool fAutoStart)
712 {
713     if (!fAutoStart)
714     {
715 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
716         unlink(GetAutostartFilePath().string().c_str());
717 #else
718         unlink(GetAutostartFilePath().native_file_string().c_str());
719 #endif
720     }
721     else
722     {
723         char pszExePath[MAX_PATH+1];
724         memset(pszExePath, 0, sizeof(pszExePath));
725         if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
726             return false;
727
728         boost::filesystem::create_directories(GetAutostartDir());
729
730         boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
731         if (!optionFile.good())
732             return false;
733         // Write a bitcoin.desktop file to the autostart directory:
734         optionFile << "[Desktop Entry]\n";
735         optionFile << "Type=Application\n";
736         optionFile << "Name=Bitcoin\n";
737         optionFile << "Exec=" << pszExePath << " -min\n";
738         optionFile << "Terminal=false\n";
739         optionFile << "Hidden=false\n";
740         optionFile.close();
741     }
742     return true;
743 }
744 #else
745
746 // TODO: OSX startup stuff; see:
747 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
748
749 bool GetStartOnSystemStartup() { return false; }
750 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
751
752 #endif