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