You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

developer-notes.md 26KB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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, which is specified below. When writing patches, favor the new
  6. style over attempting to mimic the surrounding style, except for move-only
  7. commits.
  8. Do not submit patches solely to modify the style of existing code.
  9. - **Indentation and whitespace rules** as specified in
  10. [src/.clang-format](/src/.clang-format). You can use the provided
  11. [clang-format-diff script](/contrib/devtools/README.md#clang-format-diffpy)
  12. tool to clean up patches automatically before submission.
  13. - Braces on new lines for namespaces, classes, functions, methods.
  14. - Braces on the same line for everything else.
  15. - 4 space indentation (no tabs) for every block except namespaces.
  16. - No indentation for `public`/`protected`/`private` or for `namespace`.
  17. - No extra spaces inside parenthesis; don't do ( this )
  18. - No space after function names; one space after `if`, `for` and `while`.
  19. - If an `if` only has a single-statement `then`-clause, it can appear
  20. on the same line as the `if`, without braces. In every other case,
  21. braces are required, and the `then` and `else` clauses must appear
  22. correctly indented on a new line.
  23. - **Symbol naming conventions**. These are preferred in new code, but are not
  24. required when doing so would need changes to significant pieces of existing
  25. code.
  26. - Variable and namespace names are all lowercase, and may use `_` to
  27. separate words (snake_case).
  28. - Class member variables have a `m_` prefix.
  29. - Global variables have a `g_` prefix.
  30. - Constant names are all uppercase, and use `_` to separate words.
  31. - Class names, function names and method names are UpperCamelCase
  32. (PascalCase). Do not prefix class names with `C`.
  33. - **Miscellaneous**
  34. - `++i` is preferred over `i++`.
  35. - `nullptr` is preferred over `NULL` or `(void*)0`.
  36. - `static_assert` is preferred over `assert` where possible. Generally; compile-time checking is preferred over run-time checking.
  37. Block style example:
  38. ```c++
  39. int g_count = 0;
  40. namespace foo
  41. {
  42. class Class
  43. {
  44. std::string m_name;
  45. public:
  46. bool Function(const std::string& s, int n)
  47. {
  48. // Comment summarising what this section of code does
  49. for (int i = 0; i < n; ++i) {
  50. int total_sum = 0;
  51. // When something fails, return early
  52. if (!Something()) return false;
  53. ...
  54. if (SomethingElse(i)) {
  55. total_sum += ComputeSomething(g_count);
  56. } else {
  57. DoSomething(m_name, total_sum);
  58. }
  59. }
  60. // Success return is usually at the end
  61. return true;
  62. }
  63. }
  64. } // namespace foo
  65. ```
  66. Doxygen comments
  67. -----------------
  68. To facilitate the generation of documentation, use doxygen-compatible comment blocks for functions, methods and fields.
  69. For example, to describe a function use:
  70. ```c++
  71. /**
  72. * ... text ...
  73. * @param[in] arg1 A description
  74. * @param[in] arg2 Another argument description
  75. * @pre Precondition for function...
  76. */
  77. bool function(int arg1, const char *arg2)
  78. ```
  79. A complete list of `@xxx` commands can be found at http://www.stack.nl/~dimitri/doxygen/manual/commands.html.
  80. As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't
  81. *need* to provide any commands for a comment to be valid; just a description text is fine.
  82. To describe a class use the same construct above the class definition:
  83. ```c++
  84. /**
  85. * Alerts are for notifying old versions if they become too obsolete and
  86. * need to upgrade. The message is displayed in the status bar.
  87. * @see GetWarnings()
  88. */
  89. class CAlert
  90. {
  91. ```
  92. To describe a member or variable use:
  93. ```c++
  94. int var; //!< Detailed description after the member
  95. ```
  96. or
  97. ```cpp
  98. //! Description before the member
  99. int var;
  100. ```
  101. Also OK:
  102. ```c++
  103. ///
  104. /// ... text ...
  105. ///
  106. bool function2(int arg1, const char *arg2)
  107. ```
  108. Not OK (used plenty in the current source, but not picked up):
  109. ```c++
  110. //
  111. // ... text ...
  112. //
  113. ```
  114. A full list of comment syntaxes picked up by doxygen can be found at http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html,
  115. but if possible use one of the above styles.
  116. Development tips and tricks
  117. ---------------------------
  118. **compiling for debugging**
  119. Run configure with the --enable-debug option, then make. Or run configure with
  120. CXXFLAGS="-g -ggdb -O0" or whatever debug flags you need.
  121. **debug.log**
  122. If the code is behaving strangely, take a look in the debug.log file in the data directory;
  123. error and debugging messages are written there.
  124. The -debug=... command-line option controls debugging; running with just -debug or -debug=1 will turn
  125. 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.
  128. **testnet and regtest modes**
  129. Run with the -testnet option to run with "play bitcoins" on the test network, if you
  130. are testing multi-machine code that needs to operate across the internet.
  131. If you are testing something that can run on one machine, run with the -regtest option.
  132. In regression test mode, blocks can be created on-demand; see test/functional/ for tests
  133. that run in -regtest mode.
  134. **DEBUG_LOCKORDER**
  135. Bitcoin Core is a multithreaded application, and deadlocks or other multithreading bugs
  136. can be very difficult to track down. Compiling with -DDEBUG_LOCKORDER (configure
  137. CXXFLAGS="-DDEBUG_LOCKORDER -g") inserts run-time checks to keep track of which locks
  138. are held, and adds warnings to the debug.log file if inconsistencies are detected.
  139. **Valgrind suppressions file**
  140. Valgrind is a programming tool for memory debugging, memory leak detection, and
  141. profiling. The repo contains a Valgrind suppressions file
  142. ([`valgrind.supp`](https://github.com/bitcoin/bitcoin/blob/master/contrib/valgrind.supp))
  143. which includes known Valgrind warnings in our dependencies that cannot be fixed
  144. in-tree. Example use:
  145. ```shell
  146. $ valgrind --suppressions=contrib/valgrind.supp src/test/test_bitcoin
  147. $ valgrind --suppressions=contrib/valgrind.supp --leak-check=full \
  148. --show-leak-kinds=all src/test/test_bitcoin --log_level=test_suite
  149. $ valgrind -v --leak-check=full src/bitcoind -printtoconsole
  150. ```
  151. **compiling for test coverage**
  152. LCOV can be used to generate a test coverage report based upon `make check`
  153. execution. LCOV must be installed on your system (e.g. the `lcov` package
  154. on Debian/Ubuntu).
  155. To enable LCOV report generation during test runs:
  156. ```shell
  157. ./configure --enable-lcov
  158. make
  159. make cov
  160. # A coverage report will now be accessible at `./test_bitcoin.coverage/index.html`.
  161. ```
  162. Locking/mutex usage notes
  163. -------------------------
  164. The code is multi-threaded, and uses mutexes and the
  165. LOCK/TRY_LOCK macros to protect data structures.
  166. Deadlocks due to inconsistent lock ordering (thread 1 locks cs_main
  167. and then cs_wallet, while thread 2 locks them in the opposite order:
  168. result, deadlock as each waits for the other to release its lock) are
  169. a problem. Compile with -DDEBUG_LOCKORDER to get lock order
  170. inconsistencies reported in the debug.log file.
  171. Re-architecting the core code so there are better-defined interfaces
  172. between the various components is a goal, with any necessary locking
  173. done by the components (e.g. see the self-contained CKeyStore class
  174. and its cs_KeyStore lock for example).
  175. Threads
  176. -------
  177. - ThreadScriptCheck : Verifies block scripts.
  178. - ThreadImport : Loads blocks from blk*.dat files or bootstrap.dat.
  179. - StartNode : Starts other threads.
  180. - ThreadDNSAddressSeed : Loads addresses of peers from the DNS.
  181. - ThreadMapPort : Universal plug-and-play startup/shutdown
  182. - ThreadSocketHandler : Sends/Receives data from peers on port 8333.
  183. - ThreadOpenAddedConnections : Opens network connections to added nodes.
  184. - ThreadOpenConnections : Initiates new connections to peers.
  185. - ThreadMessageHandler : Higher-level message handling (sending and receiving).
  186. - DumpAddresses : Dumps IP addresses of nodes to peers.dat.
  187. - ThreadFlushWalletDB : Close the wallet.dat file if it hasn't been used in 500ms.
  188. - ThreadRPCServer : Remote procedure call handler, listens on port 8332 for connections and services them.
  189. - BitcoinMiner : Generates bitcoins (if wallet is enabled).
  190. - Shutdown : Does an orderly shutdown of everything.
  191. Ignoring IDE/editor files
  192. --------------------------
  193. In closed-source environments in which everyone uses the same IDE it is common
  194. to add temporary files it produces to the project-wide `.gitignore` file.
  195. However, in open source software such as Bitcoin Core, where everyone uses
  196. their own editors/IDE/tools, it is less common. Only you know what files your
  197. editor produces and this may change from version to version. The canonical way
  198. to do this is thus to create your local gitignore. Add this to `~/.gitconfig`:
  199. ```
  200. [core]
  201. excludesfile = /home/.../.gitignore_global
  202. ```
  203. (alternatively, type the command `git config --global core.excludesfile ~/.gitignore_global`
  204. on a terminal)
  205. Then put your favourite tool's temporary filenames in that file, e.g.
  206. ```
  207. # NetBeans
  208. nbproject/
  209. ```
  210. Another option is to create a per-repository excludes file `.git/info/exclude`.
  211. These are not committed but apply only to one repository.
  212. If a set of tools is used by the build system or scripts the repository (for
  213. example, lcov) it is perfectly acceptable to add its files to `.gitignore`
  214. and commit them.
  215. Development guidelines
  216. ============================
  217. A few non-style-related recommendations for developers, as well as points to
  218. pay attention to for reviewers of Bitcoin Core code.
  219. General Bitcoin Core
  220. ----------------------
  221. - New features should be exposed on RPC first, then can be made available in the GUI
  222. - *Rationale*: RPC allows for better automatic testing. The test suite for
  223. the GUI is very limited
  224. - Make sure pull requests pass Travis CI before merging
  225. - *Rationale*: Makes sure that they pass thorough testing, and that the tester will keep passing
  226. on the master branch. Otherwise all new pull requests will start failing the tests, resulting in
  227. confusion and mayhem
  228. - *Explanation*: If the test suite is to be updated for a change, this has to
  229. be done first
  230. Wallet
  231. -------
  232. - Make sure that no crashes happen with run-time option `-disablewallet`.
  233. - *Rationale*: In RPC code that conditionally uses the wallet (such as
  234. `validateaddress`) it is easy to forget that global pointer `pwalletMain`
  235. can be nullptr. See `test/functional/disablewallet.py` for functional tests
  236. exercising the API with `-disablewallet`
  237. - Include `db_cxx.h` (BerkeleyDB header) only when `ENABLE_WALLET` is set
  238. - *Rationale*: Otherwise compilation of the disable-wallet build will fail in environments without BerkeleyDB
  239. General C++
  240. -------------
  241. - Assertions should not have side-effects
  242. - *Rationale*: Even though the source code is set to refuse to compile
  243. with assertions disabled, having side-effects in assertions is unexpected and
  244. makes the code harder to understand
  245. - If you use the `.h`, you must link the `.cpp`
  246. - *Rationale*: Include files define the interface for the code in implementation files. Including one but
  247. not linking the other is confusing. Please avoid that. Moving functions from
  248. the `.h` to the `.cpp` should not result in build errors
  249. - Use the RAII (Resource Acquisition Is Initialization) paradigm where possible. For example by using
  250. `unique_ptr` for allocations in a function.
  251. - *Rationale*: This avoids memory and resource leaks, and ensures exception safety
  252. C++ data structures
  253. --------------------
  254. - Never use the `std::map []` syntax when reading from a map, but instead use `.find()`
  255. - *Rationale*: `[]` does an insert (of the default element) if the item doesn't
  256. exist in the map yet. This has resulted in memory leaks in the past, as well as
  257. race conditions (expecting read-read behavior). Using `[]` is fine for *writing* to a map
  258. - Do not compare an iterator from one data structure with an iterator of
  259. another data structure (even if of the same type)
  260. - *Rationale*: Behavior is undefined. In C++ parlor this means "may reformat
  261. the universe", in practice this has resulted in at least one hard-to-debug crash bug
  262. - Watch out for out-of-bounds vector access. `&vch[vch.size()]` is illegal,
  263. including `&vch[0]` for an empty vector. Use `vch.data()` and `vch.data() +
  264. vch.size()` instead.
  265. - Vector bounds checking is only enabled in debug mode. Do not rely on it
  266. - Make sure that constructors initialize all fields. If this is skipped for a
  267. good reason (i.e., optimization on the critical path), add an explicit
  268. comment about this
  269. - *Rationale*: Ensure determinism by avoiding accidental use of uninitialized
  270. values. Also, static analyzers balk about this.
  271. - By default, declare single-argument constructors `explicit`.
  272. - *Rationale*: This is a precaution to avoid unintended conversions that might
  273. arise when single-argument constructors are used as implicit conversion
  274. functions.
  275. - Use explicitly signed or unsigned `char`s, or even better `uint8_t` and
  276. `int8_t`. Do not use bare `char` unless it is to pass to a third-party API.
  277. This type can be signed or unsigned depending on the architecture, which can
  278. lead to interoperability problems or dangerous conditions such as
  279. out-of-bounds array accesses
  280. - Prefer explicit constructions over implicit ones that rely on 'magical' C++ behavior
  281. - *Rationale*: Easier to understand what is happening, thus easier to spot mistakes, even for those
  282. that are not language lawyers
  283. Strings and formatting
  284. ------------------------
  285. - Be careful of `LogPrint` versus `LogPrintf`. `LogPrint` takes a `category` argument, `LogPrintf` does not.
  286. - *Rationale*: Confusion of these can result in runtime exceptions due to
  287. formatting mismatch, and it is easy to get wrong because of subtly similar naming
  288. - Use `std::string`, avoid C string manipulation functions
  289. - *Rationale*: C++ string handling is marginally safer, less scope for
  290. buffer overflows and surprises with `\0` characters. Also some C string manipulations
  291. tend to act differently depending on platform, or even the user locale
  292. - Use `ParseInt32`, `ParseInt64`, `ParseUInt32`, `ParseUInt64`, `ParseDouble` from `utilstrencodings.h` for number parsing
  293. - *Rationale*: These functions do overflow checking, and avoid pesky locale issues
  294. - For `strprintf`, `LogPrint`, `LogPrintf` formatting characters don't need size specifiers
  295. - *Rationale*: Bitcoin Core uses tinyformat, which is type safe. Leave them out to avoid confusion
  296. Variable names
  297. --------------
  298. Although the shadowing warning (`-Wshadow`) is not enabled by default (it prevents issues rising
  299. from using a different variable with the same name),
  300. please name variables so that their names do not shadow variables defined in the source code.
  301. E.g. in member initializers, prepend `_` to the argument name shadowing the
  302. member name:
  303. ```c++
  304. class AddressBookPage
  305. {
  306. Mode mode;
  307. }
  308. AddressBookPage::AddressBookPage(Mode _mode) :
  309. mode(_mode)
  310. ...
  311. ```
  312. When using nested cycles, do not name the inner cycle variable the same as in
  313. upper cycle etc.
  314. Threads and synchronization
  315. ----------------------------
  316. - Build and run tests with `-DDEBUG_LOCKORDER` to verify that no potential
  317. deadlocks are introduced. As of 0.12, this is defined by default when
  318. configuring with `--enable-debug`
  319. - When using `LOCK`/`TRY_LOCK` be aware that the lock exists in the context of
  320. the current scope, so surround the statement and the code that needs the lock
  321. with braces
  322. OK:
  323. ```c++
  324. {
  325. TRY_LOCK(cs_vNodes, lockNodes);
  326. ...
  327. }
  328. ```
  329. Wrong:
  330. ```c++
  331. TRY_LOCK(cs_vNodes, lockNodes);
  332. {
  333. ...
  334. }
  335. ```
  336. Source code organization
  337. --------------------------
  338. - Implementation code should go into the `.cpp` file and not the `.h`, unless necessary due to template usage or
  339. when performance due to inlining is critical
  340. - *Rationale*: Shorter and simpler header files are easier to read, and reduce compile time
  341. - Every `.cpp` and `.h` file should `#include` every header file it directly uses classes, functions or other
  342. definitions from, even if those headers are already included indirectly through other headers. One exception
  343. is that a `.cpp` file does not need to re-include the includes already included in its corresponding `.h` file.
  344. - *Rationale*: Excluding headers because they are already indirectly included results in compilation
  345. failures when those indirect dependencies change. Furthermore, it obscures what the real code
  346. dependencies are.
  347. - Don't import anything into the global namespace (`using namespace ...`). Use
  348. fully specified types such as `std::string`.
  349. - *Rationale*: Avoids symbol conflicts
  350. - Terminate namespaces with a comment (`// namespace mynamespace`). The comment
  351. should be placed on the same line as the brace closing the namespace, e.g.
  352. ```c++
  353. namespace mynamespace {
  354. ...
  355. } // namespace mynamespace
  356. namespace {
  357. ...
  358. } // namespace
  359. ```
  360. - *Rationale*: Avoids confusion about the namespace context
  361. - Prefer `#include <primitives/transaction.h>` bracket syntax instead of
  362. `#include "primitives/transactions.h"` quote syntax when possible.
  363. - *Rationale*: Bracket syntax is less ambiguous because the preprocessor
  364. searches a fixed list of include directories without taking location of the
  365. source file into account. This allows quoted includes to stand out more when
  366. the location of the source file actually is relevant.
  367. GUI
  368. -----
  369. - Do not display or manipulate dialogs in model code (classes `*Model`)
  370. - *Rationale*: Model classes pass through events and data from the core, they
  371. should not interact with the user. That's where View classes come in. The converse also
  372. holds: try to not directly access core data structures from Views.
  373. Subtrees
  374. ----------
  375. Several parts of the repository are subtrees of software maintained elsewhere.
  376. Some of these are maintained by active developers of Bitcoin Core, in which case changes should probably go
  377. directly upstream without being PRed directly against the project. They will be merged back in the next
  378. subtree merge.
  379. Others are external projects without a tight relationship with our project. Changes to these should also
  380. be sent upstream but bugfixes may also be prudent to PR against Bitcoin Core so that they can be integrated
  381. quickly. Cosmetic changes should be purely taken upstream.
  382. There is a tool in contrib/devtools/git-subtree-check.sh to check a subtree directory for consistency with
  383. its upstream repository.
  384. Current subtrees include:
  385. - src/leveldb
  386. - Upstream at https://github.com/google/leveldb ; Maintained by Google, but open important PRs to Core to avoid delay
  387. - src/libsecp256k1
  388. - Upstream at https://github.com/bitcoin-core/secp256k1/ ; actively maintaned by Core contributors.
  389. - src/crypto/ctaes
  390. - Upstream at https://github.com/bitcoin-core/ctaes ; actively maintained by Core contributors.
  391. - src/univalue
  392. - Upstream at https://github.com/jgarzik/univalue ; report important PRs to Core to avoid delay.
  393. Git and GitHub tips
  394. ---------------------
  395. - For resolving merge/rebase conflicts, it can be useful to enable diff3 style using
  396. `git config merge.conflictstyle diff3`. Instead of
  397. <<<
  398. yours
  399. ===
  400. theirs
  401. >>>
  402. you will see
  403. <<<
  404. yours
  405. |||
  406. original
  407. ===
  408. theirs
  409. >>>
  410. This may make it much clearer what caused the conflict. In this style, you can often just look
  411. at what changed between *original* and *theirs*, and mechanically apply that to *yours* (or the other way around).
  412. - When reviewing patches which change indentation in C++ files, use `git diff -w` and `git show -w`. This makes
  413. the diff algorithm ignore whitespace changes. This feature is also available on github.com, by adding `?w=1`
  414. at the end of any URL which shows a diff.
  415. - When reviewing patches that change symbol names in many places, use `git diff --word-diff`. This will instead
  416. of showing the patch as deleted/added *lines*, show deleted/added *words*.
  417. - When reviewing patches that move code around, try using
  418. `git diff --patience commit~:old/file.cpp commit:new/file/name.cpp`, and ignoring everything except the
  419. moved body of code which should show up as neither `+` or `-` lines. In case it was not a pure move, this may
  420. even work when combined with the `-w` or `--word-diff` options described above.
  421. - When looking at other's pull requests, it may make sense to add the following section to your `.git/config`
  422. file:
  423. [remote "upstream-pull"]
  424. fetch = +refs/pull/*:refs/remotes/upstream-pull/*
  425. url = git@github.com:bitcoin/bitcoin.git
  426. This will add an `upstream-pull` remote to your git repository, which can be fetched using `git fetch --all`
  427. or `git fetch upstream-pull`. Afterwards, you can use `upstream-pull/NUMBER/head` in arguments to `git show`,
  428. `git checkout` and anywhere a commit id would be acceptable to see the changes from pull request NUMBER.
  429. Scripted diffs
  430. --------------
  431. For reformatting and refactoring commits where the changes can be easily automated using a bash script, we use
  432. scripted-diff commits. The bash script is included in the commit message and our Travis CI job checks that
  433. the result of the script is identical to the commit. This aids reviewers since they can verify that the script
  434. does exactly what it's supposed to do. It is also helpful for rebasing (since the same script can just be re-run
  435. on the new master commit).
  436. To create a scripted-diff:
  437. - start the commit message with `scripted-diff:` (and then a description of the diff on the same line)
  438. - in the commit message include the bash script between lines containing just the following text:
  439. - `-BEGIN VERIFY SCRIPT-`
  440. - `-END VERIFY SCRIPT-`
  441. The scripted-diff is verified by the tool `contrib/devtools/commit-script-check.sh`
  442. Commit `bb81e173` is an example of a scripted-diff.
  443. RPC interface guidelines
  444. --------------------------
  445. A few guidelines for introducing and reviewing new RPC interfaces:
  446. - Method naming: use consecutive lower-case names such as `getrawtransaction` and `submitblock`
  447. - *Rationale*: Consistency with existing interface.
  448. - Argument naming: use snake case `fee_delta` (and not, e.g. camel case `feeDelta`)
  449. - *Rationale*: Consistency with existing interface.
  450. - Use the JSON parser for parsing, don't manually parse integers or strings from
  451. arguments unless absolutely necessary.
  452. - *Rationale*: Introduces hand-rolled string manipulation code at both the caller and callee sites,
  453. which is error prone, and it is easy to get things such as escaping wrong.
  454. JSON already supports nested data structures, no need to re-invent the wheel.
  455. - *Exception*: AmountFromValue can parse amounts as string. This was introduced because many JSON
  456. parsers and formatters hard-code handling decimal numbers as floating point
  457. values, resulting in potential loss of precision. This is unacceptable for
  458. monetary values. **Always** use `AmountFromValue` and `ValueFromAmount` when
  459. inputting or outputting monetary values. The only exceptions to this are
  460. `prioritisetransaction` and `getblocktemplate` because their interface
  461. is specified as-is in BIP22.
  462. - Missing arguments and 'null' should be treated the same: as default values. If there is no
  463. default value, both cases should fail in the same way. The easiest way to follow this
  464. guideline is detect unspecified arguments with `params[x].isNull()` instead of
  465. `params.size() <= x`. The former returns true if the argument is either null or missing,
  466. while the latter returns true if is missing, and false if it is null.
  467. - *Rationale*: Avoids surprises when switching to name-based arguments. Missing name-based arguments
  468. are passed as 'null'.
  469. - Try not to overload methods on argument type. E.g. don't make `getblock(true)` and `getblock("hash")`
  470. do different things.
  471. - *Rationale*: This is impossible to use with `bitcoin-cli`, and can be surprising to users.
  472. - *Exception*: Some RPC calls can take both an `int` and `bool`, most notably when a bool was switched
  473. to a multi-value, or due to other historical reasons. **Always** have false map to 0 and
  474. true to 1 in this case.
  475. - Don't forget to fill in the argument names correctly in the RPC command table.
  476. - *Rationale*: If not, the call can not be used with name-based arguments.
  477. - Set okSafeMode in the RPC command table to a sensible value: safe mode is when the
  478. blockchain is regarded to be in a confused state, and the client deems it unsafe to
  479. do anything irreversible such as send. Anything that just queries should be permitted.
  480. - *Rationale*: Troubleshooting a node in safe mode is difficult if half the
  481. RPCs don't work.
  482. - Add every non-string RPC argument `(method, idx, name)` to the table `vRPCConvertParams` in `rpc/client.cpp`.
  483. - *Rationale*: `bitcoin-cli` and the GUI debug console use this table to determine how to
  484. convert a plaintext command line to JSON. If the types don't match, the method can be unusable
  485. from there.
  486. - A RPC method must either be a wallet method or a non-wallet method. Do not
  487. introduce new methods such as `signrawtransaction` that differ in behavior
  488. based on presence of a wallet.
  489. - *Rationale*: as well as complicating the implementation and interfering
  490. with the introduction of multi-wallet, wallet and non-wallet code should be
  491. separated to avoid introducing circular dependencies between code units.
  492. - Try to make the RPC response a JSON object.
  493. - *Rationale*: If a RPC response is not a JSON object then it is harder to avoid API breakage if
  494. new data in the response is needed.
  495. - Wallet RPCs call BlockUntilSyncedToCurrentChain to maintain consistency with
  496. `getblockchaininfo`'s state immediately prior to the call's execution. Wallet
  497. RPCs whose behavior does *not* depend on the current chainstate may omit this
  498. call.
  499. - *Rationale*: In previous versions of Bitcoin Core, the wallet was always
  500. in-sync with the chainstate (by virtue of them all being updated in the
  501. same cs_main lock). In order to maintain the behavior that wallet RPCs
  502. return results as of at least the highest best-known block an RPC
  503. client may be aware of prior to entering a wallet RPC call, we must block
  504. until the wallet is caught up to the chainstate as of the RPC call's entry.
  505. This also makes the API much easier for RPC clients to reason about.