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