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