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