[depends] miniupnpc 2.0.20170509
[bitcoinplatinum.git] / doc / developer-notes.md
blobcf860a1bf271207f2f62ea53dbd7524916ef5cf8
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 and you are encouraged to use the provided
8 [clang-format-diff script](/contrib/devtools/README.md#clang-format-diffpy)
9 to clean up the patch automatically before submitting a pull request.
11 - Basic rules specified in [src/.clang-format](/src/.clang-format).
12   - Braces on new lines for namespaces, classes, functions, methods.
13   - Braces on the same line for everything else.
14   - 4 space indentation (no tabs) for every block except namespaces.
15   - No indentation for `public`/`protected`/`private` or for `namespace`.
16   - No extra spaces inside parenthesis; don't do ( this )
17   - No space after function names; one space after `if`, `for` and `while`.
18   - If an `if` only has a single-statement then-clause, it can appear
19     on the same line as the if, without braces. In every other case,
20     braces are required, and the then and else clauses must appear
21     correctly indented on a new line.
22   - `++i` is preferred over `i++`.
24 Block style example:
25 ```c++
26 namespace foo
28 class Class
30     bool Function(const std::string& s, int n)
31     {
32         // Comment summarising what this section of code does
33         for (int i = 0; i < n; ++i) {
34             // When something fails, return early
35             if (!Something()) return false;
36             ...
37             if (SomethingElse()) {
38                 DoMore();
39             } else {
40                 DoLess();
41             }
42         }
44         // Success return is usually at the end
45         return true;
46     }
49 ```
51 Doxygen comments
52 -----------------
54 To facilitate the generation of documentation, use doxygen-compatible comment blocks for functions, methods and fields.
56 For example, to describe a function use:
57 ```c++
58 /**
59  * ... text ...
60  * @param[in] arg1    A description
61  * @param[in] arg2    Another argument description
62  * @pre Precondition for function...
63  */
64 bool function(int arg1, const char *arg2)
65 ```
66 A complete list of `@xxx` commands can be found at http://www.stack.nl/~dimitri/doxygen/manual/commands.html.
67 As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't
68 *need* to provide any commands for a comment to be valid; just a description text is fine.
70 To describe a class use the same construct above the class definition:
71 ```c++
72 /**
73  * Alerts are for notifying old versions if they become too obsolete and
74  * need to upgrade. The message is displayed in the status bar.
75  * @see GetWarnings()
76  */
77 class CAlert
79 ```
81 To describe a member or variable use:
82 ```c++
83 int var; //!< Detailed description after the member
84 ```
87 ```cpp
88 //! Description before the member
89 int var;
90 ```
92 Also OK:
93 ```c++
94 ///
95 /// ... text ...
96 ///
97 bool function2(int arg1, const char *arg2)
98 ```
100 Not OK (used plenty in the current source, but not picked up):
101 ```c++
103 // ... text ...
107 A full list of comment syntaxes picked up by doxygen can be found at http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html,
108 but if possible use one of the above styles.
110 Development tips and tricks
111 ---------------------------
113 **compiling for debugging**
115 Run configure with the --enable-debug option, then make. Or run configure with
116 CXXFLAGS="-g -ggdb -O0" or whatever debug flags you need.
118 **debug.log**
120 If the code is behaving strangely, take a look in the debug.log file in the data directory;
121 error and debugging messages are written there.
123 The -debug=... command-line option controls debugging; running with just -debug or -debug=1 will turn
124 on all categories (and give you a very large debug.log file).
126 The Qt code routes qDebug() output to debug.log under category "qt": run with -debug=qt
127 to see it.
129 **testnet and regtest modes**
131 Run with the -testnet option to run with "play bitcoins" on the test network, if you
132 are testing multi-machine code that needs to operate across the internet.
134 If you are testing something that can run on one machine, run with the -regtest option.
135 In regression test mode, blocks can be created on-demand; see test/functional/ for tests
136 that run in -regtest mode.
138 **DEBUG_LOCKORDER**
140 Bitcoin Core is a multithreaded application, and deadlocks or other multithreading bugs
141 can be very difficult to track down. Compiling with -DDEBUG_LOCKORDER (configure
142 CXXFLAGS="-DDEBUG_LOCKORDER -g") inserts run-time checks to keep track of which locks
143 are held, and adds warnings to the debug.log file if inconsistencies are detected.
145 Locking/mutex usage notes
146 -------------------------
148 The code is multi-threaded, and uses mutexes and the
149 LOCK/TRY_LOCK macros to protect data structures.
151 Deadlocks due to inconsistent lock ordering (thread 1 locks cs_main
152 and then cs_wallet, while thread 2 locks them in the opposite order:
153 result, deadlock as each waits for the other to release its lock) are
154 a problem. Compile with -DDEBUG_LOCKORDER to get lock order
155 inconsistencies reported in the debug.log file.
157 Re-architecting the core code so there are better-defined interfaces
158 between the various components is a goal, with any necessary locking
159 done by the components (e.g. see the self-contained CKeyStore class
160 and its cs_KeyStore lock for example).
162 Threads
163 -------
165 - ThreadScriptCheck : Verifies block scripts.
167 - ThreadImport : Loads blocks from blk*.dat files or bootstrap.dat.
169 - StartNode : Starts other threads.
171 - ThreadDNSAddressSeed : Loads addresses of peers from the DNS.
173 - ThreadMapPort : Universal plug-and-play startup/shutdown
175 - ThreadSocketHandler : Sends/Receives data from peers on port 8333.
177 - ThreadOpenAddedConnections : Opens network connections to added nodes.
179 - ThreadOpenConnections : Initiates new connections to peers.
181 - ThreadMessageHandler : Higher-level message handling (sending and receiving).
183 - DumpAddresses : Dumps IP addresses of nodes to peers.dat.
185 - ThreadFlushWalletDB : Close the wallet.dat file if it hasn't been used in 500ms.
187 - ThreadRPCServer : Remote procedure call handler, listens on port 8332 for connections and services them.
189 - BitcoinMiner : Generates bitcoins (if wallet is enabled).
191 - Shutdown : Does an orderly shutdown of everything.
193 Ignoring IDE/editor files
194 --------------------------
196 In closed-source environments in which everyone uses the same IDE it is common
197 to add temporary files it produces to the project-wide `.gitignore` file.
199 However, in open source software such as Bitcoin Core, where everyone uses
200 their own editors/IDE/tools, it is less common. Only you know what files your
201 editor produces and this may change from version to version. The canonical way
202 to do this is thus to create your local gitignore. Add this to `~/.gitconfig`:
205 [core]
206         excludesfile = /home/.../.gitignore_global
209 (alternatively, type the command `git config --global core.excludesfile ~/.gitignore_global`
210 on a terminal)
212 Then put your favourite tool's temporary filenames in that file, e.g.
214 # NetBeans
215 nbproject/
218 Another option is to create a per-repository excludes file `.git/info/exclude`.
219 These are not committed but apply only to one repository.
221 If a set of tools is used by the build system or scripts the repository (for
222 example, lcov) it is perfectly acceptable to add its files to `.gitignore`
223 and commit them.
225 Development guidelines
226 ============================
228 A few non-style-related recommendations for developers, as well as points to
229 pay attention to for reviewers of Bitcoin Core code.
231 General Bitcoin Core
232 ----------------------
234 - New features should be exposed on RPC first, then can be made available in the GUI
236   - *Rationale*: RPC allows for better automatic testing. The test suite for
237     the GUI is very limited
239 - Make sure pull requests pass Travis CI before merging
241   - *Rationale*: Makes sure that they pass thorough testing, and that the tester will keep passing
242      on the master branch. Otherwise all new pull requests will start failing the tests, resulting in
243      confusion and mayhem
245   - *Explanation*: If the test suite is to be updated for a change, this has to
246     be done first
248 Wallet
249 -------
251 - Make sure that no crashes happen with run-time option `-disablewallet`.
253   - *Rationale*: In RPC code that conditionally uses the wallet (such as
254     `validateaddress`) it is easy to forget that global pointer `pwalletMain`
255     can be NULL. See `test/functional/disablewallet.py` for functional tests
256     exercising the API with `-disablewallet`
258 - Include `db_cxx.h` (BerkeleyDB header) only when `ENABLE_WALLET` is set
260   - *Rationale*: Otherwise compilation of the disable-wallet build will fail in environments without BerkeleyDB
262 General C++
263 -------------
265 - Assertions should not have side-effects
267   - *Rationale*: Even though the source code is set to to refuse to compile
268     with assertions disabled, having side-effects in assertions is unexpected and
269     makes the code harder to understand
271 - If you use the `.h`, you must link the `.cpp`
273   - *Rationale*: Include files define the interface for the code in implementation files. Including one but
274       not linking the other is confusing. Please avoid that. Moving functions from
275       the `.h` to the `.cpp` should not result in build errors
277 - Use the RAII (Resource Acquisition Is Initialization) paradigm where possible. For example by using
278   `unique_ptr` for allocations in a function.
280   - *Rationale*: This avoids memory and resource leaks, and ensures exception safety
282 C++ data structures
283 --------------------
285 - Never use the `std::map []` syntax when reading from a map, but instead use `.find()`
287   - *Rationale*: `[]` does an insert (of the default element) if the item doesn't
288     exist in the map yet. This has resulted in memory leaks in the past, as well as
289     race conditions (expecting read-read behavior). Using `[]` is fine for *writing* to a map
291 - Do not compare an iterator from one data structure with an iterator of
292   another data structure (even if of the same type)
294   - *Rationale*: Behavior is undefined. In C++ parlor this means "may reformat
295     the universe", in practice this has resulted in at least one hard-to-debug crash bug
297 - Watch out for out-of-bounds vector access. `&vch[vch.size()]` is illegal,
298   including `&vch[0]` for an empty vector. Use `vch.data()` and `vch.data() +
299   vch.size()` instead.
301 - Vector bounds checking is only enabled in debug mode. Do not rely on it
303 - Make sure that constructors initialize all fields. If this is skipped for a
304   good reason (i.e., optimization on the critical path), add an explicit
305   comment about this
307   - *Rationale*: Ensure determinism by avoiding accidental use of uninitialized
308     values. Also, static analyzers balk about this.
310 - Use explicitly signed or unsigned `char`s, or even better `uint8_t` and
311   `int8_t`. Do not use bare `char` unless it is to pass to a third-party API.
312   This type can be signed or unsigned depending on the architecture, which can
313   lead to interoperability problems or dangerous conditions such as
314   out-of-bounds array accesses
316 - Prefer explicit constructions over implicit ones that rely on 'magical' C++ behavior
318   - *Rationale*: Easier to understand what is happening, thus easier to spot mistakes, even for those
319   that are not language lawyers
321 Strings and formatting
322 ------------------------
324 - Be careful of `LogPrint` versus `LogPrintf`. `LogPrint` takes a `category` argument, `LogPrintf` does not.
326   - *Rationale*: Confusion of these can result in runtime exceptions due to
327     formatting mismatch, and it is easy to get wrong because of subtly similar naming
329 - Use `std::string`, avoid C string manipulation functions
331   - *Rationale*: C++ string handling is marginally safer, less scope for
332     buffer overflows and surprises with `\0` characters. Also some C string manipulations
333     tend to act differently depending on platform, or even the user locale
335 - Use `ParseInt32`, `ParseInt64`, `ParseUInt32`, `ParseUInt64`, `ParseDouble` from `utilstrencodings.h` for number parsing
337   - *Rationale*: These functions do overflow checking, and avoid pesky locale issues
339 - For `strprintf`, `LogPrint`, `LogPrintf` formatting characters don't need size specifiers
341   - *Rationale*: Bitcoin Core uses tinyformat, which is type safe. Leave them out to avoid confusion
343 Variable names
344 --------------
346 Although the shadowing warning (`-Wshadow`) is not enabled by default (it prevents issues rising
347 from using a different variable with the same name),
348 please name variables so that their names do not shadow variables defined in the source code.
350 E.g. in member initializers, prepend `_` to the argument name shadowing the
351 member name:
353 ```c++
354 class AddressBookPage
356     Mode mode;
359 AddressBookPage::AddressBookPage(Mode _mode) :
360       mode(_mode)
364 When using nested cycles, do not name the inner cycle variable the same as in
365 upper cycle etc.
368 Threads and synchronization
369 ----------------------------
371 - Build and run tests with `-DDEBUG_LOCKORDER` to verify that no potential
372   deadlocks are introduced. As of 0.12, this is defined by default when
373   configuring with `--enable-debug`
375 - When using `LOCK`/`TRY_LOCK` be aware that the lock exists in the context of
376   the current scope, so surround the statement and the code that needs the lock
377   with braces
379   OK:
381 ```c++
383     TRY_LOCK(cs_vNodes, lockNodes);
384     ...
388   Wrong:
390 ```c++
391 TRY_LOCK(cs_vNodes, lockNodes);
393     ...
397 Source code organization
398 --------------------------
400 - Implementation code should go into the `.cpp` file and not the `.h`, unless necessary due to template usage or
401   when performance due to inlining is critical
403   - *Rationale*: Shorter and simpler header files are easier to read, and reduce compile time
405 - Don't import anything into the global namespace (`using namespace ...`). Use
406   fully specified types such as `std::string`.
408   - *Rationale*: Avoids symbol conflicts
411 -----
413 - Do not display or manipulate dialogs in model code (classes `*Model`)
415   - *Rationale*: Model classes pass through events and data from the core, they
416     should not interact with the user. That's where View classes come in. The converse also
417     holds: try to not directly access core data structures from Views.
419 Subtrees
420 ----------
422 Several parts of the repository are subtrees of software maintained elsewhere.
424 Some of these are maintained by active developers of Bitcoin Core, in which case changes should probably go
425 directly upstream without being PRed directly against the project.  They will be merged back in the next
426 subtree merge.
428 Others are external projects without a tight relationship with our project.  Changes to these should also
429 be sent upstream but bugfixes may also be prudent to PR against Bitcoin Core so that they can be integrated
430 quickly.  Cosmetic changes should be purely taken upstream.
432 There is a tool in contrib/devtools/git-subtree-check.sh to check a subtree directory for consistency with
433 its upstream repository.
435 Current subtrees include:
437 - src/leveldb
438   - Upstream at https://github.com/google/leveldb ; Maintained by Google, but open important PRs to Core to avoid delay
440 - src/libsecp256k1
441   - Upstream at https://github.com/bitcoin-core/secp256k1/ ; actively maintaned by Core contributors.
443 - src/crypto/ctaes
444   - Upstream at https://github.com/bitcoin-core/ctaes ; actively maintained by Core contributors.
446 - src/univalue
447   - Upstream at https://github.com/jgarzik/univalue ; report important PRs to Core to avoid delay.
450 Git and GitHub tips
451 ---------------------
453 - For resolving merge/rebase conflicts, it can be useful to enable diff3 style using
454   `git config merge.conflictstyle diff3`. Instead of
456         <<<
457         yours
458         ===
459         theirs
460         >>>
462   you will see
464         <<<
465         yours
466         |||
467         original
468         ===
469         theirs
470         >>>
472   This may make it much clearer what caused the conflict. In this style, you can often just look
473   at what changed between *original* and *theirs*, and mechanically apply that to *yours* (or the other way around).
475 - When reviewing patches which change indentation in C++ files, use `git diff -w` and `git show -w`. This makes
476   the diff algorithm ignore whitespace changes. This feature is also available on github.com, by adding `?w=1`
477   at the end of any URL which shows a diff.
479 - When reviewing patches that change symbol names in many places, use `git diff --word-diff`. This will instead
480   of showing the patch as deleted/added *lines*, show deleted/added *words*.
482 - When reviewing patches that move code around, try using
483   `git diff --patience commit~:old/file.cpp commit:new/file/name.cpp`, and ignoring everything except the
484   moved body of code which should show up as neither `+` or `-` lines. In case it was not a pure move, this may
485   even work when combined with the `-w` or `--word-diff` options described above.
487 - When looking at other's pull requests, it may make sense to add the following section to your `.git/config`
488   file:
490         [remote "upstream-pull"]
491                 fetch = +refs/pull/*:refs/remotes/upstream-pull/*
492                 url = git@github.com:bitcoin/bitcoin.git
494   This will add an `upstream-pull` remote to your git repository, which can be fetched using `git fetch --all`
495   or `git fetch upstream-pull`. Afterwards, you can use `upstream-pull/NUMBER/head` in arguments to `git show`,
496   `git checkout` and anywhere a commit id would be acceptable to see the changes from pull request NUMBER.
498 RPC interface guidelines
499 --------------------------
501 A few guidelines for introducing and reviewing new RPC interfaces:
503 - Method naming: use consecutive lower-case names such as `getrawtransaction` and `submitblock`
505   - *Rationale*: Consistency with existing interface.
507 - Argument naming: use snake case `fee_delta` (and not, e.g. camel case `feeDelta`)
509   - *Rationale*: Consistency with existing interface.
511 - Use the JSON parser for parsing, don't manually parse integers or strings from
512   arguments unless absolutely necessary.
514   - *Rationale*: Introduces hand-rolled string manipulation code at both the caller and callee sites,
515     which is error prone, and it is easy to get things such as escaping wrong.
516     JSON already supports nested data structures, no need to re-invent the wheel.
518   - *Exception*: AmountToValue can parse amounts as string. This was introduced because many JSON
519     parsers and formatters hard-code handling decimal numbers as floating point
520     values, resulting in potential loss of precision. This is unacceptable for
521     monetary values. **Always** use `AmountToValue` and `ValueToAmount` when
522     inputting or outputting monetary values. The only exceptions to this are
523     `prioritisetransaction` and `getblocktemplate` because their interface
524     is specified as-is in BIP22.
526 - Missing arguments and 'null' should be treated the same: as default values. If there is no
527   default value, both cases should fail in the same way.
529   - *Rationale*: Avoids surprises when switching to name-based arguments. Missing name-based arguments
530   are passed as 'null'.
532   - *Exception*: Many legacy exceptions to this exist, one of the worst ones is
533     `getbalance` which follows a completely different code path based on the
534     number of arguments. We are still in the process of cleaning these up. Do not introduce
535     new ones.
537 - Try not to overload methods on argument type. E.g. don't make `getblock(true)` and `getblock("hash")`
538   do different things.
540   - *Rationale*: This is impossible to use with `bitcoin-cli`, and can be surprising to users.
542   - *Exception*: Some RPC calls can take both an `int` and `bool`, most notably when a bool was switched
543     to a multi-value, or due to other historical reasons. **Always** have false map to 0 and
544     true to 1 in this case.
546 - Don't forget to fill in the argument names correctly in the RPC command table.
548   - *Rationale*: If not, the call can not be used with name-based arguments.
550 - Set okSafeMode in the RPC command table to a sensible value: safe mode is when the
551   blockchain is regarded to be in a confused state, and the client deems it unsafe to
552   do anything irreversible such as send. Anything that just queries should be permitted.
554   - *Rationale*: Troubleshooting a node in safe mode is difficult if half the
555     RPCs don't work.
557 - Add every non-string RPC argument `(method, idx, name)` to the table `vRPCConvertParams` in `rpc/client.cpp`.
559   - *Rationale*: `bitcoin-cli` and the GUI debug console use this table to determine how to
560     convert a plaintext command line to JSON. If the types don't match, the method can be unusable
561     from there.
563 - A RPC method must either be a wallet method or a non-wallet method. Do not
564   introduce new methods such as `getinfo` and `signrawtransaction` that differ
565   in behavior based on presence of a wallet.
567   - *Rationale*: as well as complicating the implementation and interfering
568     with the introduction of multi-wallet, wallet and non-wallet code should be
569     separated to avoid introducing circular dependencies between code units.