Merge #11035: [contrib] Add Valgrind suppressions file
[bitcoinplatinum.git] / doc / developer-notes.md
blob763ab054caea96f9cf7dc5210dbfb11b65dae68c
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 mimic 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++`.
40   - `nullptr` is preferred over `NULL` or `(void*)0`.
41   - `static_assert` is preferred over `assert` where possible. Generally; compile-time checking is preferred over run-time checking.
43 Block style example:
44 ```c++
45 int g_count = 0;
47 namespace foo
49 class Class
51     std::string m_name;
53 public:
54     bool Function(const std::string& s, int n)
55     {
56         // Comment summarising what this section of code does
57         for (int i = 0; i < n; ++i) {
58             int total_sum = 0;
59             // When something fails, return early
60             if (!Something()) return false;
61             ...
62             if (SomethingElse(i)) {
63                 total_sum += ComputeSomething(g_count);
64             } else {
65                 DoSomething(m_name, total_sum);
66             }
67         }
69         // Success return is usually at the end
70         return true;
71     }
73 } // namespace foo
74 ```
76 Doxygen comments
77 -----------------
79 To facilitate the generation of documentation, use doxygen-compatible comment blocks for functions, methods and fields.
81 For example, to describe a function use:
82 ```c++
83 /**
84  * ... text ...
85  * @param[in] arg1    A description
86  * @param[in] arg2    Another argument description
87  * @pre Precondition for function...
88  */
89 bool function(int arg1, const char *arg2)
90 ```
91 A complete list of `@xxx` commands can be found at http://www.stack.nl/~dimitri/doxygen/manual/commands.html.
92 As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't
93 *need* to provide any commands for a comment to be valid; just a description text is fine.
95 To describe a class use the same construct above the class definition:
96 ```c++
97 /**
98  * Alerts are for notifying old versions if they become too obsolete and
99  * need to upgrade. The message is displayed in the status bar.
100  * @see GetWarnings()
101  */
102 class CAlert
106 To describe a member or variable use:
107 ```c++
108 int var; //!< Detailed description after the member
112 ```cpp
113 //! Description before the member
114 int var;
117 Also OK:
118 ```c++
120 /// ... text ...
122 bool function2(int arg1, const char *arg2)
125 Not OK (used plenty in the current source, but not picked up):
126 ```c++
128 // ... text ...
132 A full list of comment syntaxes picked up by doxygen can be found at http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html,
133 but if possible use one of the above styles.
135 Development tips and tricks
136 ---------------------------
138 **compiling for debugging**
140 Run configure with the --enable-debug option, then make. Or run configure with
141 CXXFLAGS="-g -ggdb -O0" or whatever debug flags you need.
143 **debug.log**
145 If the code is behaving strangely, take a look in the debug.log file in the data directory;
146 error and debugging messages are written there.
148 The -debug=... command-line option controls debugging; running with just -debug or -debug=1 will turn
149 on all categories (and give you a very large debug.log file).
151 The Qt code routes qDebug() output to debug.log under category "qt": run with -debug=qt
152 to see it.
154 **testnet and regtest modes**
156 Run with the -testnet option to run with "play bitcoins" on the test network, if you
157 are testing multi-machine code that needs to operate across the internet.
159 If you are testing something that can run on one machine, run with the -regtest option.
160 In regression test mode, blocks can be created on-demand; see test/functional/ for tests
161 that run in -regtest mode.
163 **DEBUG_LOCKORDER**
165 Bitcoin Core is a multithreaded application, and deadlocks or other multithreading bugs
166 can be very difficult to track down. Compiling with -DDEBUG_LOCKORDER (configure
167 CXXFLAGS="-DDEBUG_LOCKORDER -g") inserts run-time checks to keep track of which locks
168 are held, and adds warnings to the debug.log file if inconsistencies are detected.
170 **Valgrind suppressions file**
172 Valgrind is a programming tool for memory debugging, memory leak detection, and
173 profiling. The repo contains a Valgrind suppressions file
174 ([`valgrind.supp`](https://github.com/bitcoin/bitcoin/blob/master/contrib/valgrind.supp))
175 which includes known Valgrind warnings in our dependencies that cannot be fixed
176 in-tree. Example use:
178 ```shell
179 $ valgrind --suppressions=contrib/valgrind.supp src/test/test_bitcoin
180 $ valgrind --suppressions=contrib/valgrind.supp --leak-check=full \
181       --show-leak-kinds=all src/test/test_bitcoin --log_level=test_suite
182 $ valgrind -v --leak-check=full src/bitcoind -printtoconsole
185 Locking/mutex usage notes
186 -------------------------
188 The code is multi-threaded, and uses mutexes and the
189 LOCK/TRY_LOCK macros to protect data structures.
191 Deadlocks due to inconsistent lock ordering (thread 1 locks cs_main
192 and then cs_wallet, while thread 2 locks them in the opposite order:
193 result, deadlock as each waits for the other to release its lock) are
194 a problem. Compile with -DDEBUG_LOCKORDER to get lock order
195 inconsistencies reported in the debug.log file.
197 Re-architecting the core code so there are better-defined interfaces
198 between the various components is a goal, with any necessary locking
199 done by the components (e.g. see the self-contained CKeyStore class
200 and its cs_KeyStore lock for example).
202 Threads
203 -------
205 - ThreadScriptCheck : Verifies block scripts.
207 - ThreadImport : Loads blocks from blk*.dat files or bootstrap.dat.
209 - StartNode : Starts other threads.
211 - ThreadDNSAddressSeed : Loads addresses of peers from the DNS.
213 - ThreadMapPort : Universal plug-and-play startup/shutdown
215 - ThreadSocketHandler : Sends/Receives data from peers on port 8333.
217 - ThreadOpenAddedConnections : Opens network connections to added nodes.
219 - ThreadOpenConnections : Initiates new connections to peers.
221 - ThreadMessageHandler : Higher-level message handling (sending and receiving).
223 - DumpAddresses : Dumps IP addresses of nodes to peers.dat.
225 - ThreadFlushWalletDB : Close the wallet.dat file if it hasn't been used in 500ms.
227 - ThreadRPCServer : Remote procedure call handler, listens on port 8332 for connections and services them.
229 - BitcoinMiner : Generates bitcoins (if wallet is enabled).
231 - Shutdown : Does an orderly shutdown of everything.
233 Ignoring IDE/editor files
234 --------------------------
236 In closed-source environments in which everyone uses the same IDE it is common
237 to add temporary files it produces to the project-wide `.gitignore` file.
239 However, in open source software such as Bitcoin Core, where everyone uses
240 their own editors/IDE/tools, it is less common. Only you know what files your
241 editor produces and this may change from version to version. The canonical way
242 to do this is thus to create your local gitignore. Add this to `~/.gitconfig`:
245 [core]
246         excludesfile = /home/.../.gitignore_global
249 (alternatively, type the command `git config --global core.excludesfile ~/.gitignore_global`
250 on a terminal)
252 Then put your favourite tool's temporary filenames in that file, e.g.
254 # NetBeans
255 nbproject/
258 Another option is to create a per-repository excludes file `.git/info/exclude`.
259 These are not committed but apply only to one repository.
261 If a set of tools is used by the build system or scripts the repository (for
262 example, lcov) it is perfectly acceptable to add its files to `.gitignore`
263 and commit them.
265 Development guidelines
266 ============================
268 A few non-style-related recommendations for developers, as well as points to
269 pay attention to for reviewers of Bitcoin Core code.
271 General Bitcoin Core
272 ----------------------
274 - New features should be exposed on RPC first, then can be made available in the GUI
276   - *Rationale*: RPC allows for better automatic testing. The test suite for
277     the GUI is very limited
279 - Make sure pull requests pass Travis CI before merging
281   - *Rationale*: Makes sure that they pass thorough testing, and that the tester will keep passing
282      on the master branch. Otherwise all new pull requests will start failing the tests, resulting in
283      confusion and mayhem
285   - *Explanation*: If the test suite is to be updated for a change, this has to
286     be done first
288 Wallet
289 -------
291 - Make sure that no crashes happen with run-time option `-disablewallet`.
293   - *Rationale*: In RPC code that conditionally uses the wallet (such as
294     `validateaddress`) it is easy to forget that global pointer `pwalletMain`
295     can be nullptr. See `test/functional/disablewallet.py` for functional tests
296     exercising the API with `-disablewallet`
298 - Include `db_cxx.h` (BerkeleyDB header) only when `ENABLE_WALLET` is set
300   - *Rationale*: Otherwise compilation of the disable-wallet build will fail in environments without BerkeleyDB
302 General C++
303 -------------
305 - Assertions should not have side-effects
307   - *Rationale*: Even though the source code is set to refuse to compile
308     with assertions disabled, having side-effects in assertions is unexpected and
309     makes the code harder to understand
311 - If you use the `.h`, you must link the `.cpp`
313   - *Rationale*: Include files define the interface for the code in implementation files. Including one but
314       not linking the other is confusing. Please avoid that. Moving functions from
315       the `.h` to the `.cpp` should not result in build errors
317 - Use the RAII (Resource Acquisition Is Initialization) paradigm where possible. For example by using
318   `unique_ptr` for allocations in a function.
320   - *Rationale*: This avoids memory and resource leaks, and ensures exception safety
322 C++ data structures
323 --------------------
325 - Never use the `std::map []` syntax when reading from a map, but instead use `.find()`
327   - *Rationale*: `[]` does an insert (of the default element) if the item doesn't
328     exist in the map yet. This has resulted in memory leaks in the past, as well as
329     race conditions (expecting read-read behavior). Using `[]` is fine for *writing* to a map
331 - Do not compare an iterator from one data structure with an iterator of
332   another data structure (even if of the same type)
334   - *Rationale*: Behavior is undefined. In C++ parlor this means "may reformat
335     the universe", in practice this has resulted in at least one hard-to-debug crash bug
337 - Watch out for out-of-bounds vector access. `&vch[vch.size()]` is illegal,
338   including `&vch[0]` for an empty vector. Use `vch.data()` and `vch.data() +
339   vch.size()` instead.
341 - Vector bounds checking is only enabled in debug mode. Do not rely on it
343 - Make sure that constructors initialize all fields. If this is skipped for a
344   good reason (i.e., optimization on the critical path), add an explicit
345   comment about this
347   - *Rationale*: Ensure determinism by avoiding accidental use of uninitialized
348     values. Also, static analyzers balk about this.
350 - By default, declare single-argument constructors `explicit`.
352   - *Rationale*: This is a precaution to avoid unintended conversions that might
353     arise when single-argument constructors are used as implicit conversion
354     functions.
356 - Use explicitly signed or unsigned `char`s, or even better `uint8_t` and
357   `int8_t`. Do not use bare `char` unless it is to pass to a third-party API.
358   This type can be signed or unsigned depending on the architecture, which can
359   lead to interoperability problems or dangerous conditions such as
360   out-of-bounds array accesses
362 - Prefer explicit constructions over implicit ones that rely on 'magical' C++ behavior
364   - *Rationale*: Easier to understand what is happening, thus easier to spot mistakes, even for those
365   that are not language lawyers
367 Strings and formatting
368 ------------------------
370 - Be careful of `LogPrint` versus `LogPrintf`. `LogPrint` takes a `category` argument, `LogPrintf` does not.
372   - *Rationale*: Confusion of these can result in runtime exceptions due to
373     formatting mismatch, and it is easy to get wrong because of subtly similar naming
375 - Use `std::string`, avoid C string manipulation functions
377   - *Rationale*: C++ string handling is marginally safer, less scope for
378     buffer overflows and surprises with `\0` characters. Also some C string manipulations
379     tend to act differently depending on platform, or even the user locale
381 - Use `ParseInt32`, `ParseInt64`, `ParseUInt32`, `ParseUInt64`, `ParseDouble` from `utilstrencodings.h` for number parsing
383   - *Rationale*: These functions do overflow checking, and avoid pesky locale issues
385 - For `strprintf`, `LogPrint`, `LogPrintf` formatting characters don't need size specifiers
387   - *Rationale*: Bitcoin Core uses tinyformat, which is type safe. Leave them out to avoid confusion
389 Variable names
390 --------------
392 Although the shadowing warning (`-Wshadow`) is not enabled by default (it prevents issues rising
393 from using a different variable with the same name),
394 please name variables so that their names do not shadow variables defined in the source code.
396 E.g. in member initializers, prepend `_` to the argument name shadowing the
397 member name:
399 ```c++
400 class AddressBookPage
402     Mode mode;
405 AddressBookPage::AddressBookPage(Mode _mode) :
406       mode(_mode)
410 When using nested cycles, do not name the inner cycle variable the same as in
411 upper cycle etc.
414 Threads and synchronization
415 ----------------------------
417 - Build and run tests with `-DDEBUG_LOCKORDER` to verify that no potential
418   deadlocks are introduced. As of 0.12, this is defined by default when
419   configuring with `--enable-debug`
421 - When using `LOCK`/`TRY_LOCK` be aware that the lock exists in the context of
422   the current scope, so surround the statement and the code that needs the lock
423   with braces
425   OK:
427 ```c++
429     TRY_LOCK(cs_vNodes, lockNodes);
430     ...
434   Wrong:
436 ```c++
437 TRY_LOCK(cs_vNodes, lockNodes);
439     ...
443 Source code organization
444 --------------------------
446 - Implementation code should go into the `.cpp` file and not the `.h`, unless necessary due to template usage or
447   when performance due to inlining is critical
449   - *Rationale*: Shorter and simpler header files are easier to read, and reduce compile time
451 - Every `.cpp` and `.h` file should `#include` every header file it directly uses classes, functions or other
452   definitions from, even if those headers are already included indirectly through other headers. One exception
453   is that a `.cpp` file does not need to re-include the includes already included in its corresponding `.h` file.
455   - *Rationale*: Excluding headers because they are already indirectly included results in compilation
456     failures when those indirect dependencies change. Furthermore, it obscures what the real code
457     dependencies are.
459 - Don't import anything into the global namespace (`using namespace ...`). Use
460   fully specified types such as `std::string`.
462   - *Rationale*: Avoids symbol conflicts
464 - Terminate namespaces with a comment (`// namespace mynamespace`). The comment
465   should be placed on the same line as the brace closing the namespace, e.g.
467 ```c++
468 namespace mynamespace {
469     ...
470 } // namespace mynamespace
472 namespace {
473     ...
474 } // namespace
477   - *Rationale*: Avoids confusion about the namespace context
480 -----
482 - Do not display or manipulate dialogs in model code (classes `*Model`)
484   - *Rationale*: Model classes pass through events and data from the core, they
485     should not interact with the user. That's where View classes come in. The converse also
486     holds: try to not directly access core data structures from Views.
488 Subtrees
489 ----------
491 Several parts of the repository are subtrees of software maintained elsewhere.
493 Some of these are maintained by active developers of Bitcoin Core, in which case changes should probably go
494 directly upstream without being PRed directly against the project.  They will be merged back in the next
495 subtree merge.
497 Others are external projects without a tight relationship with our project.  Changes to these should also
498 be sent upstream but bugfixes may also be prudent to PR against Bitcoin Core so that they can be integrated
499 quickly.  Cosmetic changes should be purely taken upstream.
501 There is a tool in contrib/devtools/git-subtree-check.sh to check a subtree directory for consistency with
502 its upstream repository.
504 Current subtrees include:
506 - src/leveldb
507   - Upstream at https://github.com/google/leveldb ; Maintained by Google, but open important PRs to Core to avoid delay
509 - src/libsecp256k1
510   - Upstream at https://github.com/bitcoin-core/secp256k1/ ; actively maintaned by Core contributors.
512 - src/crypto/ctaes
513   - Upstream at https://github.com/bitcoin-core/ctaes ; actively maintained by Core contributors.
515 - src/univalue
516   - Upstream at https://github.com/jgarzik/univalue ; report important PRs to Core to avoid delay.
519 Git and GitHub tips
520 ---------------------
522 - For resolving merge/rebase conflicts, it can be useful to enable diff3 style using
523   `git config merge.conflictstyle diff3`. Instead of
525         <<<
526         yours
527         ===
528         theirs
529         >>>
531   you will see
533         <<<
534         yours
535         |||
536         original
537         ===
538         theirs
539         >>>
541   This may make it much clearer what caused the conflict. In this style, you can often just look
542   at what changed between *original* and *theirs*, and mechanically apply that to *yours* (or the other way around).
544 - When reviewing patches which change indentation in C++ files, use `git diff -w` and `git show -w`. This makes
545   the diff algorithm ignore whitespace changes. This feature is also available on github.com, by adding `?w=1`
546   at the end of any URL which shows a diff.
548 - When reviewing patches that change symbol names in many places, use `git diff --word-diff`. This will instead
549   of showing the patch as deleted/added *lines*, show deleted/added *words*.
551 - When reviewing patches that move code around, try using
552   `git diff --patience commit~:old/file.cpp commit:new/file/name.cpp`, and ignoring everything except the
553   moved body of code which should show up as neither `+` or `-` lines. In case it was not a pure move, this may
554   even work when combined with the `-w` or `--word-diff` options described above.
556 - When looking at other's pull requests, it may make sense to add the following section to your `.git/config`
557   file:
559         [remote "upstream-pull"]
560                 fetch = +refs/pull/*:refs/remotes/upstream-pull/*
561                 url = git@github.com:bitcoin/bitcoin.git
563   This will add an `upstream-pull` remote to your git repository, which can be fetched using `git fetch --all`
564   or `git fetch upstream-pull`. Afterwards, you can use `upstream-pull/NUMBER/head` in arguments to `git show`,
565   `git checkout` and anywhere a commit id would be acceptable to see the changes from pull request NUMBER.
567 Scripted diffs
568 --------------
570 For reformatting and refactoring commits where the changes can be easily automated using a bash script, we use
571 scripted-diff commits. The bash script is included in the commit message and our Travis CI job checks that
572 the result of the script is identical to the commit. This aids reviewers since they can verify that the script
573 does exactly what it's supposed to do. It is also helpful for rebasing (since the same script can just be re-run
574 on the new master commit).
576 To create a scripted-diff:
578 - start the commit message with `scripted-diff:` (and then a description of the diff on the same line)
579 - in the commit message include the bash script between lines containing just the following text:
580     - `-BEGIN VERIFY SCRIPT-`
581     - `-END VERIFY SCRIPT-`
583 The scripted-diff is verified by the tool `contrib/devtools/commit-script-check.sh`
585 Commit `bb81e173` is an example of a scripted-diff.
587 RPC interface guidelines
588 --------------------------
590 A few guidelines for introducing and reviewing new RPC interfaces:
592 - Method naming: use consecutive lower-case names such as `getrawtransaction` and `submitblock`
594   - *Rationale*: Consistency with existing interface.
596 - Argument naming: use snake case `fee_delta` (and not, e.g. camel case `feeDelta`)
598   - *Rationale*: Consistency with existing interface.
600 - Use the JSON parser for parsing, don't manually parse integers or strings from
601   arguments unless absolutely necessary.
603   - *Rationale*: Introduces hand-rolled string manipulation code at both the caller and callee sites,
604     which is error prone, and it is easy to get things such as escaping wrong.
605     JSON already supports nested data structures, no need to re-invent the wheel.
607   - *Exception*: AmountFromValue can parse amounts as string. This was introduced because many JSON
608     parsers and formatters hard-code handling decimal numbers as floating point
609     values, resulting in potential loss of precision. This is unacceptable for
610     monetary values. **Always** use `AmountFromValue` and `ValueFromAmount` when
611     inputting or outputting monetary values. The only exceptions to this are
612     `prioritisetransaction` and `getblocktemplate` because their interface
613     is specified as-is in BIP22.
615 - Missing arguments and 'null' should be treated the same: as default values. If there is no
616   default value, both cases should fail in the same way. The easiest way to follow this
617   guideline is detect unspecified arguments with `params[x].isNull()` instead of
618   `params.size() <= x`. The former returns true if the argument is either null or missing,
619   while the latter returns true if is missing, and false if it is null.
621   - *Rationale*: Avoids surprises when switching to name-based arguments. Missing name-based arguments
622   are passed as 'null'.
624 - Try not to overload methods on argument type. E.g. don't make `getblock(true)` and `getblock("hash")`
625   do different things.
627   - *Rationale*: This is impossible to use with `bitcoin-cli`, and can be surprising to users.
629   - *Exception*: Some RPC calls can take both an `int` and `bool`, most notably when a bool was switched
630     to a multi-value, or due to other historical reasons. **Always** have false map to 0 and
631     true to 1 in this case.
633 - Don't forget to fill in the argument names correctly in the RPC command table.
635   - *Rationale*: If not, the call can not be used with name-based arguments.
637 - Set okSafeMode in the RPC command table to a sensible value: safe mode is when the
638   blockchain is regarded to be in a confused state, and the client deems it unsafe to
639   do anything irreversible such as send. Anything that just queries should be permitted.
641   - *Rationale*: Troubleshooting a node in safe mode is difficult if half the
642     RPCs don't work.
644 - Add every non-string RPC argument `(method, idx, name)` to the table `vRPCConvertParams` in `rpc/client.cpp`.
646   - *Rationale*: `bitcoin-cli` and the GUI debug console use this table to determine how to
647     convert a plaintext command line to JSON. If the types don't match, the method can be unusable
648     from there.
650 - A RPC method must either be a wallet method or a non-wallet method. Do not
651   introduce new methods such as `signrawtransaction` that differ in behavior
652   based on presence of a wallet.
654   - *Rationale*: as well as complicating the implementation and interfering
655     with the introduction of multi-wallet, wallet and non-wallet code should be
656     separated to avoid introducing circular dependencies between code units.
658 - Try to make the RPC response a JSON object.
660   - *Rationale*: If a RPC response is not a JSON object then it is harder to avoid API breakage if
661     new data in the response is needed.