Leave IRC enabled by default on testnet
[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     if (fTestNet)
263     {
264         SoftSetBoolArg("-irc", true);
265     }
266
267     fDebug = GetBoolArg("-debug");
268
269 #if !defined(WIN32) && !defined(QT_GUI)
270     fDaemon = GetBoolArg("-daemon");
271 #else
272     fDaemon = false;
273 #endif
274
275     if (fDaemon)
276         fServer = true;
277     else
278         fServer = GetBoolArg("-server");
279
280     /* force fServer when running without GUI */
281 #if !defined(QT_GUI)
282     fServer = true;
283 #endif
284     fPrintToConsole = GetBoolArg("-printtoconsole");
285     fPrintToDebugger = GetBoolArg("-printtodebugger");
286     fLogTimestamps = GetBoolArg("-logtimestamps");
287
288 #ifndef QT_GUI
289     for (int i = 1; i < argc; i++)
290         if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
291             fCommandLine = true;
292
293     if (fCommandLine)
294     {
295         int ret = CommandLineRPC(argc, argv);
296         exit(ret);
297     }
298 #endif
299
300 #if !defined(WIN32) && !defined(QT_GUI)
301     if (fDaemon)
302     {
303         // Daemonize
304         pid_t pid = fork();
305         if (pid < 0)
306         {
307             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
308             return false;
309         }
310         if (pid > 0)
311         {
312             CreatePidFile(GetPidFile(), pid);
313             return true;
314         }
315
316         pid_t sid = setsid();
317         if (sid < 0)
318             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
319     }
320 #endif
321
322     if (!fDebug && !pszSetDataDir[0])
323         ShrinkDebugFile();
324     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
325     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
326     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
327
328     if (GetBoolArg("-loadblockindextest"))
329     {
330         CTxDB txdb("r");
331         txdb.LoadBlockIndex();
332         PrintBlockTree();
333         return false;
334     }
335
336     // Make sure only a single bitcoin process is using the data directory.
337     string strLockFile = GetDataDir() + "/.lock";
338     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
339     if (file) fclose(file);
340     static boost::interprocess::file_lock lock(strLockFile.c_str());
341     if (!lock.try_lock())
342     {
343         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
344         return false;
345     }
346
347     std::ostringstream strErrors;
348     //
349     // Load data files
350     //
351     if (fDaemon)
352         fprintf(stdout, "bitcoin server starting\n");
353     int64 nStart;
354
355     InitMessage(_("Loading addresses..."));
356     printf("Loading addresses...\n");
357     nStart = GetTimeMillis();
358     if (!LoadAddresses())
359         strErrors << _("Error loading addr.dat") << "\n";
360     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
361
362     InitMessage(_("Loading block index..."));
363     printf("Loading block index...\n");
364     nStart = GetTimeMillis();
365     if (!LoadBlockIndex())
366         strErrors << _("Error loading blkindex.dat") << "\n";
367     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
368
369     InitMessage(_("Loading wallet..."));
370     printf("Loading wallet...\n");
371     nStart = GetTimeMillis();
372     bool fFirstRun;
373     pwalletMain = new CWallet("wallet.dat");
374     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
375     if (nLoadWalletRet != DB_LOAD_OK)
376     {
377         if (nLoadWalletRet == DB_CORRUPT)
378             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
379         else if (nLoadWalletRet == DB_TOO_NEW)
380             strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
381         else if (nLoadWalletRet == DB_NEED_REWRITE)
382         {
383             strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
384             wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
385             return false;
386         }
387         else
388             strErrors << _("Error loading wallet.dat") << "\n";
389     }
390     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
391
392     RegisterWallet(pwalletMain);
393
394     CBlockIndex *pindexRescan = pindexBest;
395     if (GetBoolArg("-rescan"))
396         pindexRescan = pindexGenesisBlock;
397     else
398     {
399         CWalletDB walletdb("wallet.dat");
400         CBlockLocator locator;
401         if (walletdb.ReadBestBlock(locator))
402             pindexRescan = locator.GetBlockIndex();
403     }
404     if (pindexBest != pindexRescan)
405     {
406         InitMessage(_("Rescanning..."));
407         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
408         nStart = GetTimeMillis();
409         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
410         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
411     }
412
413     InitMessage(_("Done loading"));
414     printf("Done loading\n");
415
416     //// debug print
417     printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
418     printf("nBestHeight = %d\n",            nBestHeight);
419     printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
420     printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
421     printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
422
423     if (!strErrors.str().empty())
424     {
425         wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
426         return false;
427     }
428
429     // Add wallet transactions that aren't already in a block to mapTransactions
430     pwalletMain->ReacceptWalletTransactions();
431
432     // Note: Bitcoin-QT stores several settings in the wallet, so we want
433     // to load the wallet BEFORE parsing command-line arguments, so
434     // the command-line/bitcoin.conf settings override GUI setting.
435
436     //
437     // Parameters
438     //
439     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
440     {
441         PrintBlockTree();
442         return false;
443     }
444
445     if (mapArgs.count("-timeout"))
446     {
447         int nNewTimeout = GetArg("-timeout", 5000);
448         if (nNewTimeout > 0 && nNewTimeout < 600000)
449             nConnectTimeout = nNewTimeout;
450     }
451
452     if (mapArgs.count("-printblock"))
453     {
454         string strMatch = mapArgs["-printblock"];
455         int nFound = 0;
456         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
457         {
458             uint256 hash = (*mi).first;
459             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
460             {
461                 CBlockIndex* pindex = (*mi).second;
462                 CBlock block;
463                 block.ReadFromDisk(pindex);
464                 block.BuildMerkleTree();
465                 block.print();
466                 printf("\n");
467                 nFound++;
468             }
469         }
470         if (nFound == 0)
471             printf("No blocks matching %s were found\n", strMatch.c_str());
472         return false;
473     }
474
475     fGenerateBitcoins = GetBoolArg("-gen");
476
477     if (mapArgs.count("-proxy"))
478     {
479         fUseProxy = true;
480         addrProxy = CService(mapArgs["-proxy"], 9050);
481         if (!addrProxy.IsValid())
482         {
483             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
484             return false;
485         }
486     }
487
488     bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
489     if (fTor)
490     {
491         // Use SoftSetBoolArg here so user can override any of these if they wish.
492         // Note: the GetBoolArg() calls for all of these must happen later.
493         SoftSetBoolArg("-listen", false);
494         SoftSetBoolArg("-irc", false);
495         SoftSetBoolArg("-dnsseed", false);
496         SoftSetBoolArg("-upnp", false);
497         SoftSetBoolArg("-dns", false);
498     }
499
500     fAllowDNS = GetBoolArg("-dns");
501     fNoListen = !GetBoolArg("-listen", true);
502
503     // This code can be removed once a super-majority of the network has upgraded.
504     if (GetBoolArg("-bip16", true))
505     {
506         if (fTestNet)
507             SoftSetArg("-paytoscripthashtime", "1329264000"); // Feb 15
508         else
509             SoftSetArg("-paytoscripthashtime", "1330578000"); // Mar 1
510
511         // Put "/P2SH/" in the coinbase so everybody can tell when
512         // a majority of miners support it
513         const char* pszP2SH = "/P2SH/";
514         COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
515     }
516     else
517     {
518         const char* pszP2SH = "NOP2SH";
519         COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
520     }
521
522     // Command-line args override in-wallet settings:
523 #if USE_UPNP
524     fUseUPnP = GetBoolArg("-upnp", true);
525 #else
526     fUseUPnP = GetBoolArg("-upnp", false);
527 #endif
528
529     if (!fNoListen)
530     {
531         std::string strError;
532         if (!BindListenPort(strError))
533         {
534             wxMessageBox(strError, "Bitcoin");
535             return false;
536         }
537     }
538
539     if (mapArgs.count("-addnode"))
540     {
541         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
542         {
543             CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
544             addr.nTime = 0; // so it won't relay unless successfully connected
545             if (addr.IsValid())
546                 AddAddress(addr);
547         }
548     }
549
550     if (mapArgs.count("-paytxfee"))
551     {
552         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
553         {
554             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
555             return false;
556         }
557         if (nTransactionFee > 0.25 * COIN)
558             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
559     }
560
561     //
562     // Start the node
563     //
564     if (!CheckDiskSpace())
565         return false;
566
567     RandAddSeedPerfmon();
568
569     if (!CreateThread(StartNode, NULL))
570         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
571
572     if (fServer)
573         CreateThread(ThreadRPCServer, NULL);
574
575 #ifdef QT_GUI
576     if(GetStartOnSystemStartup())
577         SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
578 #endif
579
580 #if !defined(QT_GUI)
581     while (1)
582         Sleep(5000);
583 #endif
584
585     return true;
586 }
587
588 #ifdef WIN32
589 string StartupShortcutPath()
590 {
591     return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
592 }
593
594 bool GetStartOnSystemStartup()
595 {
596     return filesystem::exists(StartupShortcutPath().c_str());
597 }
598
599 bool SetStartOnSystemStartup(bool fAutoStart)
600 {
601     // If the shortcut exists already, remove it for updating
602     remove(StartupShortcutPath().c_str());
603
604     if (fAutoStart)
605     {
606         CoInitialize(NULL);
607
608         // Get a pointer to the IShellLink interface.
609         IShellLink* psl = NULL;
610         HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
611                                 CLSCTX_INPROC_SERVER, IID_IShellLink,
612                                 reinterpret_cast<void**>(&psl));
613
614         if (SUCCEEDED(hres))
615         {
616             // Get the current executable path
617             TCHAR pszExePath[MAX_PATH];
618             GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
619
620             TCHAR pszArgs[5] = TEXT("-min");
621
622             // Set the path to the shortcut target
623             psl->SetPath(pszExePath);
624             PathRemoveFileSpec(pszExePath);
625             psl->SetWorkingDirectory(pszExePath);
626             psl->SetShowCmd(SW_SHOWMINNOACTIVE);
627             psl->SetArguments(pszArgs);
628
629             // Query IShellLink for the IPersistFile interface for
630             // saving the shortcut in persistent storage.
631             IPersistFile* ppf = NULL;
632             hres = psl->QueryInterface(IID_IPersistFile,
633                                        reinterpret_cast<void**>(&ppf));
634             if (SUCCEEDED(hres))
635             {
636                 WCHAR pwsz[MAX_PATH];
637                 // Ensure that the string is ANSI.
638                 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
639                 // Save the link by calling IPersistFile::Save.
640                 hres = ppf->Save(pwsz, TRUE);
641                 ppf->Release();
642                 psl->Release();
643                 CoUninitialize();
644                 return true;
645             }
646             psl->Release();
647         }
648         CoUninitialize();
649         return false;
650     }
651     return true;
652 }
653
654 #elif defined(LINUX)
655
656 // Follow the Desktop Application Autostart Spec:
657 //  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
658
659 boost::filesystem::path GetAutostartDir()
660 {
661     namespace fs = boost::filesystem;
662
663     char* pszConfigHome = getenv("XDG_CONFIG_HOME");
664     if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
665     char* pszHome = getenv("HOME");
666     if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
667     return fs::path();
668 }
669
670 boost::filesystem::path GetAutostartFilePath()
671 {
672     return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
673 }
674
675 bool GetStartOnSystemStartup()
676 {
677     boost::filesystem::ifstream optionFile(GetAutostartFilePath());
678     if (!optionFile.good())
679         return false;
680     // Scan through file for "Hidden=true":
681     string line;
682     while (!optionFile.eof())
683     {
684         getline(optionFile, line);
685         if (line.find("Hidden") != string::npos &&
686             line.find("true") != string::npos)
687             return false;
688     }
689     optionFile.close();
690
691     return true;
692 }
693
694 bool SetStartOnSystemStartup(bool fAutoStart)
695 {
696     if (!fAutoStart)
697     {
698 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
699         unlink(GetAutostartFilePath().string().c_str());
700 #else
701         unlink(GetAutostartFilePath().native_file_string().c_str());
702 #endif
703     }
704     else
705     {
706         char pszExePath[MAX_PATH+1];
707         memset(pszExePath, 0, sizeof(pszExePath));
708         if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
709             return false;
710
711         boost::filesystem::create_directories(GetAutostartDir());
712
713         boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
714         if (!optionFile.good())
715             return false;
716         // Write a bitcoin.desktop file to the autostart directory:
717         optionFile << "[Desktop Entry]\n";
718         optionFile << "Type=Application\n";
719         optionFile << "Name=Bitcoin\n";
720         optionFile << "Exec=" << pszExePath << " -min\n";
721         optionFile << "Terminal=false\n";
722         optionFile << "Hidden=false\n";
723         optionFile.close();
724     }
725     return true;
726 }
727 #else
728
729 // TODO: OSX startup stuff; see:
730 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
731
732 bool GetStartOnSystemStartup() { return false; }
733 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
734
735 #endif