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++`.
30 bool Function(const std::string& s, int n)
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;
37 if (SomethingElse()) {
44 // Success return is usually at the end
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:
60 * @param[in] arg1 A description
61 * @param[in] arg2 Another argument description
62 * @pre Precondition for function...
64 bool function(int arg1, const char *arg2)
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:
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.
81 To describe a member or variable use:
83 int var; //!< Detailed description after the member
88 //! Description before the member
97 bool function2(int arg1, const char *arg2)
100 Not OK (used plenty in the current source, but not picked up):
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.
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
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.
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).
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`:
206 excludesfile = /home/.../.gitignore_global
209 (alternatively, type the command `git config --global core.excludesfile ~/.gitignore_global`
212 Then put your favourite tool's temporary filenames in that file, e.g.
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`
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.
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
245 - *Explanation*: If the test suite is to be updated for a change, this has to
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
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
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() +
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
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
346 The shadowing warning (`-Wshadow`) is enabled by default. It prevents issues rising
347 from using a different variable with the same name.
349 Please name variables so that their names do not shadow variables defined in the source code.
351 E.g. in member initializers, prepend `_` to the argument name shadowing the
355 class AddressBookPage
360 AddressBookPage::AddressBookPage(Mode _mode) :
365 When using nested cycles, do not name the inner cycle variable the same as in
369 Threads and synchronization
370 ----------------------------
372 - Build and run tests with `-DDEBUG_LOCKORDER` to verify that no potential
373 deadlocks are introduced. As of 0.12, this is defined by default when
374 configuring with `--enable-debug`
376 - When using `LOCK`/`TRY_LOCK` be aware that the lock exists in the context of
377 the current scope, so surround the statement and the code that needs the lock
384 TRY_LOCK(cs_vNodes, lockNodes);
392 TRY_LOCK(cs_vNodes, lockNodes);
398 Source code organization
399 --------------------------
401 - Implementation code should go into the `.cpp` file and not the `.h`, unless necessary due to template usage or
402 when performance due to inlining is critical
404 - *Rationale*: Shorter and simpler header files are easier to read, and reduce compile time
406 - Don't import anything into the global namespace (`using namespace ...`). Use
407 fully specified types such as `std::string`.
409 - *Rationale*: Avoids symbol conflicts
414 - Do not display or manipulate dialogs in model code (classes `*Model`)
416 - *Rationale*: Model classes pass through events and data from the core, they
417 should not interact with the user. That's where View classes come in. The converse also
418 holds: try to not directly access core data structures from Views.
423 Several parts of the repository are subtrees of software maintained elsewhere.
425 Some of these are maintained by active developers of Bitcoin Core, in which case changes should probably go
426 directly upstream without being PRed directly against the project. They will be merged back in the next
429 Others are external projects without a tight relationship with our project. Changes to these should also
430 be sent upstream but bugfixes may also be prudent to PR against Bitcoin Core so that they can be integrated
431 quickly. Cosmetic changes should be purely taken upstream.
433 There is a tool in contrib/devtools/git-subtree-check.sh to check a subtree directory for consistency with
434 its upstream repository.
436 Current subtrees include:
439 - Upstream at https://github.com/google/leveldb ; Maintained by Google, but open important PRs to Core to avoid delay
442 - Upstream at https://github.com/bitcoin-core/secp256k1/ ; actively maintaned by Core contributors.
445 - Upstream at https://github.com/bitcoin-core/ctaes ; actively maintained by Core contributors.
448 - Upstream at https://github.com/jgarzik/univalue ; report important PRs to Core to avoid delay.
452 ---------------------
454 - For resolving merge/rebase conflicts, it can be useful to enable diff3 style using
455 `git config merge.conflictstyle diff3`. Instead of
473 This may make it much clearer what caused the conflict. In this style, you can often just look
474 at what changed between *original* and *theirs*, and mechanically apply that to *yours* (or the other way around).
476 - When reviewing patches which change indentation in C++ files, use `git diff -w` and `git show -w`. This makes
477 the diff algorithm ignore whitespace changes. This feature is also available on github.com, by adding `?w=1`
478 at the end of any URL which shows a diff.
480 - When reviewing patches that change symbol names in many places, use `git diff --word-diff`. This will instead
481 of showing the patch as deleted/added *lines*, show deleted/added *words*.
483 - When reviewing patches that move code around, try using
484 `git diff --patience commit~:old/file.cpp commit:new/file/name.cpp`, and ignoring everything except the
485 moved body of code which should show up as neither `+` or `-` lines. In case it was not a pure move, this may
486 even work when combined with the `-w` or `--word-diff` options described above.
488 - When looking at other's pull requests, it may make sense to add the following section to your `.git/config`
491 [remote "upstream-pull"]
492 fetch = +refs/pull/*:refs/remotes/upstream-pull/*
493 url = git@github.com:bitcoin/bitcoin.git
495 This will add an `upstream-pull` remote to your git repository, which can be fetched using `git fetch --all`
496 or `git fetch upstream-pull`. Afterwards, you can use `upstream-pull/NUMBER/head` in arguments to `git show`,
497 `git checkout` and anywhere a commit id would be acceptable to see the changes from pull request NUMBER.