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