scripted-diff: Use the C++11 keyword nullptr to denote the pointer literal instead...
[bitcoinplatinum.git] / doc / developer-notes.md
blob458e7bcbff8dd19110f7ce214070729294c4e992
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 Locking/mutex usage notes
169 -------------------------
171 The code is multi-threaded, and uses mutexes and the
172 LOCK/TRY_LOCK macros to protect data structures.
174 Deadlocks due to inconsistent lock ordering (thread 1 locks cs_main
175 and then cs_wallet, while thread 2 locks them in the opposite order:
176 result, deadlock as each waits for the other to release its lock) are
177 a problem. Compile with -DDEBUG_LOCKORDER to get lock order
178 inconsistencies reported in the debug.log file.
180 Re-architecting the core code so there are better-defined interfaces
181 between the various components is a goal, with any necessary locking
182 done by the components (e.g. see the self-contained CKeyStore class
183 and its cs_KeyStore lock for example).
185 Threads
186 -------
188 - ThreadScriptCheck : Verifies block scripts.
190 - ThreadImport : Loads blocks from blk*.dat files or bootstrap.dat.
192 - StartNode : Starts other threads.
194 - ThreadDNSAddressSeed : Loads addresses of peers from the DNS.
196 - ThreadMapPort : Universal plug-and-play startup/shutdown
198 - ThreadSocketHandler : Sends/Receives data from peers on port 8333.
200 - ThreadOpenAddedConnections : Opens network connections to added nodes.
202 - ThreadOpenConnections : Initiates new connections to peers.
204 - ThreadMessageHandler : Higher-level message handling (sending and receiving).
206 - DumpAddresses : Dumps IP addresses of nodes to peers.dat.
208 - ThreadFlushWalletDB : Close the wallet.dat file if it hasn't been used in 500ms.
210 - ThreadRPCServer : Remote procedure call handler, listens on port 8332 for connections and services them.
212 - BitcoinMiner : Generates bitcoins (if wallet is enabled).
214 - Shutdown : Does an orderly shutdown of everything.
216 Ignoring IDE/editor files
217 --------------------------
219 In closed-source environments in which everyone uses the same IDE it is common
220 to add temporary files it produces to the project-wide `.gitignore` file.
222 However, in open source software such as Bitcoin Core, where everyone uses
223 their own editors/IDE/tools, it is less common. Only you know what files your
224 editor produces and this may change from version to version. The canonical way
225 to do this is thus to create your local gitignore. Add this to `~/.gitconfig`:
228 [core]
229         excludesfile = /home/.../.gitignore_global
232 (alternatively, type the command `git config --global core.excludesfile ~/.gitignore_global`
233 on a terminal)
235 Then put your favourite tool's temporary filenames in that file, e.g.
237 # NetBeans
238 nbproject/
241 Another option is to create a per-repository excludes file `.git/info/exclude`.
242 These are not committed but apply only to one repository.
244 If a set of tools is used by the build system or scripts the repository (for
245 example, lcov) it is perfectly acceptable to add its files to `.gitignore`
246 and commit them.
248 Development guidelines
249 ============================
251 A few non-style-related recommendations for developers, as well as points to
252 pay attention to for reviewers of Bitcoin Core code.
254 General Bitcoin Core
255 ----------------------
257 - New features should be exposed on RPC first, then can be made available in the GUI
259   - *Rationale*: RPC allows for better automatic testing. The test suite for
260     the GUI is very limited
262 - Make sure pull requests pass Travis CI before merging
264   - *Rationale*: Makes sure that they pass thorough testing, and that the tester will keep passing
265      on the master branch. Otherwise all new pull requests will start failing the tests, resulting in
266      confusion and mayhem
268   - *Explanation*: If the test suite is to be updated for a change, this has to
269     be done first
271 Wallet
272 -------
274 - Make sure that no crashes happen with run-time option `-disablewallet`.
276   - *Rationale*: In RPC code that conditionally uses the wallet (such as
277     `validateaddress`) it is easy to forget that global pointer `pwalletMain`
278     can be NULL. See `test/functional/disablewallet.py` for functional tests
279     exercising the API with `-disablewallet`
281 - Include `db_cxx.h` (BerkeleyDB header) only when `ENABLE_WALLET` is set
283   - *Rationale*: Otherwise compilation of the disable-wallet build will fail in environments without BerkeleyDB
285 General C++
286 -------------
288 - Assertions should not have side-effects
290   - *Rationale*: Even though the source code is set to refuse to compile
291     with assertions disabled, having side-effects in assertions is unexpected and
292     makes the code harder to understand
294 - If you use the `.h`, you must link the `.cpp`
296   - *Rationale*: Include files define the interface for the code in implementation files. Including one but
297       not linking the other is confusing. Please avoid that. Moving functions from
298       the `.h` to the `.cpp` should not result in build errors
300 - Use the RAII (Resource Acquisition Is Initialization) paradigm where possible. For example by using
301   `unique_ptr` for allocations in a function.
303   - *Rationale*: This avoids memory and resource leaks, and ensures exception safety
305 C++ data structures
306 --------------------
308 - Never use the `std::map []` syntax when reading from a map, but instead use `.find()`
310   - *Rationale*: `[]` does an insert (of the default element) if the item doesn't
311     exist in the map yet. This has resulted in memory leaks in the past, as well as
312     race conditions (expecting read-read behavior). Using `[]` is fine for *writing* to a map
314 - Do not compare an iterator from one data structure with an iterator of
315   another data structure (even if of the same type)
317   - *Rationale*: Behavior is undefined. In C++ parlor this means "may reformat
318     the universe", in practice this has resulted in at least one hard-to-debug crash bug
320 - Watch out for out-of-bounds vector access. `&vch[vch.size()]` is illegal,
321   including `&vch[0]` for an empty vector. Use `vch.data()` and `vch.data() +
322   vch.size()` instead.
324 - Vector bounds checking is only enabled in debug mode. Do not rely on it
326 - Make sure that constructors initialize all fields. If this is skipped for a
327   good reason (i.e., optimization on the critical path), add an explicit
328   comment about this
330   - *Rationale*: Ensure determinism by avoiding accidental use of uninitialized
331     values. Also, static analyzers balk about this.
333 - Use explicitly signed or unsigned `char`s, or even better `uint8_t` and
334   `int8_t`. Do not use bare `char` unless it is to pass to a third-party API.
335   This type can be signed or unsigned depending on the architecture, which can
336   lead to interoperability problems or dangerous conditions such as
337   out-of-bounds array accesses
339 - Prefer explicit constructions over implicit ones that rely on 'magical' C++ behavior
341   - *Rationale*: Easier to understand what is happening, thus easier to spot mistakes, even for those
342   that are not language lawyers
344 Strings and formatting
345 ------------------------
347 - Be careful of `LogPrint` versus `LogPrintf`. `LogPrint` takes a `category` argument, `LogPrintf` does not.
349   - *Rationale*: Confusion of these can result in runtime exceptions due to
350     formatting mismatch, and it is easy to get wrong because of subtly similar naming
352 - Use `std::string`, avoid C string manipulation functions
354   - *Rationale*: C++ string handling is marginally safer, less scope for
355     buffer overflows and surprises with `\0` characters. Also some C string manipulations
356     tend to act differently depending on platform, or even the user locale
358 - Use `ParseInt32`, `ParseInt64`, `ParseUInt32`, `ParseUInt64`, `ParseDouble` from `utilstrencodings.h` for number parsing
360   - *Rationale*: These functions do overflow checking, and avoid pesky locale issues
362 - For `strprintf`, `LogPrint`, `LogPrintf` formatting characters don't need size specifiers
364   - *Rationale*: Bitcoin Core uses tinyformat, which is type safe. Leave them out to avoid confusion
366 Variable names
367 --------------
369 Although the shadowing warning (`-Wshadow`) is not enabled by default (it prevents issues rising
370 from using a different variable with the same name),
371 please name variables so that their names do not shadow variables defined in the source code.
373 E.g. in member initializers, prepend `_` to the argument name shadowing the
374 member name:
376 ```c++
377 class AddressBookPage
379     Mode mode;
382 AddressBookPage::AddressBookPage(Mode _mode) :
383       mode(_mode)
387 When using nested cycles, do not name the inner cycle variable the same as in
388 upper cycle etc.
391 Threads and synchronization
392 ----------------------------
394 - Build and run tests with `-DDEBUG_LOCKORDER` to verify that no potential
395   deadlocks are introduced. As of 0.12, this is defined by default when
396   configuring with `--enable-debug`
398 - When using `LOCK`/`TRY_LOCK` be aware that the lock exists in the context of
399   the current scope, so surround the statement and the code that needs the lock
400   with braces
402   OK:
404 ```c++
406     TRY_LOCK(cs_vNodes, lockNodes);
407     ...
411   Wrong:
413 ```c++
414 TRY_LOCK(cs_vNodes, lockNodes);
416     ...
420 Source code organization
421 --------------------------
423 - Implementation code should go into the `.cpp` file and not the `.h`, unless necessary due to template usage or
424   when performance due to inlining is critical
426   - *Rationale*: Shorter and simpler header files are easier to read, and reduce compile time
428 - Every `.cpp` and `.h` file should `#include` every header file it directly uses classes, functions or other
429   definitions from, even if those headers are already included indirectly through other headers. One exception
430   is that a `.cpp` file does not need to re-include the includes already included in its corresponding `.h` file.
432   - *Rationale*: Excluding headers because they are already indirectly included results in compilation
433     failures when those indirect dependencies change. Furthermore, it obscures what the real code
434     dependencies are.
436 - Don't import anything into the global namespace (`using namespace ...`). Use
437   fully specified types such as `std::string`.
439   - *Rationale*: Avoids symbol conflicts
441 - Terminate namespaces with a comment (`// namespace mynamespace`). The comment
442   should be placed on the same line as the brace closing the namespace, e.g.
444 ```c++
445 namespace mynamespace {
446     ...
447 } // namespace mynamespace
449 namespace {
450     ...
451 } // namespace
454   - *Rationale*: Avoids confusion about the namespace context
457 -----
459 - Do not display or manipulate dialogs in model code (classes `*Model`)
461   - *Rationale*: Model classes pass through events and data from the core, they
462     should not interact with the user. That's where View classes come in. The converse also
463     holds: try to not directly access core data structures from Views.
465 Subtrees
466 ----------
468 Several parts of the repository are subtrees of software maintained elsewhere.
470 Some of these are maintained by active developers of Bitcoin Core, in which case changes should probably go
471 directly upstream without being PRed directly against the project.  They will be merged back in the next
472 subtree merge.
474 Others are external projects without a tight relationship with our project.  Changes to these should also
475 be sent upstream but bugfixes may also be prudent to PR against Bitcoin Core so that they can be integrated
476 quickly.  Cosmetic changes should be purely taken upstream.
478 There is a tool in contrib/devtools/git-subtree-check.sh to check a subtree directory for consistency with
479 its upstream repository.
481 Current subtrees include:
483 - src/leveldb
484   - Upstream at https://github.com/google/leveldb ; Maintained by Google, but open important PRs to Core to avoid delay
486 - src/libsecp256k1
487   - Upstream at https://github.com/bitcoin-core/secp256k1/ ; actively maintaned by Core contributors.
489 - src/crypto/ctaes
490   - Upstream at https://github.com/bitcoin-core/ctaes ; actively maintained by Core contributors.
492 - src/univalue
493   - Upstream at https://github.com/jgarzik/univalue ; report important PRs to Core to avoid delay.
496 Git and GitHub tips
497 ---------------------
499 - For resolving merge/rebase conflicts, it can be useful to enable diff3 style using
500   `git config merge.conflictstyle diff3`. Instead of
502         <<<
503         yours
504         ===
505         theirs
506         >>>
508   you will see
510         <<<
511         yours
512         |||
513         original
514         ===
515         theirs
516         >>>
518   This may make it much clearer what caused the conflict. In this style, you can often just look
519   at what changed between *original* and *theirs*, and mechanically apply that to *yours* (or the other way around).
521 - When reviewing patches which change indentation in C++ files, use `git diff -w` and `git show -w`. This makes
522   the diff algorithm ignore whitespace changes. This feature is also available on github.com, by adding `?w=1`
523   at the end of any URL which shows a diff.
525 - When reviewing patches that change symbol names in many places, use `git diff --word-diff`. This will instead
526   of showing the patch as deleted/added *lines*, show deleted/added *words*.
528 - When reviewing patches that move code around, try using
529   `git diff --patience commit~:old/file.cpp commit:new/file/name.cpp`, and ignoring everything except the
530   moved body of code which should show up as neither `+` or `-` lines. In case it was not a pure move, this may
531   even work when combined with the `-w` or `--word-diff` options described above.
533 - When looking at other's pull requests, it may make sense to add the following section to your `.git/config`
534   file:
536         [remote "upstream-pull"]
537                 fetch = +refs/pull/*:refs/remotes/upstream-pull/*
538                 url = git@github.com:bitcoin/bitcoin.git
540   This will add an `upstream-pull` remote to your git repository, which can be fetched using `git fetch --all`
541   or `git fetch upstream-pull`. Afterwards, you can use `upstream-pull/NUMBER/head` in arguments to `git show`,
542   `git checkout` and anywhere a commit id would be acceptable to see the changes from pull request NUMBER.
544 RPC interface guidelines
545 --------------------------
547 A few guidelines for introducing and reviewing new RPC interfaces:
549 - Method naming: use consecutive lower-case names such as `getrawtransaction` and `submitblock`
551   - *Rationale*: Consistency with existing interface.
553 - Argument naming: use snake case `fee_delta` (and not, e.g. camel case `feeDelta`)
555   - *Rationale*: Consistency with existing interface.
557 - Use the JSON parser for parsing, don't manually parse integers or strings from
558   arguments unless absolutely necessary.
560   - *Rationale*: Introduces hand-rolled string manipulation code at both the caller and callee sites,
561     which is error prone, and it is easy to get things such as escaping wrong.
562     JSON already supports nested data structures, no need to re-invent the wheel.
564   - *Exception*: AmountToValue can parse amounts as string. This was introduced because many JSON
565     parsers and formatters hard-code handling decimal numbers as floating point
566     values, resulting in potential loss of precision. This is unacceptable for
567     monetary values. **Always** use `AmountToValue` and `ValueToAmount` when
568     inputting or outputting monetary values. The only exceptions to this are
569     `prioritisetransaction` and `getblocktemplate` because their interface
570     is specified as-is in BIP22.
572 - Missing arguments and 'null' should be treated the same: as default values. If there is no
573   default value, both cases should fail in the same way.
575   - *Rationale*: Avoids surprises when switching to name-based arguments. Missing name-based arguments
576   are passed as 'null'.
578   - *Exception*: Many legacy exceptions to this exist, one of the worst ones is
579     `getbalance` which follows a completely different code path based on the
580     number of arguments. We are still in the process of cleaning these up. Do not introduce
581     new ones.
583 - Try not to overload methods on argument type. E.g. don't make `getblock(true)` and `getblock("hash")`
584   do different things.
586   - *Rationale*: This is impossible to use with `bitcoin-cli`, and can be surprising to users.
588   - *Exception*: Some RPC calls can take both an `int` and `bool`, most notably when a bool was switched
589     to a multi-value, or due to other historical reasons. **Always** have false map to 0 and
590     true to 1 in this case.
592 - Don't forget to fill in the argument names correctly in the RPC command table.
594   - *Rationale*: If not, the call can not be used with name-based arguments.
596 - Set okSafeMode in the RPC command table to a sensible value: safe mode is when the
597   blockchain is regarded to be in a confused state, and the client deems it unsafe to
598   do anything irreversible such as send. Anything that just queries should be permitted.
600   - *Rationale*: Troubleshooting a node in safe mode is difficult if half the
601     RPCs don't work.
603 - Add every non-string RPC argument `(method, idx, name)` to the table `vRPCConvertParams` in `rpc/client.cpp`.
605   - *Rationale*: `bitcoin-cli` and the GUI debug console use this table to determine how to
606     convert a plaintext command line to JSON. If the types don't match, the method can be unusable
607     from there.
609 - A RPC method must either be a wallet method or a non-wallet method. Do not
610   introduce new methods such as `getinfo` and `signrawtransaction` that differ
611   in behavior based on presence of a wallet.
613   - *Rationale*: as well as complicating the implementation and interfering
614     with the introduction of multi-wallet, wallet and non-wallet code should be
615     separated to avoid introducing circular dependencies between code units.