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