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