f09f044f168655314157c4ecdaa6210272c60b0f
[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 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 are parsed in qt/bitcoin.cpp's main()
154 #if !defined(QT_GUI)
155     ParseParameters(argc, argv);
156 #endif
157
158     if (mapArgs.count("-datadir"))
159     {
160         if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
161         {
162             filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
163             strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
164         }
165         else
166         {
167             fprintf(stderr, "Error: Specified directory does not exist\n");
168             Shutdown(NULL);
169         }
170     }
171
172
173     ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
174
175     if (mapArgs.count("-?") || mapArgs.count("--help"))
176     {
177         string strUsage = string() +
178           _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
179           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
180             "  bitcoind [options]                   \t  " + "\n" +
181             "  bitcoind [options] <command> [params]\t  " + _("Send command to -server or bitcoind") + "\n" +
182             "  bitcoind [options] help              \t\t  " + _("List commands") + "\n" +
183             "  bitcoind [options] help <command>    \t\t  " + _("Get help for a command") + "\n" +
184           _("Options:") + "\n" +
185             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
186             "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
187             "  -gen             \t\t  " + _("Generate coins") + "\n" +
188             "  -gen=0           \t\t  " + _("Don't generate coins") + "\n" +
189             "  -min             \t\t  " + _("Start minimized") + "\n" +
190             "  -datadir=<dir>   \t\t  " + _("Specify data directory") + "\n" +
191             "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)") + "\n" +
192             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy") + "\n" +
193             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect") + "\n" +
194             "  -port=<port>     \t\t  " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
195             "  -maxconnections=<n>\t  " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
196             "  -addnode=<ip>    \t  "   + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
197             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node") + "\n" +
198             "  -irc             \t  "   + _("Find peers using internet relay chat (default: 0)") + "\n" +
199             "  -listen          \t  "   + _("Accept connections from outside (default: 1)") + "\n" +
200 #ifdef QT_GUI
201             "  -lang=<lang>     \t\t  " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
202 #endif
203             "  -dnsseed         \t  "   + _("Find peers using DNS lookup (default: 1)") + "\n" +
204             "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
205             "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
206             "  -maxreceivebuffer=<n>\t  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
207             "  -maxsendbuffer=<n>\t  "   + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
208 #ifdef USE_UPNP
209 #if USE_UPNP
210             "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
211 #else
212             "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
213 #endif
214 #endif
215             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send") + "\n" +
216 #ifdef QT_GUI
217             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands") + "\n" +
218 #endif
219 #if !defined(WIN32) && !defined(QT_GUI)
220             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands") + "\n" +
221 #endif
222             "  -testnet         \t\t  " + _("Use the test network") + "\n" +
223             "  -debug           \t\t  " + _("Output extra debugging information") + "\n" +
224             "  -logtimestamps   \t  "   + _("Prepend debug output with timestamp") + "\n" +
225             "  -printtoconsole  \t  "   + _("Send trace/debug info to console instead of debug.log file") + "\n" +
226 #ifdef WIN32
227             "  -printtodebugger \t  "   + _("Send trace/debug info to debugger") + "\n" +
228 #endif
229             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections") + "\n" +
230             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections") + "\n" +
231             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
232             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
233             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
234             "  -blocknotify=<cmd> "     + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
235             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)") + "\n" +
236             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions") + "\n";
237
238 #ifdef USE_SSL
239         strUsage += string() +
240             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
241             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
242             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)") + "\n" +
243             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)") + "\n" +
244             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
245 #endif
246
247         strUsage += string() +
248             "  -?               \t\t  " + _("This help message") + "\n";
249
250         // Remove tabs
251         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
252 #if defined(QT_GUI) && defined(WIN32)
253         // On windows, show a message box, as there is no stderr
254         wxMessageBox(strUsage, "Usage");
255 #else
256         fprintf(stderr, "%s", strUsage.c_str());
257 #endif
258         return false;
259     }
260
261     fTestNet = GetBoolArg("-testnet");
262     fDebug = GetBoolArg("-debug");
263
264 #if !defined(WIN32) && !defined(QT_GUI)
265     fDaemon = GetBoolArg("-daemon");
266 #else
267     fDaemon = false;
268 #endif
269
270     if (fDaemon)
271         fServer = true;
272     else
273         fServer = GetBoolArg("-server");
274
275     /* force fServer when running without GUI */
276 #if !defined(QT_GUI)
277     fServer = true;
278 #endif
279     fPrintToConsole = GetBoolArg("-printtoconsole");
280     fPrintToDebugger = GetBoolArg("-printtodebugger");
281     fLogTimestamps = GetBoolArg("-logtimestamps");
282
283 #ifndef QT_GUI
284     for (int i = 1; i < argc; i++)
285         if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
286             fCommandLine = true;
287
288     if (fCommandLine)
289     {
290         int ret = CommandLineRPC(argc, argv);
291         exit(ret);
292     }
293 #endif
294
295 #if !defined(WIN32) && !defined(QT_GUI)
296     if (fDaemon)
297     {
298         // Daemonize
299         pid_t pid = fork();
300         if (pid < 0)
301         {
302             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
303             return false;
304         }
305         if (pid > 0)
306         {
307             CreatePidFile(GetPidFile(), pid);
308             return true;
309         }
310
311         pid_t sid = setsid();
312         if (sid < 0)
313             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
314     }
315 #endif
316
317     if (!fDebug && !pszSetDataDir[0])
318         ShrinkDebugFile();
319     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
320     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
321     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
322
323     if (GetBoolArg("-loadblockindextest"))
324     {
325         CTxDB txdb("r");
326         txdb.LoadBlockIndex();
327         PrintBlockTree();
328         return false;
329     }
330
331     // Make sure only a single bitcoin process is using the data directory.
332     string strLockFile = GetDataDir() + "/.lock";
333     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
334     if (file) fclose(file);
335     static boost::interprocess::file_lock lock(strLockFile.c_str());
336     if (!lock.try_lock())
337     {
338         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
339         return false;
340     }
341
342     std::ostringstream strErrors;
343     //
344     // Load data files
345     //
346     if (fDaemon)
347         fprintf(stdout, "bitcoin server starting\n");
348     int64 nStart;
349
350     InitMessage(_("Loading addresses..."));
351     printf("Loading addresses...\n");
352     nStart = GetTimeMillis();
353     if (!LoadAddresses())
354         strErrors << _("Error loading addr.dat") << "\n";
355     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
356
357     InitMessage(_("Loading block index..."));
358     printf("Loading block index...\n");
359     nStart = GetTimeMillis();
360     if (!LoadBlockIndex())
361         strErrors << _("Error loading blkindex.dat") << "\n";
362     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
363
364     InitMessage(_("Loading wallet..."));
365     printf("Loading wallet...\n");
366     nStart = GetTimeMillis();
367     bool fFirstRun;
368     pwalletMain = new CWallet("wallet.dat");
369     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
370     if (nLoadWalletRet != DB_LOAD_OK)
371     {
372         if (nLoadWalletRet == DB_CORRUPT)
373             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
374         else if (nLoadWalletRet == DB_TOO_NEW)
375             strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
376         else if (nLoadWalletRet == DB_NEED_REWRITE)
377         {
378             strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
379             wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
380             return false;
381         }
382         else
383             strErrors << _("Error loading wallet.dat") << "\n";
384     }
385     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
386
387     RegisterWallet(pwalletMain);
388
389     CBlockIndex *pindexRescan = pindexBest;
390     if (GetBoolArg("-rescan"))
391         pindexRescan = pindexGenesisBlock;
392     else
393     {
394         CWalletDB walletdb("wallet.dat");
395         CBlockLocator locator;
396         if (walletdb.ReadBestBlock(locator))
397             pindexRescan = locator.GetBlockIndex();
398     }
399     if (pindexBest != pindexRescan)
400     {
401         InitMessage(_("Rescanning..."));
402         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
403         nStart = GetTimeMillis();
404         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
405         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
406     }
407
408     InitMessage(_("Done loading"));
409     printf("Done loading\n");
410
411     //// debug print
412     printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
413     printf("nBestHeight = %d\n",            nBestHeight);
414     printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
415     printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
416     printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
417
418     if (!strErrors.str().empty())
419     {
420         wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
421         return false;
422     }
423
424     // Add wallet transactions that aren't already in a block to mapTransactions
425     pwalletMain->ReacceptWalletTransactions();
426
427     // Note: Bitcoin-QT stores several settings in the wallet, so we want
428     // to load the wallet BEFORE parsing command-line arguments, so
429     // the command-line/bitcoin.conf settings override GUI setting.
430
431     //
432     // Parameters
433     //
434     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
435     {
436         PrintBlockTree();
437         return false;
438     }
439
440     if (mapArgs.count("-timeout"))
441     {
442         int nNewTimeout = GetArg("-timeout", 5000);
443         if (nNewTimeout > 0 && nNewTimeout < 600000)
444             nConnectTimeout = nNewTimeout;
445     }
446
447     if (mapArgs.count("-printblock"))
448     {
449         string strMatch = mapArgs["-printblock"];
450         int nFound = 0;
451         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
452         {
453             uint256 hash = (*mi).first;
454             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
455             {
456                 CBlockIndex* pindex = (*mi).second;
457                 CBlock block;
458                 block.ReadFromDisk(pindex);
459                 block.BuildMerkleTree();
460                 block.print();
461                 printf("\n");
462                 nFound++;
463             }
464         }
465         if (nFound == 0)
466             printf("No blocks matching %s were found\n", strMatch.c_str());
467         return false;
468     }
469
470     fGenerateBitcoins = GetBoolArg("-gen");
471
472     if (mapArgs.count("-proxy"))
473     {
474         fUseProxy = true;
475         addrProxy = CService(mapArgs["-proxy"], 9050);
476         if (!addrProxy.IsValid())
477         {
478             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
479             return false;
480         }
481     }
482
483     bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
484     if (fTor)
485     {
486         // Use SoftSetBoolArg here so user can override any of these if they wish.
487         // Note: the GetBoolArg() calls for all of these must happen later.
488         SoftSetBoolArg("-listen", false);
489         SoftSetBoolArg("-irc", false);
490         SoftSetBoolArg("-dnsseed", false);
491         SoftSetBoolArg("-upnp", false);
492         SoftSetBoolArg("-dns", false);
493     }
494
495     fAllowDNS = GetBoolArg("-dns");
496     fNoListen = !GetBoolArg("-listen", true);
497
498     // This code can be removed once a super-majority of the network has upgraded.
499     if (GetBoolArg("-bip16", true))
500     {
501         if (fTestNet)
502             SoftSetArg("-paytoscripthashtime", "1329264000"); // Feb 15
503         else
504             SoftSetArg("-paytoscripthashtime", "1330578000"); // Mar 1
505
506         // Put "/P2SH/" in the coinbase so everybody can tell when
507         // a majority of miners support it
508         const char* pszP2SH = "/P2SH/";
509         COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
510     }
511     else
512     {
513         const char* pszP2SH = "NOP2SH";
514         COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
515     }
516
517     // Command-line args override in-wallet settings:
518 #if USE_UPNP
519     fUseUPnP = GetBoolArg("-upnp", true);
520 #else
521     fUseUPnP = GetBoolArg("-upnp", false);
522 #endif
523
524     if (!fNoListen)
525     {
526         std::string strError;
527         if (!BindListenPort(strError))
528         {
529             wxMessageBox(strError, "Bitcoin");
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                 AddAddress(addr);
542         }
543     }
544
545     if (mapArgs.count("-paytxfee"))
546     {
547         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
548         {
549             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
550             return false;
551         }
552         if (nTransactionFee > 0.25 * COIN)
553             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
554     }
555
556     //
557     // Start the node
558     //
559     if (!CheckDiskSpace())
560         return false;
561
562     RandAddSeedPerfmon();
563
564     if (!CreateThread(StartNode, NULL))
565         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
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