Add note about Valgrind suppressions file in developer-notes.md
[bitcoinplatinum.git] / doc / developer-notes.md
blobde0026a0a50750b0f5959167858d9b1c87554187
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, which is specified below. When writing patches, favor the new
7 style over attempting to mimick the surrounding style, except for move-only
8 commits.
10 Do not submit patches solely to modify the style of existing code.
12 - **Indentation and whitespace rules** as specified in
13 [src/.clang-format](/src/.clang-format). You can use the provided
14 [clang-format-diff script](/contrib/devtools/README.md#clang-format-diffpy)
15 tool to clean up patches automatically before submission.
16   - Braces on new lines for namespaces, classes, functions, methods.
17   - Braces on the same line for everything else.
18   - 4 space indentation (no tabs) for every block except namespaces.
19   - No indentation for `public`/`protected`/`private` or for `namespace`.
20   - No extra spaces inside parenthesis; don't do ( this )
21   - No space after function names; one space after `if`, `for` and `while`.
22   - If an `if` only has a single-statement `then`-clause, it can appear
23     on the same line as the `if`, without braces. In every other case,
24     braces are required, and the `then` and `else` clauses must appear
25     correctly indented on a new line.
27 - **Symbol naming conventions**. These are preferred in new code, but are not
28 required when doing so would need changes to significant pieces of existing
29 code.
30   - Variable and namespace names are all lowercase, and may use `_` to
31     separate words (snake_case).
32     - Class member variables have a `m_` prefix.
33     - Global variables have a `g_` prefix.
34   - Constant names are all uppercase, and use `_` to separate words.
35   - Class names, function names and method names are UpperCamelCase
36     (PascalCase). Do not prefix class names with `C`.
38 - **Miscellaneous**
39   - `++i` is preferred over `i++`.
41 Block style example:
42 ```c++
43 int g_count = 0;
45 namespace foo
47 class Class
49     std::string m_name;
51 public:
52     bool Function(const std::string& s, int n)
53     {
54         // Comment summarising what this section of code does
55         for (int i = 0; i < n; ++i) {
56             int total_sum = 0;
57             // When something fails, return early
58             if (!Something()) return false;
59             ...
60             if (SomethingElse(i)) {
61                 total_sum += ComputeSomething(g_count);
62             } else {
63                 DoSomething(m_name, total_sum);
64             }
65         }
67         // Success return is usually at the end
68         return true;
69     }
71 } // namespace foo
72 ```
74 Doxygen comments
75 -----------------
77 To facilitate the generation of documentation, use doxygen-compatible comment blocks for functions, methods and fields.
79 For example, to describe a function use:
80 ```c++
81 /**
82  * ... text ...
83  * @param[in] arg1    A description
84  * @param[in] arg2    Another argument description
85  * @pre Precondition for function...
86  */
87 bool function(int arg1, const char *arg2)
88 ```
89 A complete list of `@xxx` commands can be found at http://www.stack.nl/~dimitri/doxygen/manual/commands.html.
90 As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't
91 *need* to provide any commands for a comment to be valid; just a description text is fine.
93 To describe a class use the same construct above the class definition:
94 ```c++
95 /**
96  * Alerts are for notifying old versions if they become too obsolete and
97  * need to upgrade. The message is displayed in the status bar.
98  * @see GetWarnings()
99  */
100 class CAlert
104 To describe a member or variable use:
105 ```c++
106 int var; //!< Detailed description after the member
110 ```cpp
111 //! Description before the member
112 int var;
115 Also OK:
116 ```c++
118 /// ... text ...
120 bool function2(int arg1, const char *arg2)
123 Not OK (used plenty in the current source, but not picked up):
124 ```c++
126 // ... text ...
130 A full list of comment syntaxes picked up by doxygen can be found at http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html,
131 but if possible use one of the above styles.
133 Development tips and tricks
134 ---------------------------
136 **compiling for debugging**
138 Run configure with the --enable-debug option, then make. Or run configure with
139 CXXFLAGS="-g -ggdb -O0" or whatever debug flags you need.
141 **debug.log**
143 If the code is behaving strangely, take a look in the debug.log file in the data directory;
144 error and debugging messages are written there.
146 The -debug=... command-line option controls debugging; running with just -debug or -debug=1 will turn
147 on all categories (and give you a very large debug.log file).
149 The Qt code routes qDebug() output to debug.log under category "qt": run with -debug=qt
150 to see it.
152 **testnet and regtest modes**
154 Run with the -testnet option to run with "play bitcoins" on the test network, if you
155 are testing multi-machine code that needs to operate across the internet.
157 If you are testing something that can run on one machine, run with the -regtest option.
158 In regression test mode, blocks can be created on-demand; see test/functional/ for tests
159 that run in -regtest mode.
161 **DEBUG_LOCKORDER**
163 Bitcoin Core is a multithreaded application, and deadlocks or other multithreading bugs
164 can be very difficult to track down. Compiling with -DDEBUG_LOCKORDER (configure
165 CXXFLAGS="-DDEBUG_LOCKORDER -g") inserts run-time checks to keep track of which locks
166 are held, and adds warnings to the debug.log file if inconsistencies are detected.
168 **Valgrind suppressions file**
170 Valgrind is a programming tool for memory debugging, memory leak detection, and
171 profiling. The repo contains a Valgrind suppressions file
172 ([`valgrind.supp`](https://github.com/bitcoin/bitcoin/blob/master/contrib/valgrind.supp))
173 which includes known Valgrind warnings in our dependencies that cannot be fixed
174 in-tree. Example use:
176 ```shell
177 $ valgrind --suppressions=contrib/valgrind.supp src/test/test_bitcoin
178 $ valgrind --suppressions=contrib/valgrind.supp --leak-check=full \
179       --show-leak-kinds=all src/test/test_bitcoin --log_level=test_suite
180 $ valgrind -v --leak-check=full src/bitcoind -printtoconsole
183 Locking/mutex usage notes
184 -------------------------
186 The code is multi-threaded, and uses mutexes and the
187 LOCK/TRY_LOCK macros to protect data structures.
189 Deadlocks due to inconsistent lock ordering (thread 1 locks cs_main
190 and then cs_wallet, while thread 2 locks them in the opposite order:
191 result, deadlock as each waits for the other to release its lock) are
192 a problem. Compile with -DDEBUG_LOCKORDER to get lock order
193 inconsistencies reported in the debug.log file.
195 Re-architecting the core code so there are better-defined interfaces
196 between the various components is a goal, with any necessary locking
197 done by the components (e.g. see the self-contained CKeyStore class
198 and its cs_KeyStore lock for example).
200 Threads
201 -------
203 - ThreadScriptCheck : Verifies block scripts.
205 - ThreadImport : Loads blocks from blk*.dat files or bootstrap.dat.
207 - StartNode : Starts other threads.
209 - ThreadDNSAddressSeed : Loads addresses of peers from the DNS.
211 - ThreadMapPort : Universal plug-and-play startup/shutdown
213 - ThreadSocketHandler : Sends/Receives data from peers on port 8333.
215 - ThreadOpenAddedConnections : Opens network connections to added nodes.
217 - ThreadOpenConnections : Initiates new connections to peers.
219 - ThreadMessageHandler : Higher-level message handling (sending and receiving).
221 - DumpAddresses : Dumps IP addresses of nodes to peers.dat.
223 - ThreadFlushWalletDB : Close the wallet.dat file if it hasn't been used in 500ms.
225 - ThreadRPCServer : Remote procedure call handler, listens on port 8332 for connections and services them.
227 - BitcoinMiner : Generates bitcoins (if wallet is enabled).
229 - Shutdown : Does an orderly shutdown of everything.
231 Ignoring IDE/editor files
232 --------------------------
234 In closed-source environments in which everyone uses the same IDE it is common
235 to add temporary files it produces to the project-wide `.gitignore` file.
237 However, in open source software such as Bitcoin Core, where everyone uses
238 their own editors/IDE/tools, it is less common. Only you know what files your
239 editor produces and this may change from version to version. The canonical way
240 to do this is thus to create your local gitignore. Add this to `~/.gitconfig`:
243 [core]
244         excludesfile = /home/.../.gitignore_global
247 (alternatively, type the command `git config --global core.excludesfile ~/.gitignore_global`
248 on a terminal)
250 Then put your favourite tool's temporary filenames in that file, e.g.
252 # NetBeans
253 nbproject/
256 Another option is to create a per-repository excludes file `.git/info/exclude`.
257 These are not committed but apply only to one repository.
259 If a set of tools is used by the build system or scripts the repository (for
260 example, lcov) it is perfectly acceptable to add its files to `.gitignore`
261 and commit them.
263 Development guidelines
264 ============================
266 A few non-style-related recommendations for developers, as well as points to
267 pay attention to for reviewers of Bitcoin Core code.
269 General Bitcoin Core
270 ----------------------
272 - New features should be exposed on RPC first, then can be made available in the GUI
274   - *Rationale*: RPC allows for better automatic testing. The test suite for
275     the GUI is very limited
277 - Make sure pull requests pass Travis CI before merging
279   - *Rationale*: Makes sure that they pass thorough testing, and that the tester will keep passing
280      on the master branch. Otherwise all new pull requests will start failing the tests, resulting in
281      confusion and mayhem
283   - *Explanation*: If the test suite is to be updated for a change, this has to
284     be done first
286 Wallet
287 -------
289 - Make sure that no crashes happen with run-time option `-disablewallet`.
291   - *Rationale*: In RPC code that conditionally uses the wallet (such as
292     `validateaddress`) it is easy to forget that global pointer `pwalletMain`
293     can be NULL. See `test/functional/disablewallet.py` for functional tests
294     exercising the API with `-disablewallet`
296 - Include `db_cxx.h` (BerkeleyDB header) only when `ENABLE_WALLET` is set
298   - *Rationale*: Otherwise compilation of the disable-wallet build will fail in environments without BerkeleyDB
300 General C++
301 -------------
303 - Assertions should not have side-effects
305   - *Rationale*: Even though the source code is set to refuse to compile
306     with assertions disabled, having side-effects in assertions is unexpected and
307     makes the code harder to understand
309 - If you use the `.h`, you must link the `.cpp`
311   - *Rationale*: Include files define the interface for the code in implementation files. Including one but
312       not linking the other is confusing. Please avoid that. Moving functions from
313       the `.h` to the `.cpp` should not result in build errors
315 - Use the RAII (Resource Acquisition Is Initialization) paradigm where possible. For example by using
316   `unique_ptr` for allocations in a function.
318   - *Rationale*: This avoids memory and resource leaks, and ensures exception safety
320 C++ data structures
321 --------------------
323 - Never use the `std::map []` syntax when reading from a map, but instead use `.find()`
325   - *Rationale*: `[]` does an insert (of the default element) if the item doesn't
326     exist in the map yet. This has resulted in memory leaks in the past, as well as
327     race conditions (expecting read-read behavior). Using `[]` is fine for *writing* to a map
329 - Do not compare an iterator from one data structure with an iterator of
330   another data structure (even if of the same type)
332   - *Rationale*: Behavior is undefined. In C++ parlor this means "may reformat
333     the universe", in practice this has resulted in at least one hard-to-debug crash bug
335 - Watch out for out-of-bounds vector access. `&vch[vch.size()]` is illegal,
336   including `&vch[0]` for an empty vector. Use `vch.data()` and `vch.data() +
337   vch.size()` instead.
339 - Vector bounds checking is only enabled in debug mode. Do not rely on it
341 - Make sure that constructors initialize all fields. If this is skipped for a
342   good reason (i.e., optimization on the critical path), add an explicit
343   comment about this
345   - *Rationale*: Ensure determinism by avoiding accidental use of uninitialized
346     values. Also, static analyzers balk about this.
348 - Use explicitly signed or unsigned `char`s, or even better `uint8_t` and
349   `int8_t`. Do not use bare `char` unless it is to pass to a third-party API.
350   This type can be signed or unsigned depending on the architecture, which can
351   lead to interoperability problems or dangerous conditions such as
352   out-of-bounds array accesses
354 - Prefer explicit constructions over implicit ones that rely on 'magical' C++ behavior
356   - *Rationale*: Easier to understand what is happening, thus easier to spot mistakes, even for those
357   that are not language lawyers
359 Strings and formatting
360 ------------------------
362 - Be careful of `LogPrint` versus `LogPrintf`. `LogPrint` takes a `category` argument, `LogPrintf` does not.
364   - *Rationale*: Confusion of these can result in runtime exceptions due to
365     formatting mismatch, and it is easy to get wrong because of subtly similar naming
367 - Use `std::string`, avoid C string manipulation functions
369   - *Rationale*: C++ string handling is marginally safer, less scope for
370     buffer overflows and surprises with `\0` characters. Also some C string manipulations
371     tend to act differently depending on platform, or even the user locale
373 - Use `ParseInt32`, `ParseInt64`, `ParseUInt32`, `ParseUInt64`, `ParseDouble` from `utilstrencodings.h` for number parsing
375   - *Rationale*: These functions do overflow checking, and avoid pesky locale issues
377 - For `strprintf`, `LogPrint`, `LogPrintf` formatting characters don't need size specifiers
379   - *Rationale*: Bitcoin Core uses tinyformat, which is type safe. Leave them out to avoid confusion
381 Variable names
382 --------------
384 Although the shadowing warning (`-Wshadow`) is not enabled by default (it prevents issues rising
385 from using a different variable with the same name),
386 please name variables so that their names do not shadow variables defined in the source code.
388 E.g. in member initializers, prepend `_` to the argument name shadowing the
389 member name:
391 ```c++
392 class AddressBookPage
394     Mode mode;
397 AddressBookPage::AddressBookPage(Mode _mode) :
398       mode(_mode)
402 When using nested cycles, do not name the inner cycle variable the same as in
403 upper cycle etc.
406 Threads and synchronization
407 ----------------------------
409 - Build and run tests with `-DDEBUG_LOCKORDER` to verify that no potential
410   deadlocks are introduced. As of 0.12, this is defined by default when
411   configuring with `--enable-debug`
413 - When using `LOCK`/`TRY_LOCK` be aware that the lock exists in the context of
414   the current scope, so surround the statement and the code that needs the lock
415   with braces
417   OK:
419 ```c++
421     TRY_LOCK(cs_vNodes, lockNodes);
422     ...
426   Wrong:
428 ```c++
429 TRY_LOCK(cs_vNodes, lockNodes);
431     ...
435 Source code organization
436 --------------------------
438 - Implementation code should go into the `.cpp` file and not the `.h`, unless necessary due to template usage or
439   when performance due to inlining is critical
441   - *Rationale*: Shorter and simpler header files are easier to read, and reduce compile time
443 - Every `.cpp` and `.h` file should `#include` every header file it directly uses classes, functions or other
444   definitions from, even if those headers are already included indirectly through other headers. One exception
445   is that a `.cpp` file does not need to re-include the includes already included in its corresponding `.h` file.
447   - *Rationale*: Excluding headers because they are already indirectly included results in compilation
448     failures when those indirect dependencies change. Furthermore, it obscures what the real code
449     dependencies are.
451 - Don't import anything into the global namespace (`using namespace ...`). Use
452   fully specified types such as `std::string`.
454   - *Rationale*: Avoids symbol conflicts
456 - Terminate namespaces with a comment (`// namespace mynamespace`). The comment
457   should be placed on the same line as the brace closing the namespace, e.g.
459 ```c++
460 namespace mynamespace {
461     ...
462 } // namespace mynamespace
464 namespace {
465     ...
466 } // namespace
469   - *Rationale*: Avoids confusion about the namespace context
472 -----
474 - Do not display or manipulate dialogs in model code (classes `*Model`)
476   - *Rationale*: Model classes pass through events and data from the core, they
477     should not interact with the user. That's where View classes come in. The converse also
478     holds: try to not directly access core data structures from Views.
480 Subtrees
481 ----------
483 Several parts of the repository are subtrees of software maintained elsewhere.
485 Some of these are maintained by active developers of Bitcoin Core, in which case changes should probably go
486 directly upstream without being PRed directly against the project.  They will be merged back in the next
487 subtree merge.
489 Others are external projects without a tight relationship with our project.  Changes to these should also
490 be sent upstream but bugfixes may also be prudent to PR against Bitcoin Core so that they can be integrated
491 quickly.  Cosmetic changes should be purely taken upstream.
493 There is a tool in contrib/devtools/git-subtree-check.sh to check a subtree directory for consistency with
494 its upstream repository.
496 Current subtrees include:
498 - src/leveldb
499   - Upstream at https://github.com/google/leveldb ; Maintained by Google, but open important PRs to Core to avoid delay
501 - src/libsecp256k1
502   - Upstream at https://github.com/bitcoin-core/secp256k1/ ; actively maintaned by Core contributors.
504 - src/crypto/ctaes
505   - Upstream at https://github.com/bitcoin-core/ctaes ; actively maintained by Core contributors.
507 - src/univalue
508   - Upstream at https://github.com/jgarzik/univalue ; report important PRs to Core to avoid delay.
511 Git and GitHub tips
512 ---------------------
514 - For resolving merge/rebase conflicts, it can be useful to enable diff3 style using
515   `git config merge.conflictstyle diff3`. Instead of
517         <<<
518         yours
519         ===
520         theirs
521         >>>
523   you will see
525         <<<
526         yours
527         |||
528         original
529         ===
530         theirs
531         >>>
533   This may make it much clearer what caused the conflict. In this style, you can often just look
534   at what changed between *original* and *theirs*, and mechanically apply that to *yours* (or the other way around).
536 - When reviewing patches which change indentation in C++ files, use `git diff -w` and `git show -w`. This makes
537   the diff algorithm ignore whitespace changes. This feature is also available on github.com, by adding `?w=1`
538   at the end of any URL which shows a diff.
540 - When reviewing patches that change symbol names in many places, use `git diff --word-diff`. This will instead
541   of showing the patch as deleted/added *lines*, show deleted/added *words*.
543 - When reviewing patches that move code around, try using
544   `git diff --patience commit~:old/file.cpp commit:new/file/name.cpp`, and ignoring everything except the
545   moved body of code which should show up as neither `+` or `-` lines. In case it was not a pure move, this may
546   even work when combined with the `-w` or `--word-diff` options described above.
548 - When looking at other's pull requests, it may make sense to add the following section to your `.git/config`
549   file:
551         [remote "upstream-pull"]
552                 fetch = +refs/pull/*:refs/remotes/upstream-pull/*
553                 url = git@github.com:bitcoin/bitcoin.git
555   This will add an `upstream-pull` remote to your git repository, which can be fetched using `git fetch --all`
556   or `git fetch upstream-pull`. Afterwards, you can use `upstream-pull/NUMBER/head` in arguments to `git show`,
557   `git checkout` and anywhere a commit id would be acceptable to see the changes from pull request NUMBER.
559 RPC interface guidelines
560 --------------------------
562 A few guidelines for introducing and reviewing new RPC interfaces:
564 - Method naming: use consecutive lower-case names such as `getrawtransaction` and `submitblock`
566   - *Rationale*: Consistency with existing interface.
568 - Argument naming: use snake case `fee_delta` (and not, e.g. camel case `feeDelta`)
570   - *Rationale*: Consistency with existing interface.
572 - Use the JSON parser for parsing, don't manually parse integers or strings from
573   arguments unless absolutely necessary.
575   - *Rationale*: Introduces hand-rolled string manipulation code at both the caller and callee sites,
576     which is error prone, and it is easy to get things such as escaping wrong.
577     JSON already supports nested data structures, no need to re-invent the wheel.
579   - *Exception*: AmountFromValue can parse amounts as string. This was introduced because many JSON
580     parsers and formatters hard-code handling decimal numbers as floating point
581     values, resulting in potential loss of precision. This is unacceptable for
582     monetary values. **Always** use `AmountFromValue` and `ValueFromAmount` when
583     inputting or outputting monetary values. The only exceptions to this are
584     `prioritisetransaction` and `getblocktemplate` because their interface
585     is specified as-is in BIP22.
587 - Missing arguments and 'null' should be treated the same: as default values. If there is no
588   default value, both cases should fail in the same way.
590   - *Rationale*: Avoids surprises when switching to name-based arguments. Missing name-based arguments
591   are passed as 'null'.
593   - *Exception*: Many legacy exceptions to this exist, one of the worst ones is
594     `getbalance` which follows a completely different code path based on the
595     number of arguments. We are still in the process of cleaning these up. Do not introduce
596     new ones.
598 - Try not to overload methods on argument type. E.g. don't make `getblock(true)` and `getblock("hash")`
599   do different things.
601   - *Rationale*: This is impossible to use with `bitcoin-cli`, and can be surprising to users.
603   - *Exception*: Some RPC calls can take both an `int` and `bool`, most notably when a bool was switched
604     to a multi-value, or due to other historical reasons. **Always** have false map to 0 and
605     true to 1 in this case.
607 - Don't forget to fill in the argument names correctly in the RPC command table.
609   - *Rationale*: If not, the call can not be used with name-based arguments.
611 - Set okSafeMode in the RPC command table to a sensible value: safe mode is when the
612   blockchain is regarded to be in a confused state, and the client deems it unsafe to
613   do anything irreversible such as send. Anything that just queries should be permitted.
615   - *Rationale*: Troubleshooting a node in safe mode is difficult if half the
616     RPCs don't work.
618 - Add every non-string RPC argument `(method, idx, name)` to the table `vRPCConvertParams` in `rpc/client.cpp`.
620   - *Rationale*: `bitcoin-cli` and the GUI debug console use this table to determine how to
621     convert a plaintext command line to JSON. If the types don't match, the method can be unusable
622     from there.
624 - A RPC method must either be a wallet method or a non-wallet method. Do not
625   introduce new methods such as `getinfo` and `signrawtransaction` that differ
626   in behavior based on presence of a wallet.
628   - *Rationale*: as well as complicating the implementation and interfering
629     with the introduction of multi-wallet, wallet and non-wallet code should be
630     separated to avoid introducing circular dependencies between code units.