Add configure check for -latomic
[bitcoinplatinum.git] / doc / developer-notes.md
blob95c46b05fe203e06bcbd089da482d1a00bae802d
1 Developer Notes
2 ===============
4 Various coding styles have been used during the history of the codebase,
5 and the result is not very consistent. However, we're now trying to converge to
6 a single style, so please use it in new code. Old code will be converted
7 gradually.
8 - Basic rules specified in [src/.clang-format](/src/.clang-format).
9   Use a recent clang-format to format automatically using one of the [dev scripts]
10   (/contrib/devtools/README.md#clang-formatpy).
11   - Braces on new lines for namespaces, classes, functions, methods.
12   - Braces on the same line for everything else.
13   - 4 space indentation (no tabs) for every block except namespaces.
14   - No indentation for public/protected/private or for namespaces.
15   - No extra spaces inside parenthesis; don't do ( this )
16   - No space after function names; one space after if, for and while.
18 Block style example:
19 ```c++
20 namespace foo
22 class Class
24     bool Function(char* psz, int n)
25     {
26         // Comment summarising what this section of code does
27         for (int i = 0; i < n; i++) {
28             // When something fails, return early
29             if (!Something())
30                 return false;
31             ...
32         }
34         // Success return is usually at the end
35         return true;
36     }
39 ```
41 Doxygen comments
42 -----------------
44 To facilitate the generation of documentation, use doxygen-compatible comment blocks for functions, methods and fields.
46 For example, to describe a function use:
47 ```c++
48 /**
49  * ... text ...
50  * @param[in] arg1    A description
51  * @param[in] arg2    Another argument description
52  * @pre Precondition for function...
53  */
54 bool function(int arg1, const char *arg2)
55 ```
56 A complete list of `@xxx` commands can be found at http://www.stack.nl/~dimitri/doxygen/manual/commands.html.
57 As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't
58 *need* to provide any commands for a comment to be valid; just a description text is fine.
60 To describe a class use the same construct above the class definition:
61 ```c++
62 /**
63  * Alerts are for notifying old versions if they become too obsolete and
64  * need to upgrade. The message is displayed in the status bar.
65  * @see GetWarnings()
66  */
67 class CAlert
69 ```
71 To describe a member or variable use:
72 ```c++
73 int var; //!< Detailed description after the member
74 ```
77 ```cpp
78 //! Description before the member
79 int var;
80 ```
82 Also OK:
83 ```c++
84 ///
85 /// ... text ...
86 ///
87 bool function2(int arg1, const char *arg2)
88 ```
90 Not OK (used plenty in the current source, but not picked up):
91 ```c++
93 // ... text ...
95 ```
97 A full list of comment syntaxes picked up by doxygen can be found at http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html,
98 but if possible use one of the above styles.
100 Development tips and tricks
101 ---------------------------
103 **compiling for debugging**
105 Run configure with the --enable-debug option, then make. Or run configure with
106 CXXFLAGS="-g -ggdb -O0" or whatever debug flags you need.
108 **debug.log**
110 If the code is behaving strangely, take a look in the debug.log file in the data directory;
111 error and debugging messages are written there.
113 The -debug=... command-line option controls debugging; running with just -debug or -debug=1 will turn
114 on all categories (and give you a very large debug.log file).
116 The Qt code routes qDebug() output to debug.log under category "qt": run with -debug=qt
117 to see it.
119 **testnet and regtest modes**
121 Run with the -testnet option to run with "play bitcoins" on the test network, if you
122 are testing multi-machine code that needs to operate across the internet.
124 If you are testing something that can run on one machine, run with the -regtest option.
125 In regression test mode, blocks can be created on-demand; see qa/rpc-tests/ for tests
126 that run in -regtest mode.
128 **DEBUG_LOCKORDER**
130 Bitcoin Core is a multithreaded application, and deadlocks or other multithreading bugs
131 can be very difficult to track down. Compiling with -DDEBUG_LOCKORDER (configure
132 CXXFLAGS="-DDEBUG_LOCKORDER -g") inserts run-time checks to keep track of which locks
133 are held, and adds warnings to the debug.log file if inconsistencies are detected.
135 Locking/mutex usage notes
136 -------------------------
138 The code is multi-threaded, and uses mutexes and the
139 LOCK/TRY_LOCK macros to protect data structures.
141 Deadlocks due to inconsistent lock ordering (thread 1 locks cs_main
142 and then cs_wallet, while thread 2 locks them in the opposite order:
143 result, deadlock as each waits for the other to release its lock) are
144 a problem. Compile with -DDEBUG_LOCKORDER to get lock order
145 inconsistencies reported in the debug.log file.
147 Re-architecting the core code so there are better-defined interfaces
148 between the various components is a goal, with any necessary locking
149 done by the components (e.g. see the self-contained CKeyStore class
150 and its cs_KeyStore lock for example).
152 Threads
153 -------
155 - ThreadScriptCheck : Verifies block scripts.
157 - ThreadImport : Loads blocks from blk*.dat files or bootstrap.dat.
159 - StartNode : Starts other threads.
161 - ThreadDNSAddressSeed : Loads addresses of peers from the DNS.
163 - ThreadMapPort : Universal plug-and-play startup/shutdown
165 - ThreadSocketHandler : Sends/Receives data from peers on port 8333.
167 - ThreadOpenAddedConnections : Opens network connections to added nodes.
169 - ThreadOpenConnections : Initiates new connections to peers.
171 - ThreadMessageHandler : Higher-level message handling (sending and receiving).
173 - DumpAddresses : Dumps IP addresses of nodes to peers.dat.
175 - ThreadFlushWalletDB : Close the wallet.dat file if it hasn't been used in 500ms.
177 - ThreadRPCServer : Remote procedure call handler, listens on port 8332 for connections and services them.
179 - BitcoinMiner : Generates bitcoins (if wallet is enabled).
181 - Shutdown : Does an orderly shutdown of everything.
183 Ignoring IDE/editor files
184 --------------------------
186 In closed-source environments in which everyone uses the same IDE it is common
187 to add temporary files it produces to the project-wide `.gitignore` file.
189 However, in open source software such as Bitcoin Core, where everyone uses
190 their own editors/IDE/tools, it is less common. Only you know what files your
191 editor produces and this may change from version to version. The canonical way
192 to do this is thus to create your local gitignore. Add this to `~/.gitconfig`:
195 [core]
196         excludesfile = /home/.../.gitignore_global
199 (alternatively, type the command `git config --global core.excludesfile ~/.gitignore_global`
200 on a terminal)
202 Then put your favourite tool's temporary filenames in that file, e.g.
204 # NetBeans
205 nbproject/
208 Another option is to create a per-repository excludes file `.git/info/exclude`.
209 These are not committed but apply only to one repository.
211 If a set of tools is used by the build system or scripts the repository (for
212 example, lcov) it is perfectly acceptable to add its files to `.gitignore`
213 and commit them.
215 Development guidelines
216 ============================
218 A few non-style-related recommendations for developers, as well as points to
219 pay attention to for reviewers of Bitcoin Core code.
221 General Bitcoin Core
222 ----------------------
224 - New features should be exposed on RPC first, then can be made available in the GUI
226   - *Rationale*: RPC allows for better automatic testing. The test suite for
227     the GUI is very limited
229 - Make sure pull requests pass Travis CI before merging
231   - *Rationale*: Makes sure that they pass thorough testing, and that the tester will keep passing
232      on the master branch. Otherwise all new pull requests will start failing the tests, resulting in
233      confusion and mayhem
235   - *Explanation*: If the test suite is to be updated for a change, this has to
236     be done first 
238 Wallet
239 -------
241 - Make sure that no crashes happen with run-time option `-disablewallet`.
243   - *Rationale*: In RPC code that conditionally uses the wallet (such as
244     `validateaddress`) it is easy to forget that global pointer `pwalletMain`
245     can be NULL. See `qa/rpc-tests/disablewallet.py` for functional tests
246     exercising the API with `-disablewallet`
248 - Include `db_cxx.h` (BerkeleyDB header) only when `ENABLE_WALLET` is set
250   - *Rationale*: Otherwise compilation of the disable-wallet build will fail in environments without BerkeleyDB
252 General C++
253 -------------
255 - Assertions should not have side-effects
257   - *Rationale*: Even though the source code is set to to refuse to compile
258     with assertions disabled, having side-effects in assertions is unexpected and
259     makes the code harder to understand
261 - If you use the `.h`, you must link the `.cpp`
263   - *Rationale*: Include files define the interface for the code in implementation files. Including one but
264       not linking the other is confusing. Please avoid that. Moving functions from
265       the `.h` to the `.cpp` should not result in build errors
267 - Use the RAII (Resource Acquisition Is Initialization) paradigm where possible. For example by using
268   `unique_ptr` for allocations in a function.
270   - *Rationale*: This avoids memory and resource leaks, and ensures exception safety
272 C++ data structures
273 --------------------
275 - Never use the `std::map []` syntax when reading from a map, but instead use `.find()`
277   - *Rationale*: `[]` does an insert (of the default element) if the item doesn't
278     exist in the map yet. This has resulted in memory leaks in the past, as well as
279     race conditions (expecting read-read behavior). Using `[]` is fine for *writing* to a map
281 - Do not compare an iterator from one data structure with an iterator of
282   another data structure (even if of the same type)
284   - *Rationale*: Behavior is undefined. In C++ parlor this means "may reformat
285     the universe", in practice this has resulted in at least one hard-to-debug crash bug
287 - Watch out for out-of-bounds vector access. `&vch[vch.size()]` is illegal,
288   including `&vch[0]` for an empty vector. Use `vch.data()` and `vch.data() +
289   vch.size()` instead.
291 - Vector bounds checking is only enabled in debug mode. Do not rely on it
293 - Make sure that constructors initialize all fields. If this is skipped for a
294   good reason (i.e., optimization on the critical path), add an explicit
295   comment about this
297   - *Rationale*: Ensure determinism by avoiding accidental use of uninitialized
298     values. Also, static analyzers balk about this.
300 - Use explicitly signed or unsigned `char`s, or even better `uint8_t` and
301   `int8_t`. Do not use bare `char` unless it is to pass to a third-party API.
302   This type can be signed or unsigned depending on the architecture, which can
303   lead to interoperability problems or dangerous conditions such as
304   out-of-bounds array accesses
306 - Prefer explicit constructions over implicit ones that rely on 'magical' C++ behavior
308   - *Rationale*: Easier to understand what is happening, thus easier to spot mistakes, even for those
309   that are not language lawyers
311 Strings and formatting
312 ------------------------
314 - Be careful of `LogPrint` versus `LogPrintf`. `LogPrint` takes a `category` argument, `LogPrintf` does not.
316   - *Rationale*: Confusion of these can result in runtime exceptions due to
317     formatting mismatch, and it is easy to get wrong because of subtly similar naming
319 - Use `std::string`, avoid C string manipulation functions
321   - *Rationale*: C++ string handling is marginally safer, less scope for
322     buffer overflows and surprises with `\0` characters. Also some C string manipulations
323     tend to act differently depending on platform, or even the user locale
325 - Use `ParseInt32`, `ParseInt64`, `ParseUInt32`, `ParseUInt64`, `ParseDouble` from `utilstrencodings.h` for number parsing
327   - *Rationale*: These functions do overflow checking, and avoid pesky locale issues
329 - For `strprintf`, `LogPrint`, `LogPrintf` formatting characters don't need size specifiers
331   - *Rationale*: Bitcoin Core uses tinyformat, which is type safe. Leave them out to avoid confusion
333 Threads and synchronization
334 ----------------------------
336 - Build and run tests with `-DDEBUG_LOCKORDER` to verify that no potential
337   deadlocks are introduced. As of 0.12, this is defined by default when
338   configuring with `--enable-debug`
340 - When using `LOCK`/`TRY_LOCK` be aware that the lock exists in the context of
341   the current scope, so surround the statement and the code that needs the lock
342   with braces
344   OK:
346 ```c++
348     TRY_LOCK(cs_vNodes, lockNodes);
349     ...
353   Wrong:
355 ```c++
356 TRY_LOCK(cs_vNodes, lockNodes);
358     ...
362 Source code organization
363 --------------------------
365 - Implementation code should go into the `.cpp` file and not the `.h`, unless necessary due to template usage or
366   when performance due to inlining is critical
368   - *Rationale*: Shorter and simpler header files are easier to read, and reduce compile time
370 - Don't import anything into the global namespace (`using namespace ...`). Use
371   fully specified types such as `std::string`.
373   - *Rationale*: Avoids symbol conflicts
376 -----
378 - Do not display or manipulate dialogs in model code (classes `*Model`)
380   - *Rationale*: Model classes pass through events and data from the core, they
381     should not interact with the user. That's where View classes come in. The converse also
382     holds: try to not directly access core data structures from Views.
384 Git and github tips
385 ---------------------
387 - For resolving merge/rebase conflicts, it can be useful to enable diff3 style using
388   `git config merge.conflictstyle diff3`. Instead of
390         <<<
391         yours
392         ===
393         theirs
394         >>>
396   you will see
398         <<<
399         yours
400         |||
401         original
402         ===
403         theirs
404         >>>
406   This may make it much clearer what caused the conflict. In this style, you can often just look
407   at what changed between *original* and *theirs*, and mechanically apply that to *yours* (or the other way around).
409 - When reviewing patches which change indentation in C++ files, use `git diff -w` and `git show -w`. This makes
410   the diff algorithm ignore whitespace changes. This feature is also available on github.com, by adding `?w=1`
411   at the end of any URL which shows a diff.
413 - When reviewing patches that change symbol names in many places, use `git diff --word-diff`. This will instead
414   of showing the patch as deleted/added *lines*, show deleted/added *words*.
416 - When reviewing patches that move code around, try using
417   `git diff --patience commit~:old/file.cpp commit:new/file/name.cpp`, and ignoring everything except the
418   moved body of code which should show up as neither `+` or `-` lines. In case it was not a pure move, this may
419   even work when combined with the `-w` or `--word-diff` options described above.
421 - When looking at other's pull requests, it may make sense to add the following section to your `.git/config`
422   file:
424         [remote "upstream-pull"]
425                 fetch = +refs/pull/*:refs/remotes/upstream-pull/*
426                 url = git@github.com:bitcoin/bitcoin.git
428   This will add an `upstream-pull` remote to your git repository, which can be fetched using `git fetch --all`
429   or `git fetch upstream-pull`. Afterwards, you can use `upstream-pull/NUMBER/head` in arguments to `git show`,
430   `git checkout` and anywhere a commit id would be acceptable to see the changes from pull request NUMBER.