PageRenderTime 69ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/doc/developer-notes.md

https://gitlab.com/yenny.prathivi/bitcoin
Markdown | 375 lines | 269 code | 106 blank | 0 comment | 0 complexity | 53f40a4c155f31d374831be64033db71 MD5 | raw file
  1. Developer Notes
  2. ===============
  3. Various coding styles have been used during the history of the codebase,
  4. and the result is not very consistent. However, we're now trying to converge to
  5. a single style, so please use it in new code. Old code will be converted
  6. gradually.
  7. - Basic rules specified in src/.clang-format. Use a recent clang-format-3.5 to format automatically.
  8. - Braces on new lines for namespaces, classes, functions, methods.
  9. - Braces on the same line for everything else.
  10. - 4 space indentation (no tabs) for every block except namespaces.
  11. - No indentation for public/protected/private or for namespaces.
  12. - No extra spaces inside parenthesis; don't do ( this )
  13. - No space after function names; one space after if, for and while.
  14. Block style example:
  15. ```c++
  16. namespace foo
  17. {
  18. class Class
  19. {
  20. bool Function(char* psz, int n)
  21. {
  22. // Comment summarising what this section of code does
  23. for (int i = 0; i < n; i++) {
  24. // When something fails, return early
  25. if (!Something())
  26. return false;
  27. ...
  28. }
  29. // Success return is usually at the end
  30. return true;
  31. }
  32. }
  33. }
  34. ```
  35. Doxygen comments
  36. -----------------
  37. To facilitate the generation of documentation, use doxygen-compatible comment blocks for functions, methods and fields.
  38. For example, to describe a function use:
  39. ```c++
  40. /**
  41. * ... text ...
  42. * @param[in] arg1 A description
  43. * @param[in] arg2 Another argument description
  44. * @pre Precondition for function...
  45. */
  46. bool function(int arg1, const char *arg2)
  47. ```
  48. A complete list of `@xxx` commands can be found at http://www.stack.nl/~dimitri/doxygen/manual/commands.html.
  49. As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't
  50. *need* to provide any commands for a comment to be valid; just a description text is fine.
  51. To describe a class use the same construct above the class definition:
  52. ```c++
  53. /**
  54. * Alerts are for notifying old versions if they become too obsolete and
  55. * need to upgrade. The message is displayed in the status bar.
  56. * @see GetWarnings()
  57. */
  58. class CAlert
  59. {
  60. ```
  61. To describe a member or variable use:
  62. ```c++
  63. int var; //!< Detailed description after the member
  64. ```
  65. Also OK:
  66. ```c++
  67. ///
  68. /// ... text ...
  69. ///
  70. bool function2(int arg1, const char *arg2)
  71. ```
  72. Not OK (used plenty in the current source, but not picked up):
  73. ```c++
  74. //
  75. // ... text ...
  76. //
  77. ```
  78. A full list of comment syntaxes picked up by doxygen can be found at http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html,
  79. but if possible use one of the above styles.
  80. Development tips and tricks
  81. ---------------------------
  82. **compiling for debugging**
  83. Run configure with the --enable-debug option, then make. Or run configure with
  84. CXXFLAGS="-g -ggdb -O0" or whatever debug flags you need.
  85. **debug.log**
  86. If the code is behaving strangely, take a look in the debug.log file in the data directory;
  87. error and debugging messages are written there.
  88. The -debug=... command-line option controls debugging; running with just -debug or -debug=1 will turn
  89. on all categories (and give you a very large debug.log file).
  90. The Qt code routes qDebug() output to debug.log under category "qt": run with -debug=qt
  91. to see it.
  92. **testnet and regtest modes**
  93. Run with the -testnet option to run with "play bitcoins" on the test network, if you
  94. are testing multi-machine code that needs to operate across the internet.
  95. If you are testing something that can run on one machine, run with the -regtest option.
  96. In regression test mode, blocks can be created on-demand; see qa/rpc-tests/ for tests
  97. that run in -regtest mode.
  98. **DEBUG_LOCKORDER**
  99. Bitcoin Core is a multithreaded application, and deadlocks or other multithreading bugs
  100. can be very difficult to track down. Compiling with -DDEBUG_LOCKORDER (configure
  101. CXXFLAGS="-DDEBUG_LOCKORDER -g") inserts run-time checks to keep track of which locks
  102. are held, and adds warnings to the debug.log file if inconsistencies are detected.
  103. Locking/mutex usage notes
  104. -------------------------
  105. The code is multi-threaded, and uses mutexes and the
  106. LOCK/TRY_LOCK macros to protect data structures.
  107. Deadlocks due to inconsistent lock ordering (thread 1 locks cs_main
  108. and then cs_wallet, while thread 2 locks them in the opposite order:
  109. result, deadlock as each waits for the other to release its lock) are
  110. a problem. Compile with -DDEBUG_LOCKORDER to get lock order
  111. inconsistencies reported in the debug.log file.
  112. Re-architecting the core code so there are better-defined interfaces
  113. between the various components is a goal, with any necessary locking
  114. done by the components (e.g. see the self-contained CKeyStore class
  115. and its cs_KeyStore lock for example).
  116. Threads
  117. -------
  118. - ThreadScriptCheck : Verifies block scripts.
  119. - ThreadImport : Loads blocks from blk*.dat files or bootstrap.dat.
  120. - StartNode : Starts other threads.
  121. - ThreadDNSAddressSeed : Loads addresses of peers from the DNS.
  122. - ThreadMapPort : Universal plug-and-play startup/shutdown
  123. - ThreadSocketHandler : Sends/Receives data from peers on port 8333.
  124. - ThreadOpenAddedConnections : Opens network connections to added nodes.
  125. - ThreadOpenConnections : Initiates new connections to peers.
  126. - ThreadMessageHandler : Higher-level message handling (sending and receiving).
  127. - DumpAddresses : Dumps IP addresses of nodes to peers.dat.
  128. - ThreadFlushWalletDB : Close the wallet.dat file if it hasn't been used in 500ms.
  129. - ThreadRPCServer : Remote procedure call handler, listens on port 8332 for connections and services them.
  130. - BitcoinMiner : Generates bitcoins (if wallet is enabled).
  131. - Shutdown : Does an orderly shutdown of everything.
  132. Ignoring IDE/editor files
  133. --------------------------
  134. In closed-source environments in which everyone uses the same IDE it is common
  135. to add temporary files it produces to the project-wide `.gitignore` file.
  136. However, in open source software such as Bitcoin Core, where everyone uses
  137. their own editors/IDE/tools, it is less common. Only you know what files your
  138. editor produces and this may change from version to version. The canonical way
  139. to do this is thus to create your local gitignore. Add this to `~/.gitconfig`:
  140. ```
  141. [core]
  142. excludesfile = /home/.../.gitignore_global
  143. ```
  144. (alternatively, type the command `git config --global core.excludesfile ~/.gitignore_global`
  145. on a terminal)
  146. Then put your favourite tool's temporary filenames in that file, e.g.
  147. ```
  148. # NetBeans
  149. nbproject/
  150. ```
  151. Another option is to create a per-repository excludes file `.git/info/exclude`.
  152. These are not committed but apply only to one repository.
  153. If a set of tools is used by the build system or scripts the repository (for
  154. example, lcov) it is perfectly acceptable to add its files to `.gitignore`
  155. and commit them.
  156. Development guidelines
  157. ============================
  158. A few non-style-related recommendations for developers, as well as points to
  159. pay attention to for reviewers of Bitcoin Core code.
  160. General Bitcoin Core
  161. ----------------------
  162. - New features should be exposed on RPC first, then can be made available in the GUI
  163. - *Rationale*: RPC allows for better automatic testing. The test suite for
  164. the GUI is very limited
  165. - Make sure pull requests pass Travis CI before merging
  166. - *Rationale*: Makes sure that they pass thorough testing, and that the tester will keep passing
  167. on the master branch. Otherwise all new pull requests will start failing the tests, resulting in
  168. confusion and mayhem
  169. - *Explanation*: If the test suite is to be updated for a change, this has to
  170. be done first
  171. Wallet
  172. -------
  173. - Make sure that no crashes happen with run-time option `-disablewallet`.
  174. - *Rationale*: In RPC code that conditionally uses the wallet (such as
  175. `validateaddress`) it is easy to forget that global pointer `pwalletMain`
  176. can be NULL. See `qa/rpc-tests/disablewallet.py` for functional tests
  177. exercising the API with `-disablewallet`
  178. - Include `db_cxx.h` (BerkeleyDB header) only when `ENABLE_WALLET` is set
  179. - *Rationale*: Otherwise compilation of the disable-wallet build will fail in environments without BerkeleyDB
  180. General C++
  181. -------------
  182. - Assertions should not have side-effects
  183. - *Rationale*: Even though the source code is set to to refuse to compile
  184. with assertions disabled, having side-effects in assertions is unexpected and
  185. makes the code harder to understand
  186. - If you use the `.h`, you must link the `.cpp`
  187. - *Rationale*: Include files define the interface for the code in implementation files. Including one but
  188. not linking the other is confusing. Please avoid that. Moving functions from
  189. the `.h` to the `.cpp` should not result in build errors
  190. - Use the RAII (Resource Acquisition Is Initialization) paradigm where possible. For example by using
  191. `scoped_pointer` for allocations in a function.
  192. - *Rationale*: This avoids memory and resource leaks, and ensures exception safety
  193. C++ data structures
  194. --------------------
  195. - Never use the `std::map []` syntax when reading from a map, but instead use `.find()`
  196. - *Rationale*: `[]` does an insert (of the default element) if the item doesn't
  197. exist in the map yet. This has resulted in memory leaks in the past, as well as
  198. race conditions (expecting read-read behavior). Using `[]` is fine for *writing* to a map
  199. - Do not compare an iterator from one data structure with an iterator of
  200. another data structure (even if of the same type)
  201. - *Rationale*: Behavior is undefined. In C++ parlor this means "may reformat
  202. the universe", in practice this has resulted in at least one hard-to-debug crash bug
  203. - Watch out for vector out-of-bounds exceptions. `&vch[0]` is illegal for an
  204. empty vector, `&vch[vch.size()]` is always illegal. Use `begin_ptr(vch)` and
  205. `end_ptr(vch)` to get the begin and end pointer instead (defined in
  206. `serialize.h`)
  207. - Vector bounds checking is only enabled in debug mode. Do not rely on it
  208. - Make sure that constructors initialize all fields. If this is skipped for a
  209. good reason (i.e., optimization on the critical path), add an explicit
  210. comment about this
  211. - *Rationale*: Ensure determinism by avoiding accidental use of uninitialized
  212. values. Also, static analyzers balk about this.
  213. - Use explicitly signed or unsigned `char`s, or even better `uint8_t` and
  214. `int8_t`. Do not use bare `char` unless it is to pass to a third-party API.
  215. This type can be signed or unsigned depending on the architecture, which can
  216. lead to interoperability problems or dangerous conditions such as
  217. out-of-bounds array accesses
  218. - Prefer explicit constructions over implicit ones that rely on 'magical' C++ behavior
  219. - *Rationale*: Easier to understand what is happening, thus easier to spot mistakes, even for those
  220. that are not language lawyers
  221. Strings and formatting
  222. ------------------------
  223. - Be careful of `LogPrint` versus `LogPrintf`. `LogPrint` takes a `category` argument, `LogPrintf` does not.
  224. - *Rationale*: Confusion of these can result in runtime exceptions due to
  225. formatting mismatch, and it is easy to get wrong because of subtly similar naming
  226. - Use `std::string`, avoid C string manipulation functions
  227. - *Rationale*: C++ string handling is marginally safer, less scope for
  228. buffer overflows and surprises with `\0` characters. Also some C string manipulations
  229. tend to act differently depending on platform, or even the user locale
  230. - Use `ParseInt32`, `ParseInt64`, `ParseDouble` from `utilstrencodings.h` for number parsing
  231. - *Rationale*: These functions do overflow checking, and avoid pesky locale issues
  232. - For `strprintf`, `LogPrint`, `LogPrintf` formatting characters don't need size specifiers
  233. - *Rationale*: Bitcoin Core uses tinyformat, which is type safe. Leave them out to avoid confusion
  234. Threads and synchronization
  235. ----------------------------
  236. - Build and run tests with `-DDEBUG_LOCKORDER` to verify that no potential
  237. deadlocks are introduced. As of 0.12, this is defined by default when
  238. configuring with `--enable-debug`
  239. - When using `LOCK`/`TRY_LOCK` be aware that the lock exists in the context of
  240. the current scope, so surround the statement and the code that needs the lock
  241. with braces
  242. OK:
  243. ```c++
  244. {
  245. TRY_LOCK(cs_vNodes, lockNodes);
  246. ...
  247. }
  248. ```
  249. Wrong:
  250. ```c++
  251. TRY_LOCK(cs_vNodes, lockNodes);
  252. {
  253. ...
  254. }
  255. ```
  256. Source code organization
  257. --------------------------
  258. - Implementation code should go into the `.cpp` file and not the `.h`, unless necessary due to template usage or
  259. when performance due to inlining is critical
  260. - *Rationale*: Shorter and simpler header files are easier to read, and reduce compile time
  261. - Don't import anything into the global namespace (`using namespace ...`). Use
  262. fully specified types such as `std::string`.
  263. - *Rationale*: Avoids symbol conflicts
  264. GUI
  265. -----
  266. - Do not display or manipulate dialogs in model code (classes `*Model`)
  267. - *Rationale*: Model classes pass through events and data from the core, they
  268. should not interact with the user. That's where View classes come in. The converse also
  269. holds: try to not directly access core data structures from Views.