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