diff --git a/.gitmodules b/.gitmodules index efd7751578..a23e7609d2 100644 --- a/.gitmodules +++ b/.gitmodules @@ -2,3 +2,6 @@ path = test/vendor url = https://github.com/nervosnetwork/ckb-tests.git shallow = true +[submodule "docs/ckb_rpc_openrpc"] + path = docs/ckb_rpc_openrpc + url = https://github.com/nervosnetwork/ckb-rpc-resources.git diff --git a/Cargo.lock b/Cargo.lock index 9975c37510..1f913ffcf9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -67,6 +67,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + [[package]] name = "anes" version = "0.1.6" @@ -347,6 +362,16 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3" +[[package]] +name = "bstr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c79ad7fb2dd38f3dabd76b09c6a5a20c038fc0213ef1e9afd30eb777f120f019" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "bumpalo" version = "3.14.0" @@ -450,6 +475,40 @@ dependencies = [ "zeroize", ] +[[package]] +name = "chrono" +version = "0.4.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "num-traits", + "windows-targets 0.48.5", +] + +[[package]] +name = "chrono-tz" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29c39203181991a7dd4343b8005bd804e7a9a37afb8ac070e43771e8c820bbde" +dependencies = [ + "chrono", + "chrono-tz-build", + "phf 0.11.2", +] + +[[package]] +name = "chrono-tz-build" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f509c3a87b33437b05e2458750a0700e5bdd6956176773e6c7d6dd15a283a0c" +dependencies = [ + "parse-zoneinfo", + "phf 0.11.2", + "phf_codegen 0.11.2", +] + [[package]] name = "ciborium" version = "0.2.1" @@ -788,6 +847,7 @@ dependencies = [ name = "ckb-fixed-hash-core" version = "0.114.0-pre" dependencies = [ + "ckb_schemars", "faster-hex", "serde", "serde_json", @@ -883,6 +943,7 @@ name = "ckb-jsonrpc-types" version = "0.114.0-pre" dependencies = [ "ckb-types", + "ckb_schemars", "faster-hex", "lazy_static", "proptest", @@ -1241,7 +1302,7 @@ dependencies = [ "ckb-types", "includedir", "includedir_codegen", - "phf", + "phf 0.8.0", "serde", "tempfile", "walkdir", @@ -1311,6 +1372,7 @@ dependencies = [ "ckb-util", "ckb-verification", "ckb-verification-traits", + "ckb_schemars", "futures-util", "itertools 0.11.0", "jsonrpc-core", @@ -1325,6 +1387,16 @@ dependencies = [ "tower-http", ] +[[package]] +name = "ckb-rpc-gen" +version = "0.114.0-pre" +dependencies = [ + "ckb-rpc", + "ckb_schemars", + "serde_json", + "tera", +] + [[package]] name = "ckb-rust-unstable-port" version = "0.114.0-pre" @@ -1494,7 +1566,7 @@ dependencies = [ "faster-hex", "includedir", "includedir_codegen", - "phf", + "phf 0.8.0", ] [[package]] @@ -1682,6 +1754,30 @@ dependencies = [ "paste", ] +[[package]] +name = "ckb_schemars" +version = "0.8.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "160bd7cb5051a4bd6fe80a3c3e794cd26864dba70360d0e5ea34e21a71d7e4a3" +dependencies = [ + "ckb_schemars_derive", + "dyn-clone", + "serde", + "serde_json", +] + +[[package]] +name = "ckb_schemars_derive" +version = "0.8.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4003e04a097903cf2d96d20f5c587c5f744cdef972ce8029bd30a4674634c9" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 1.0.109", +] + [[package]] name = "clang-sys" version = "1.6.1" @@ -1721,6 +1817,16 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" +[[package]] +name = "codespan-reporting" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +dependencies = [ + "termcolor", + "unicode-width", +] + [[package]] name = "colorchoice" version = "1.0.0" @@ -1945,6 +2051,50 @@ dependencies = [ "zeroize", ] +[[package]] +name = "cxx" +version = "1.0.112" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58ab30434ea0ff6aa640a08dda5284026a366d47565496fd40b6cbfbdd7e31a2" +dependencies = [ + "cc", + "cxxbridge-flags", + "cxxbridge-macro", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.112" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b649d7dfae8268450d53d109388b337b9352c7cba1fc10db4a1bc23c3dc189fb" +dependencies = [ + "cc", + "codespan-reporting", + "once_cell", + "proc-macro2", + "quote", + "scratch", + "syn 2.0.38", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.112" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42281b20eba5218c539295c667c18e2f50211bb11902419194c6ed1ae808e547" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.112" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b45506e3c66512b0a65d291a6b452128b7b1dd9841e20d1e151addbd2c00ea50" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] + [[package]] name = "daemonize" version = "0.5.0" @@ -2037,6 +2187,12 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "deunicode" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d95203a6a50906215a502507c0f879a0ce7ff205a6111e2db2a5ef8e4bb92e43" + [[package]] name = "diff" version = "0.1.13" @@ -2072,6 +2228,12 @@ dependencies = [ "const-random", ] +[[package]] +name = "dyn-clone" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d2f3407d9a573d666de4b5bdf10569d73ca9478087346697dcbae6244bfbcd" + [[package]] name = "eaglesong" version = "0.1.0" @@ -2401,6 +2563,30 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +[[package]] +name = "globset" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "759c97c1e17c55525b57192c06a267cda0ac5210b222d6b82189a2338fa1c13d" +dependencies = [ + "aho-corasick", + "bstr", + "fnv", + "log", + "regex", +] + +[[package]] +name = "globwalk" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e3af942408868f6934a7b85134a3230832b9977cf66125df2f9edcfce4ddcc" +dependencies = [ + "bitflags 1.3.2", + "ignore", + "walkdir", +] + [[package]] name = "goblin" version = "0.2.3" @@ -2601,6 +2787,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "humansize" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02296996cb8796d7c6e3bc2d9211b7802812d36999a51bb754123ead7d37d026" + [[package]] name = "humantime" version = "2.1.0" @@ -2644,6 +2836,30 @@ dependencies = [ "tokio-native-tls", ] +[[package]] +name = "iana-time-zone" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows 0.48.0", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" +dependencies = [ + "cxx", + "cxx-build", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -2684,6 +2900,23 @@ dependencies = [ "xmltree", ] +[[package]] +name = "ignore" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbe7873dab538a9a44ad79ede1faf5f30d49f9a5c883ddbab48bce81b64b7492" +dependencies = [ + "globset", + "lazy_static", + "log", + "memchr", + "regex", + "same-file", + "thread_local", + "walkdir", + "winapi-util", +] + [[package]] name = "includedir" version = "0.6.0" @@ -2691,7 +2924,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "afd126bd778c00c43a9dc76d1609a0894bf4222088088b2217ccc0ce9e816db7" dependencies = [ "flate2", - "phf", + "phf 0.8.0", ] [[package]] @@ -2701,7 +2934,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ac1500c9780957c9808c4ec3b94002f35aab01483833f5a8bce7dfb243e3148" dependencies = [ "flate2", - "phf_codegen", + "phf_codegen 0.8.0", "walkdir", ] @@ -2929,6 +3162,15 @@ version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" +[[package]] +name = "link-cplusplus" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d240c6f7e1ba3a28b0249f774e6a9dd0175054b52dfbb61b16eb8505c3785c9" +dependencies = [ + "cc", +] + [[package]] name = "linked-hash-map" version = "0.5.6" @@ -3404,6 +3646,15 @@ dependencies = [ "windows-targets 0.48.5", ] +[[package]] +name = "parse-zoneinfo" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c705f256449c60da65e11ff6626e0c16a0a0b96aaa348de61376b249bc340f41" +dependencies = [ + "regex", +] + [[package]] name = "paste" version = "1.0.14" @@ -3428,6 +3679,51 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" +[[package]] +name = "pest" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c022f1e7b65d6a24c0dbbd5fb344c66881bc01f3e5ae74a1c8100f2f985d98a4" +dependencies = [ + "memchr", + "thiserror", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35513f630d46400a977c4cb58f78e1bfbe01434316e60c37d27b9ad6139c66d8" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc9fc1b9e7057baba189b5c626e2d6f40681ae5b6eb064dc7c7834101ec8123a" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 2.0.38", +] + +[[package]] +name = "pest_meta" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1df74e9e7ec4053ceb980e7c0c8bd3594e977fde1af91daba9c928e8e8c6708d" +dependencies = [ + "once_cell", + "pest", + "sha2", +] + [[package]] name = "petgraph" version = "0.6.4" @@ -3444,7 +3740,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12" dependencies = [ - "phf_shared", + "phf_shared 0.8.0", +] + +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_shared 0.11.2", ] [[package]] @@ -3453,8 +3758,18 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cbffee61585b0411840d3ece935cce9cb6321f01c45477d30066498cd5e1a815" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.8.0", + "phf_shared 0.8.0", +] + +[[package]] +name = "phf_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a" +dependencies = [ + "phf_generator 0.11.2", + "phf_shared 0.11.2", ] [[package]] @@ -3463,10 +3778,20 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17367f0cc86f2d25802b2c26ee58a7b23faeccf78a396094c13dced0d0182526" dependencies = [ - "phf_shared", + "phf_shared 0.8.0", "rand 0.7.3", ] +[[package]] +name = "phf_generator" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +dependencies = [ + "phf_shared 0.11.2", + "rand 0.8.5", +] + [[package]] name = "phf_shared" version = "0.8.0" @@ -3476,20 +3801,30 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", + "uncased", +] + [[package]] name = "pin-project" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" +checksum = "0302c4a0442c456bd56f841aee5c3bfd17967563f6fadc9ceb9f9c23cf3807e0" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" +checksum = "266c042b60c9c76b8d53061e52b2e0d1116abc57cefc8c5cd671619a56ac3690" dependencies = [ "proc-macro2", "quote", @@ -3857,7 +4192,7 @@ checksum = "f97f7665e51f23760e9e4949d454a4782c76ef954acaeec9d1b0f48a58e4529e" dependencies = [ "cfg-if", "rustix", - "windows", + "windows 0.51.1", ] [[package]] @@ -4076,6 +4411,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scratch" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3cf7c11c38cb994f3d40e8a8cde3bbd1f72a435e4c49e85d6553d8312306152" + [[package]] name = "scroll" version = "0.10.2" @@ -4254,6 +4595,17 @@ dependencies = [ "syn 2.0.38", ] +[[package]] +name = "serde_derive_internals" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85bf8229e7920a9f636479437026331ce11aa132b4dde37d121944a44d6e5f3c" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "serde_json" version = "1.0.107" @@ -4374,6 +4726,15 @@ dependencies = [ "parking_lot 0.11.2", ] +[[package]] +name = "slug" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3bc762e6a4b6c6fcaade73e77f9ebc6991b676f88bb2358bddb56560f073373" +dependencies = [ + "deunicode", +] + [[package]] name = "smallvec" version = "1.11.1" @@ -4580,6 +4941,28 @@ dependencies = [ "x25519-dalek", ] +[[package]] +name = "tera" +version = "1.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3df578c295f9ec044ff1c829daf31bb7581d5b3c2a7a3d87419afe1f2531438c" +dependencies = [ + "chrono", + "chrono-tz", + "globwalk", + "humansize", + "lazy_static", + "percent-encoding", + "pest", + "pest_derive", + "rand 0.8.5", + "regex", + "serde", + "serde_json", + "slug", + "unic-segment", +] + [[package]] name = "termcolor" version = "1.3.0" @@ -4629,6 +5012,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "thread_local" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" +dependencies = [ + "cfg-if", + "once_cell", +] + [[package]] name = "tikv-jemalloc-ctl" version = "0.5.4" @@ -4975,6 +5368,12 @@ dependencies = [ "serde", ] +[[package]] +name = "ucd-trie" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" + [[package]] name = "uname" version = "0.1.1" @@ -4990,6 +5389,65 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + +[[package]] +name = "unic-char-property" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" +dependencies = [ + "unic-char-range", +] + +[[package]] +name = "unic-char-range" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" + +[[package]] +name = "unic-common" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" + +[[package]] +name = "unic-segment" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4ed5d26be57f84f176157270c112ef57b86debac9cd21daaabbe56db0f88f23" +dependencies = [ + "unic-ucd-segment", +] + +[[package]] +name = "unic-ucd-segment" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2079c122a62205b421f499da10f3ee0f7697f012f55b675e002483c73ea34700" +dependencies = [ + "unic-char-property", + "unic-char-range", + "unic-ucd-version", +] + +[[package]] +name = "unic-ucd-version" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" +dependencies = [ + "unic-common", +] + [[package]] name = "unicode-bidi" version = "0.3.13" @@ -5262,6 +5720,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows" version = "0.51.1" diff --git a/Cargo.toml b/Cargo.toml index a9117c3c8f..0f9989cf4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -90,6 +90,7 @@ members = [ "rpc", "util/light-client-protocol-server", "util/launcher", + "devtools/doc/rpc-gen", "ckb-bin" ] diff --git a/Makefile b/Makefile index 99a7652e82..873e19a250 100644 --- a/Makefile +++ b/Makefile @@ -102,15 +102,10 @@ doc-deps: ## Build the documentation for the local package and all dependencies. cargo doc --workspace .PHONY: gen-rpc-doc -gen-rpc-doc: ## Generate rpc documentation - rm -f ${CARGO_TARGET_DIR}/doc/ckb_rpc/module/trait.*.html - cargo doc --workspace - ln -nsf "${CARGO_TARGET_DIR}" "target" - if command -v python3 &> /dev/null; then \ - python3 ./devtools/doc/rpc.py > rpc/README.md; \ - else \ - python ./devtools/doc/rpc.py > rpc/README.md; \ - fi +gen-rpc-doc: submodule-init ## Generate rpc documentation + cd devtools/doc/rpc-gen && cargo build + ./target/debug/ckb-rpc-gen --json + ./target/debug/ckb-rpc-gen rpc/README.md .PHONY: gen-hashes gen-hashes: ## Generate docs/hashes.toml diff --git a/devtools/doc/rpc-gen/Cargo.toml b/devtools/doc/rpc-gen/Cargo.toml new file mode 100644 index 0000000000..d71f1ed21c --- /dev/null +++ b/devtools/doc/rpc-gen/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "ckb-rpc-gen" +version = "0.114.0-pre" +edition = "2021" +license = "MIT" +authors = ["Nervos Core Dev "] +description = "CKB RPC documentation generator" +homepage = "https://github.com/nervosnetwork/ckb" +repository = "https://github.com/nervosnetwork/ckb" + +[dependencies] +ckb-rpc ={ path = "../../../rpc", version = "= 0.114.0-pre" } +schemars = { version = "0.8.16", package = "ckb_schemars" } +serde_json = "~1.0" +tera = "1" diff --git a/devtools/doc/rpc-gen/src/gen.rs b/devtools/doc/rpc-gen/src/gen.rs new file mode 100644 index 0000000000..8358f43b75 --- /dev/null +++ b/devtools/doc/rpc-gen/src/gen.rs @@ -0,0 +1,452 @@ +extern crate tera; +use ckb_rpc::RPCError; +use schemars::schema_for; +use serde_json::{Map, Value}; +use std::{fs, vec}; +use tera::Tera; + +struct RpcModule { + pub title: String, + pub description: String, + pub methods: Vec, +} + +impl RpcModule { + pub fn gen_menu(&self, commit: &str) -> Value { + let capitlized = self.title.to_string(); + let mut method_names = self + .methods + .iter() + .map(|method| method["name"].as_str().unwrap().to_owned()) + .collect::>(); + if capitlized == "Subscription" { + method_names.push("subscribe".to_owned()); + method_names.push("unsubscribe".to_owned()); + } + + gen_value(&[ + ("title", capitlized.clone().into()), + ("name", self.title.to_lowercase().into()), + ("methods", method_names.into()), + ( + "link", + gen_module_openrpc_playground(&capitlized, commit).into(), + ), + ]) + } + + pub fn gen_module_content(&self, commit: &str) -> String { + if self.title == "Subscription" { + return gen_subscription_rpc_doc(); + } + let capitlized = self.title.to_string(); + let description = self.description.replace("##", "#####"); + + let methods = self + .methods + .iter() + .map(|method| { + // generate method signatures + let name = method["name"].as_str().unwrap(); + let params = method["params"].as_array().unwrap(); + let args = params + .iter() + .map(|arg| arg["name"].as_str().unwrap()) + .collect::>() + .join(", "); + let arg_lines = params + .iter() + .map(|arg| { + let ty = gen_type(&arg["schema"]); + format!(" * `{}`: {}", arg["name"].as_str().unwrap(), ty) + }) + .collect::>() + .join("\n"); + let ret_ty = if let Some(value) = method.get("result") { + format!("* result: {}", gen_type(&value["schema"])) + } else { + "".to_string() + }; + let signatures = format!("* `{}({})`\n{}\n{}", name, args, arg_lines, ret_ty); + let mut desc = method["description"] + .as_str() + .unwrap() + .replace("##", "######"); + desc = strip_prefix_space(&desc); + format!("#### Method `{}`\n{}\n\n{}\n", name, signatures, desc,) + }) + .collect::>(); + + render_tera( + include_str!("../templates/module.tera"), + &[ + ("name", capitlized.clone().into()), + ( + "link", + gen_module_openrpc_playground(&capitlized, commit).into(), + ), + ("desc", description.into()), + ("methods", methods.into()), + ], + ) + } +} + +pub(crate) struct RpcDocGenerator { + rpc_methods: Vec, + types: Vec<(String, Value)>, + file_path: String, + commit: String, +} + +impl RpcDocGenerator { + pub fn new(all_rpc: &Vec, readme_path: String, commit: String) -> Self { + let mut rpc_methods = vec![]; + let mut all_types: Vec<&Map> = vec![]; + for rpc in all_rpc { + if let serde_json::Value::Object(map) = rpc { + let title = capitlize( + map["info"]["title"] + .as_str() + .unwrap() + .trim_end_matches("_rpc"), + ); + let description = get_description(&map["info"]["description"]); + let methods = map["methods"].as_array().unwrap(); + let types = map["components"]["schemas"].as_object().unwrap(); + all_types.push(types); + rpc_methods.push(RpcModule { + title, + description, + methods: methods.to_owned(), + }); + } + } + + // sort rpc_methods accoring to title + rpc_methods.sort_by(|a, b| a.title.cmp(&b.title)); + + let mut types: Vec<(String, Value)> = vec![]; + for map in all_types.iter() { + for (name, ty) in map.iter() { + if !types.iter().any(|(n, _)| *n == *name) { + types.push((name.to_string(), ty.to_owned())); + } + } + } + types.sort_by(|(name1, _), (name2, _)| name1.cmp(name2)); + + Self { + rpc_methods, + types, + file_path: readme_path, + commit, + } + } + + pub fn gen_markdown(self) -> String { + let readme = fs::read_to_string(&self.file_path).unwrap_or("".to_string()); + let lines = readme.lines().collect::>(); + let summary: Value = lines + .iter() + .take_while(|l| !l.contains("**NOTE:** the content below is generated by gen_doc")) + .map(|l| l.to_string()) + .collect::>() + .join("\n") + .into(); + + // generate methods menu + let module_menus = self + .rpc_methods + .iter() + .map(|r| r.gen_menu(&self.commit)) + .collect::>(); + + let type_menus: Value = self + .types + .iter() + .map(|(name, _)| vec![capitlize(name).into(), name.to_lowercase().into()]) + .collect::>>() + .into(); + + // generate module methods content + let modules: Vec = self + .rpc_methods + .iter() + .map(|r| r.gen_module_content(&self.commit).into()) + .collect::>(); + + let types = self.gen_type_contents(); + render_tera( + include_str!("../templates/markdown.tera"), + &[ + ("summary", summary), + ("module_menus", module_menus.into()), + ("type_menus", type_menus), + ("modules", modules.into()), + ("types", types.into()), + ("errors", gen_errors_contents()), + ], + ) + } + + fn gen_type_contents(&self) -> Vec { + self.types + .iter() + .map(|(name, ty)| { + let desc = if let Some(desc) = ty.get("description") { + desc.as_str().unwrap().to_string() + } else if let Some(desc) = ty.get("format") { + format!("`{}` is `{}`", name, desc.as_str().unwrap()) + } else { + "".to_string() + }; + let desc = desc.replace("##", "######"); + // remove the inline code from comments + let desc = desc + .lines() + .filter(|l| !l.contains("serde_json::from_str") && !l.contains(".unwrap()")) + .collect::>() + .join("\n"); + + // replace only the first ``` with ```json + let desc = desc.replacen("```\n", "```json\n", 1); + let fields = gen_type_fields(ty); + gen_value(&[ + ("name", capitlize(name).into()), + ("desc", desc.into()), + ("fields", fields.into()), + ]) + }) + .collect::>() + } +} + +fn capitlize(s: &str) -> String { + if s.is_empty() { + return s.to_owned(); + } + s[0..1].to_uppercase().to_string() + &s[1..] +} + +fn strip_prefix_space(content: &str) -> String { + let minimal_strip_count = content + .lines() + .map(|l| { + if l.trim().is_empty() { + usize::MAX + } else { + l.chars().take_while(|c| c.is_whitespace()).count() + } + }) + .min() + .unwrap_or(0); + if minimal_strip_count > 0 { + content + .lines() + .map(|l| { + if l.len() > minimal_strip_count { + l[minimal_strip_count..].to_string() + } else { + "".to_string() + } + }) + .collect::>() + .join("\n") + } else { + content.to_string() + } +} + +fn get_description(value: &Value) -> String { + strip_prefix_space(value.as_str().unwrap()) +} + +fn gen_type_desc(desc: &str) -> String { + // split desc by "\n\n" and only keep the first line + // then add extra leading space for left lines + let split = desc.split("\n\n"); + let first = if let Some(line) = split.clone().next() { + line + } else { + desc + }; + let left = split.skip(1).collect::>().join("\n\n"); + // add extra leading space for left lines + let left = left + .lines() + .map(|l| { + let l = l.trim_start(); + let l = if l.starts_with('#') { + format!("**{}**", l.trim().trim_matches('#').trim()) + } else { + l.to_string() + }; + if l.is_empty() { + l + } else { + format!(" {}", l) + } + }) + .collect::>() + .join("\n"); + let desc = if left.is_empty() { + first.to_string() + } else { + format!("{}\n\n{}", first, left) + }; + format!(" - {}\n", desc) +} + +fn gen_type_fields(ty: &Value) -> String { + if let Some(fields) = ty.get("required") { + let res = fields + .as_array() + .unwrap() + .iter() + .map(|field| { + let field = field.as_str().unwrap(); + let field_desc = ty["properties"][field]["description"] + .as_str() + .map_or_else(|| "".to_string(), gen_type_desc); + let ty_ref = gen_type(&ty["properties"][field]); + format!("* `{}`: {}{}", field, ty_ref, field_desc) + }) + .collect::>() + .join("\n"); + let res = strip_prefix_space(&res); + format!("\n#### Fields:\n{}", res) + } else { + "".to_string() + } +} + +fn gen_type(ty: &Value) -> String { + match ty { + Value::Object(map) => { + if let Some(ty) = map.get("type") { + if ty.as_str() == Some("array") { + // if `maxItems` is not set, then it's a fixed length array + // means it's a tuple, will be handled by `Value::Array` case + if map.get("maxItems").is_none() { + format!("`Array<` {} `>`", gen_type(&map["items"])) + } else { + gen_type(&map["items"]) + } + } else if let Some(arr) = ty.as_array() { + let ty = arr + .iter() + .map(|t| format!("`{}`", gen_type(t))) + .collect::>() + .join(" `|` "); + ty.to_string() + } else { + format!("`{}`", ty.as_str().unwrap()) + } + } else if let Some(arr) = map.get("anyOf") { + arr.as_array() + .unwrap() + .iter() + .map(gen_type) + .collect::>() + .join(" `|` ") + } else { + let ty = map["$ref"].as_str().unwrap().split('/').last().unwrap(); + format!("[`{}`](#type-{})", ty, ty.to_lowercase()) + } + } + Value::Array(arr) => { + // the `tuple` case + let elems = arr.iter().map(gen_type).collect::>().join(" , "); + format!("({})", elems) + } + Value::Null => "".to_string(), + _ => ty.as_str().unwrap().to_string(), + } +} + +fn gen_errors_contents() -> Value { + let schema = schema_for!(RPCError); + let value = serde_json::to_value(schema).unwrap(); + let summary = get_description(&value["description"]); + let errors: Vec = value["oneOf"] + .as_array() + .unwrap() + .iter() + .map(|error| { + let desc = get_description(&error["description"]); + let enum_ty = error["enum"].as_array().unwrap()[0].as_str().unwrap(); + vec![enum_ty.to_string(), desc].into() + }) + .collect::>(); + gen_value(&[("summary", summary.into()), ("errors", errors.into())]) +} + +/// generate subscription module, which is handled specially here +/// since jsonrpc-utils ignore the `SubscriptionRpc` +fn gen_subscription_rpc_doc() -> String { + let pubsub_module_source = include_str!("../../../../rpc/src/module/subscription.rs"); + // read comments before `pub trait SubscriptionRpc` and treat it as module summary + let summary = pubsub_module_source + .lines() + .take_while(|l| !l.contains("pub trait SubscriptionRpc")) + .filter(|l| l.starts_with("///")) + .map(|l| { + l.trim_start() + .trim_start_matches("///") + .replacen(' ', "", 1) + }) + .collect::>() + .join("\n"); + let summary = strip_prefix_space(&summary); + + // read the continues comments between `S: Stream` and `fn subscribe` + let sub_desc = pubsub_module_source + .lines() + .skip_while(|l| !l.contains("S: Stream")) + .filter(|l| l.trim().starts_with("///")) + .map(|l| { + l.trim_start() + .trim_start_matches("///") + .replacen(' ', "", 1) + }) + .collect::>() + .join("\n"); + let sub_desc = strip_prefix_space(&sub_desc); + + format!("{}\n\n{}\n", summary, sub_desc) +} + +/// generate openrpc playground urls +fn gen_module_openrpc_playground(module: &str, commit: &str) -> String { + let title = format!("CKB-{}", capitlize(module)); + render_tera( + include_str!("../templates/link.tera"), + &[ + ("title", title.into()), + ("module", module.to_lowercase().into()), + ("commit", commit.into()), + ], + ) +} + +/// wrapper for render value +fn gen_value(pairs: &[(&str, Value)]) -> Value { + let mut res = Value::Object(Map::new()); + for (k, v) in pairs { + res.as_object_mut() + .unwrap() + .insert(k.to_string(), v.to_owned()); + } + res +} + +fn render_tera(template: &str, content: &[(&str, Value)]) -> String { + let mut context = tera::Context::new(); + for (k, v) in content { + context.insert(*k, v); + } + let mut tera = Tera::default(); + tera.add_raw_template("template", template).unwrap(); + tera.render("template", &context).unwrap() +} diff --git a/devtools/doc/rpc-gen/src/main.rs b/devtools/doc/rpc-gen/src/main.rs new file mode 100644 index 0000000000..3c5d543a77 --- /dev/null +++ b/devtools/doc/rpc-gen/src/main.rs @@ -0,0 +1,64 @@ +//! this is a tool to generate rpc doc +mod gen; +mod utils; +use crate::gen::RpcDocGenerator; +use crate::utils::*; +use serde_json::json; +use std::{fs, path::PathBuf}; + +fn dump_openrpc_json() -> Result<(), Box> { + let json_dir = PathBuf::from(OPENRPC_DIR).join("json"); + let version = get_version(); + checkout_tag_branch(&version); + fs::create_dir_all(&json_dir)?; + + for (name, mut doc) in all_rpc_docs() { + doc["info"]["version"] = serde_json::Value::String(version.clone()); + let obj = json!(doc); + let res = serde_json::to_string_pretty(&obj)?; + fs::write(json_dir.join(name), res)?; + } + eprintln!( + "finished dump openrpc json for version: {:?} at dir: {:?}", + version, json_dir + ); + + if is_git_repo_dirty() { + // run git commit all changes before generate rpc readme + eprintln!("commit OpenRPC changes to repo: {}", get_git_remote_url()); + run_command("git", &["add", "."], Some(OPENRPC_DIR)); + run_command( + "git", + &[ + "commit", + "-m", + &format!("update openrpc json for version: {:?}", version), + ], + Some(OPENRPC_DIR), + ); + run_command("git", &["push"], Some(OPENRPC_DIR)); + } + Ok(()) +} + +/// Generate rpc readme +fn gen_rpc_readme(readme_path: &str) -> Result<(), Box> { + let commit_sha = get_commit_sha(); + let rpc_docs = all_rpc_docs() + .iter() + .map(|(_, doc)| doc.clone()) + .collect::>(); + let generator = RpcDocGenerator::new(&rpc_docs, readme_path.to_owned(), commit_sha); + fs::write(readme_path, generator.gen_markdown())?; + + Ok(()) +} + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + match args.get(1).map(String::as_str) { + Some("--json") => dump_openrpc_json(), + Some(readme_path) => gen_rpc_readme(readme_path), + None => Ok(()), + } +} diff --git a/devtools/doc/rpc-gen/src/utils.rs b/devtools/doc/rpc-gen/src/utils.rs new file mode 100644 index 0000000000..7bc6b4f88c --- /dev/null +++ b/devtools/doc/rpc-gen/src/utils.rs @@ -0,0 +1,83 @@ +use ckb_rpc::module::*; +use serde_json::Value; + +pub const OPENRPC_DIR: &str = "./docs/ckb_rpc_openrpc/"; + +macro_rules! generate_docs { + ($($func:ident),* $(,)?) => { + [ + $( + (format!("{}.json", stringify!($func)), $func()), + )* + ] + }; +} + +pub(crate) fn all_rpc_docs() -> Vec<(String, Value)> { + generate_docs!( + alert_rpc_doc, + net_rpc_doc, + subscription_rpc_doc, + debug_rpc_doc, + chain_rpc_doc, + miner_rpc_doc, + pool_rpc_doc, + stats_rpc_doc, + integration_test_rpc_doc, + indexer_rpc_doc, + experiment_rpc_doc, + ) + .into() +} + +pub(crate) fn run_command(prog: &str, args: &[&str], dir: Option<&str>) -> Option { + std::process::Command::new(prog) + .args(args) + .current_dir(dir.unwrap_or(".")) + .output() + .ok() + .filter(|output| output.status.success()) + .and_then(|r| { + String::from_utf8(r.stdout) + .ok() + .map(|s| s.trim().to_string()) + }) +} + +pub(crate) fn get_version() -> String { + let version = run_command("cargo", &["pkgid"], None) + .unwrap() + .split('#') + .nth(1) + .unwrap_or("0.0.0") + .to_owned(); + version +} + +pub(crate) fn get_commit_sha() -> String { + let res = run_command("git", &["rev-parse", "HEAD"], Some(OPENRPC_DIR)).unwrap(); + eprintln!("commit sha: {:?}", res); + res +} + +pub(crate) fn checkout_tag_branch(version: &str) { + let dir = Some(OPENRPC_DIR); + let res = run_command("git", &["checkout", version], dir); + if res.is_none() { + run_command("git", &["checkout", "-b", version], dir); + } +} + +pub(crate) fn is_git_repo_dirty() -> bool { + let res = run_command("git", &["status", "--porcelain"], Some(OPENRPC_DIR)); + res.map(|s| !s.is_empty()).unwrap_or(false) +} + +pub(crate) fn get_git_remote_url() -> String { + run_command( + "git", + &["config", "--get", "remote.origin.url"], + Some(OPENRPC_DIR), + ) + .map_or("".to_string(), |s| s.trim().to_string()) +} diff --git a/devtools/doc/rpc-gen/templates/link.tera b/devtools/doc/rpc-gen/templates/link.tera new file mode 100644 index 0000000000..f5b780914e --- /dev/null +++ b/devtools/doc/rpc-gen/templates/link.tera @@ -0,0 +1 @@ +[👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]={{title}}&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/{{commit}}/json/{{module}}_rpc_doc.json) \ No newline at end of file diff --git a/devtools/doc/rpc-gen/templates/markdown.tera b/devtools/doc/rpc-gen/templates/markdown.tera new file mode 100644 index 0000000000..c93edab30d --- /dev/null +++ b/devtools/doc/rpc-gen/templates/markdown.tera @@ -0,0 +1,35 @@ +{{ summary }} + + +* [RPC Methods](#rpc-methods) +{% for menu in module_menus %} + {%- set methods = menu["methods"] %} + * [Module {{ menu["title"] }}](#module-{{ menu["name"] }}) {{ menu["link"] }} + {%- for method in methods %} + * [Method `{{method}}`](#method-{{method}}) + {%- endfor %} +{%- endfor %} +* [RPC Types](#rpc-types) +{% for menu in type_menus %} + * [Type `{{ menu.0 }}`](#type-{{ menu.1 }}) +{%- endfor %} +* [RPC Errors](#rpc-errors) + +## RPC Modules +{% for module in modules %} +{{module}} +{%- endfor %} + +## RPC Types +{% for ty in types %} +### Type `{{ ty["name"] }}` +{{ ty["desc"] }} +{{ ty["fields"] }} +{%- endfor %} + +## RPC Errors +{{errors["summary"]}} +{% for error in errors["errors"] %} +### ERROR `{{error.0}}` +{{error.1}} +{%- endfor %} \ No newline at end of file diff --git a/devtools/doc/rpc-gen/templates/module.tera b/devtools/doc/rpc-gen/templates/module.tera new file mode 100644 index 0000000000..e63fff0035 --- /dev/null +++ b/devtools/doc/rpc-gen/templates/module.tera @@ -0,0 +1,7 @@ +### Module `{{name}}` +- {{link}} + +{{desc}} +{% for method in methods %} +{{method}} +{%- endfor %} \ No newline at end of file diff --git a/devtools/doc/rpc.py b/devtools/doc/rpc.py deleted file mode 100755 index 122414267f..0000000000 --- a/devtools/doc/rpc.py +++ /dev/null @@ -1,841 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import print_function -import os -import io -import sys -import glob -import textwrap -import re -from html.parser import HTMLParser - -if sys.version_info < (3, 0, 0): - print("Requires python 3", file=sys.stderr) - sys.exit(127) - -PREAMBLE = """# CKB JSON-RPC Protocols - - - -The RPC interface shares the version of the node version, which is returned in `local_node_info`. The interface is fully compatible between patch versions, for example, a client for 0.25.0 should work with 0.25.x for any x. - -Allowing arbitrary machines to access the JSON-RPC port (using the `rpc.listen_address` configuration option) is **dangerous and strongly discouraged**. Please strictly limit the access to only trusted machines. - -CKB JSON-RPC only supports HTTP now. If you need SSL, please set up a proxy via Nginx or other HTTP servers. - -Subscriptions require a full duplex connection. CKB offers such connections in the form of TCP (enable with `rpc.tcp_listen_address` configuration option) and WebSockets (enable with `rpc.ws_listen_address`). - -## JSONRPC Deprecation Process - -A CKB RPC method is deprecated in three steps. - -First, the method is marked as deprecated in the CKB release notes and RPC document. However, the RPC method is still available. The RPC document will have the suggestion of alternative solutions. - -The CKB dev team will disable any deprecated RPC methods starting from the next minor version release. Users can enable the deprecated methods via the config file option rpc.enable_deprecated_rpc. - -Once a deprecated method is disabled, the CKB dev team will remove it in a future minor version release. - -For example, a method is marked as deprecated in 0.35.0, it can be disabled in 0.36.0 and removed in 0.37.0. The minor versions are released monthly, so there's at least a two-month buffer for a deprecated RPC method. - -## Minimum Supported Rust Version policy (MSRV) - -The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1. - -""" - -PENDING_TYPES = set() - -TYMETHOD_DOT = 'tymethod.' -HREF_PREFIX_RPCERROR = '../enum.RPCError.html#variant.' -RUST_DOC_PREFIX = 'https://doc.rust-lang.org/1.71.1' - -NAME_PREFIX_SELF = '(&self, ' -NAME_PREFIX_SELF_NL = '&self,' - -CAMEL_TO_SNAKE_PATTERN = re.compile(r'(? 1: - file.write('* `{}({})`\n'.format(method_name, - ', '.join(v.name for v in vars[:-1]))) - for var in vars[:-1]: - file.write(' * `{}`: {}\n'.format(var.name, var.ty)) - else: - file.write('* `{}()`\n'.format(method_name)) - if method_name == 'subscribe': - file.write('* result: `string`\n') - else: - file.write('* result: {}\n'.format(vars[-1].ty)) - - -class MarkdownParser(): - def __init__(self, title_level=0): - self.chunks = [] - self.title_level = title_level - self.nested_level = 0 - self.indent_level = 0 - self.is_first_paragraph = False - self.preserve_whitespaces = False - self.pending_href = None - self.table_cols = 0 - - def append(self, text): - self.chunks.append(text) - - def indent(self, text): - if self.indent_level > 0: - self.append(textwrap.indent(text, ' ' * self.indent_level)) - else: - self.append(text) - - def completed(self): - return self.nested_level < 0 - - def handle_startblock(self, tag): - if tag in ['p', 'li', 'pre', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'tr']: - self.append("\n") - if self.indent_level > 0: - self.append(' ' * self.indent_level) - - def handle_endblock(self, tag): - if tag in ['p', 'li', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'table']: - self.append("\n") - - def handle_starttag(self, tag, attrs): - if tag not in ['hr', 'br']: - self.nested_level += 1 - - self.handle_startblock(tag) - - if tag == 'li': - self.append('* ') - self.indent_level += 4 - elif tag == 'pre': - self.append("```\n") - self.preserve_whitespaces = True - elif tag in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']: - # The content here will be used in tag a to ignore the first anchor - self.append(((int(tag[1:]) + self.title_level - 1) * '#') + ' ') - elif tag in ['strong', 'b']: - self.append('**') - elif tag in ['em', 'i']: - self.append('*') - elif tag == 'code' and not self.preserve_whitespaces: - self.append('`') - elif tag == 'a': - # ignore the first anchor link in title - if not self.chunks[-1].startswith('#') or self.chunks[-1].strip().replace('#', '') != '': - self.pending_href = transform_href(dict(attrs)['href']) - self.append('[') - elif tag == 'thead': - self.table_cols = 0 - elif tag == 'tr': - self.append('| ') - elif tag == 'th' or tag == 'td': - self.append(' ') - - def handle_endtag(self, tag): - if tag not in ['hr', 'br']: - self.nested_level -= 1 - if self.completed(): - return - - self.handle_endblock(tag) - - if tag == 'li': - self.indent_level -= 4 - elif tag == 'pre': - if not self.chunks[-1].endswith('\n'): - self.indent('\n') - self.indent("```\n") - self.preserve_whitespaces = False - elif tag in ['strong', 'b']: - self.append('**') - elif tag in ['em', 'i']: - self.append('*') - elif tag == 'code' and not self.preserve_whitespaces: - self.append('`') - elif tag == 'a': - if self.pending_href is not None: - self.append('](') - self.append(self.pending_href) - self.append(')') - self.pending_href = None - elif tag == 'thead': - self.append("\n") - if self.indent_level > 0: - self.append(' ' * self.indent_level) - self.append('| ') - for i in range(self.table_cols): - self.append('--- |') - elif tag == 'th': - self.table_cols += 1 - self.append(' |') - elif tag == 'td': - self.append(' |') - - def handle_data(self, data): - if self.nested_level < 0: - return - - if not self.preserve_whitespaces: - if data != '\n': - self.append(' '.join(data.splitlines())) - if data.endswith('\n'): - self.append(' ') - else: - if self.chunks[-1] == '```\n' and data[0] == '\n': - data = data[1:] - self.indent(data) - - def write(self, file): - file.write('\n'.join(line.rstrip() - for line in ''.join(self.chunks).splitlines())) - - -class RPCVar(): - def __init__(self): - self.name = '' - self.ty = None - self.children = [] - self.completed_children = 0 - pass - - def require_children(self, n): - while len(self.children) < n: - self.children.append(RPCVar()) - - def handle_starttag(self, tag, attrs): - attrs_dict = dict(attrs) - - if tag != 'a' or ('title' in attrs_dict and attrs_dict['title'] == 'goto source code'): - return - # 1.61.0 new source link style - # 1.67.1 rightside - if tag == 'a' and (('class', 'srclink rightside') in attrs): - return - - - if self.ty is None: - self.ty = attrs_dict['href'] - if self.ty.startswith('#'): - self.ty = None - return - - if self.ty == RUST_DOC_PREFIX + '/std/primitive.unit.html' : - self.ty = '`null`' - if self.ty == RUST_DOC_PREFIX + '/std/primitive.bool.html': - self.ty = '`boolean`' - if self.ty == RUST_DOC_PREFIX + '/alloc/string/struct.String.html': - self.ty = '`string`' - elif self.ty == RUST_DOC_PREFIX + '/core/option/enum.Option.html': - self.require_children(1) - elif self.ty == RUST_DOC_PREFIX + '/alloc/vec/struct.Vec.html': - self.require_children(1) - elif self.ty == RUST_DOC_PREFIX + '/std/collections/hash/map/struct.HashMap.html': - self.require_children(2) - elif self.ty == RUST_DOC_PREFIX + '/alloc/collections/btree/map/struct.BTreeMap.html': - self.require_children(2) - elif self.ty == '../../ckb_jsonrpc_types/struct.ResponseFormat.html': - self.require_children(1) - elif self.ty == '../../ckb_jsonrpc_types/indexer/struct.IndexerPagination.html': - self.require_children(1) - elif self.ty.startswith('../'): - if '/struct.' in self.ty: - PENDING_TYPES.add(self.ty) - type_name = self.ty.split('/struct.')[1][:-5] - self.ty = '[`{}`](#type-{})'.format(type_name, - type_name.lower()) - elif '/type.' in self.ty: - PENDING_TYPES.add(self.ty) - type_name = self.ty.split('/type.')[1][:-5] - self.ty = '[`{}`](#type-{})'.format(type_name, - type_name.lower()) - elif '/enum.' in self.ty: - PENDING_TYPES.add(self.ty) - type_name = self.ty.split('/enum.')[1][:-5] - self.ty = '[`{}`](#type-{})'.format(type_name, - type_name.lower()) - - # after 1.56 rustdoc change relative link - # now relative link do not start with '../' - elif 'title' in attrs_dict and 'ckb_jsonrpc_types::' in attrs_dict['title']: - if ('class', 'struct') in attrs and attrs_dict['title'].startswith('struct') and self.ty.startswith('struct.'): - type_name = self.ty.split('struct.')[1][:-5] - PENDING_TYPES.add('ckb_jsonrpc_types/' + self.ty) - self.ty = '[`{}`](#type-{})'.format(type_name, - type_name.lower()) - elif ('class', 'type') in attrs and attrs_dict['title'].startswith('type') and self.ty.startswith('type.'): - type_name = self.ty.split('type.')[1][:-5] - PENDING_TYPES.add('ckb_jsonrpc_types/' + self.ty) - self.ty = '[`{}`](#type-{})'.format(type_name, - type_name.lower()) - elif ('class', 'enum') in attrs and attrs_dict['title'].startswith('enum') and self.ty.startswith('enum.'): - type_name = self.ty.split('enum.')[1][:-5] - PENDING_TYPES.add('ckb_jsonrpc_types/' + self.ty) - self.ty = '[`{}`](#type-{})'.format(type_name, - type_name.lower()) - - else: - if self.completed_children >= len(self.children): - print(">>> {} {}[{}] => {} {} {}".format( - self.name, self.ty, self.completed_children, self.completed(), tag, attrs)) - self.children[self.completed_children].handle_starttag(tag, attrs) - if self.children[self.completed_children].completed(): - if self.completed(): - if self.ty == RUST_DOC_PREFIX + '/core/option/enum.Option.html': - self.ty = '{} `|` `null`'.format(self.children[0].ty) - elif self.ty == RUST_DOC_PREFIX + '/alloc/vec/struct.Vec.html': - self.ty = '`Array<` {} `>`'.format(self.children[0].ty) - elif self.ty == RUST_DOC_PREFIX + '/std/collections/hash/map/struct.HashMap.html': - self.ty = '`{{ [ key:` {} `]: ` {} `}}`'.format( - self.children[0].ty, self.children[1].ty) - elif self.ty == RUST_DOC_PREFIX + '/alloc/collections/btree/map/struct.BTreeMap.html': - self.ty = '`{{ [ key:` {} `]: ` {} `}}`'.format( - self.children[0].ty, self.children[1].ty) - elif self.ty == '../../ckb_jsonrpc_types/struct.ResponseFormat.html': - molecule_name = self.children[0].ty.split('`]')[0][2:].replace('View', '') - self.ty = '{} `|` [`Serialized{}`](#type-serialized{})'.format( - self.children[0].ty, molecule_name, molecule_name.lower()) - elif self.ty == '../../ckb_jsonrpc_types/indexer/struct.IndexerPagination.html': - self.ty = '`IndexerPagination<` {} `>`'.format(self.children[0].ty) - else: - self.completed_children += 1 - - def handle_endtag(self, tag): - pass - - def handle_data(self, data): - if self.ty is None: - self.name = self.sanitize_name(data) - if self.name.endswith(': U256'): - parts = self.name.split(': ') - self.name = parts[0] - self.ty = '[`U256`](#type-u256)' - if self.name.endswith(': RationalU256'): - parts = self.name.split(': ') - self.name = parts[0] - self.ty = '[`RationalU256`](#type-rationalu256)' - - def completed(self): - return self.ty is not None and (len(self.children) == 0 or self.children[-1].completed()) - - def sanitize_name(self, name): - name = name.strip() - - if name.startswith(NAME_PREFIX_SELF): - name = name[len(NAME_PREFIX_SELF):] - if NAME_PREFIX_SELF_NL in name: - name = name.split(NAME_PREFIX_SELF_NL)[1].strip() - if name.endswith(':'): - name = name[:-1] - if name.startswith(', '): - name = name[2:] - if ',' in name: - name = name.split(',')[1].strip() - - return name - - -class RPCMethod(): - def __init__(self, name): - self.name = name - self.rpc_var_parser = RPCVar() - self.parsing_stability = False - self.doc_parser = None - self.params = [] - - def handle_starttag(self, tag, attrs): - if self.rpc_var_parser is not None: - if tag == 'div' and (attrs == [("class", "docblock")] or attrs == [("class", "stab deprecated")]): - self.rpc_var_parser = None - self.doc_parser = MarkdownParser(title_level=1) - if attrs == [("class", "stab deprecated")]: - self.doc_parser.append("\n") - self.parsing_stability = True - return - - self.rpc_var_parser.handle_starttag(tag, attrs) - elif not self.doc_parser.completed(): - self.doc_parser.handle_starttag(tag, attrs) - elif self.parsing_stability and tag == 'div' and attrs == [("class", "docblock")]: - self.parsing_stability = False - self.doc_parser.handle_starttag(tag, attrs) - - def handle_endtag(self, tag): - if self.rpc_var_parser is not None: - self.rpc_var_parser.handle_endtag(tag) - if self.rpc_var_parser.completed(): - if '->' not in self.rpc_var_parser.name or 'Result' in self.rpc_var_parser.name: - self.params.append(self.rpc_var_parser) - self.rpc_var_parser = RPCVar() - elif not self.doc_parser.completed(): - self.doc_parser.handle_endtag(tag) - - def handle_data(self, data): - if self.rpc_var_parser is not None: - self.rpc_var_parser.handle_data(data) - elif not self.doc_parser.completed(): - self.doc_parser.handle_data(data) - - def completed(self): - return self.doc_parser is not None and not self.parsing_stability and self.doc_parser.completed() - - def write(self, file): - file.write("\n#### Method `{}`\n".format(self.name)) - write_method_signature(file, self.name, self.params) - if self.doc_parser is not None: - self.doc_parser.write(file) - file.write("\n") - - -class RPCModule(HTMLParser): - def __init__(self, name): - super().__init__() - self.name = name - self.methods = [] - self.doc_parser = None - self.active_parser = None - - def handle_starttag(self, tag, attrs): - if self.active_parser is None: - if self.doc_parser is None and tag == 'div' and attrs == [("class", "docblock")]: - self.active_parser = self.doc_parser = MarkdownParser( - title_level=3) - elif tag == 'section' and ('class', 'method') in attrs: - id = dict(attrs)['id'] - if id.startswith(TYMETHOD_DOT): - self.active_parser = RPCMethod(id[len(TYMETHOD_DOT):]) - self.methods.append(self.active_parser) - else: - self.active_parser.handle_starttag(tag, attrs) - - def handle_endtag(self, tag): - if self.active_parser is not None: - self.active_parser.handle_endtag(tag) - if self.active_parser.completed(): - self.active_parser = None - - def handle_data(self, data): - if self.active_parser is not None: - self.active_parser.handle_data(data) - - def write(self, file): - file.write("### Module {}\n".format(self.name)) - self.doc_parser.write(file) - file.write("\n") - for m in self.methods: - m.write(file) - - -class RPCErrorParser(HTMLParser): - def __init__(self): - super().__init__() - self.variants = [] - - self.module_doc = None - self.next_variant = None - self.variant_parser = None - - def handle_starttag(self, tag, attrs): - if self.module_doc is None: - if tag == 'div' and attrs == [("class", "docblock")]: - self.module_doc = MarkdownParser(title_level=3) - elif not self.module_doc.completed(): - self.module_doc.handle_starttag(tag, attrs) - elif self.next_variant is None: - if tag == 'section': - attrs_dict = dict(attrs) - if 'id' in attrs_dict and attrs_dict['id'].startswith('variant.') and ('class', 'variant') in attrs: - self.next_variant = attrs_dict['id'].split('.')[1] - elif self.variant_parser is None: - if tag == 'div' and attrs == [("class", "docblock")]: - self.variant_parser = MarkdownParser(title_level=3) - else: - self.variant_parser.handle_starttag(tag, attrs) - - def handle_endtag(self, tag): - if self.module_doc is None: - return - elif not self.module_doc.completed(): - self.module_doc.handle_endtag(tag) - elif self.variant_parser is not None: - self.variant_parser.handle_endtag(tag) - if self.variant_parser.completed(): - self.variants.append((self.next_variant, self.variant_parser)) - self.next_variant = None - self.variant_parser = None - - def handle_data(self, data): - if self.module_doc is None: - return - elif not self.module_doc.completed(): - self.module_doc.handle_data(data) - elif self.variant_parser is not None: - self.variant_parser.handle_data(data) - - def write(self, file): - self.module_doc.write(file) - file.write('\n\n') - - for (name, variant) in self.variants: - file.write('### Error `{}`\n'.format(name)) - variant.write(file) - file.write('\n\n') - - -class EnumSchema(HTMLParser): - def __init__(self, name): - super().__init__() - self.name = name - self.variants = [] - self.next_variant = None - self.variant_parser = None - - def handle_starttag(self, tag, attrs): - if self.next_variant is None: - if tag == 'section': - attrs_dict = dict(attrs) - if 'id' in attrs_dict and attrs_dict['id'].startswith('variant.') and ('class', 'variant') in attrs: - self.next_variant = camel_to_snake(attrs_dict['id'].split('.')[1]) - elif self.variant_parser is None: - if tag == 'div' and attrs == [("class", "docblock")]: - self.variant_parser = MarkdownParser(title_level=3) - self.variant_parser.indent_level = 4 - else: - self.variant_parser.handle_starttag(tag, attrs) - - def handle_endtag(self, tag): - if self.next_variant is not None and self.variant_parser is not None: - self.variant_parser.handle_endtag(tag) - if self.variant_parser.completed(): - if self.next_variant not in [v[0] for v in self.variants]: - self.variants.append((self.next_variant, self.variant_parser)) - self.variant_parser = None - self.next_variant = None - - - def handle_data(self, data): - if self.variant_parser is not None: - self.variant_parser.handle_data(data) - - def write(self, file): - if self.name == 'PoolTransactionReject': - self.write_pool_transaction_reject(file) - return - - file.write('`{}` is equivalent to `"{}"`.\n\n'.format( - self.name, '" | "'.join(v[0] for v in self.variants))) - - for (name, v) in self.variants: - file.write('* ') - out = io.StringIO() - v.write(out) - variant_doc = out.getvalue().lstrip() - file.write(variant_doc) - file.write('\n') - if '\n' in variant_doc: - file.write('\n') - - # PoolTransactionReject - def write_pool_transaction_reject(self, file): - file.write( - '`{}` is a JSON object with following fields.\n\n'.format(self.name)) - - file.write('* `type`: `"{}"` - Reject type.\n'.format( - '" | "'.join(snake_to_camel(v[0]) for v in self.variants))) - file.write( - '* `description`: `string` - Detailed description about why the transaction is rejected.\n\n') - file.write('Different reject types:\n\n') - - for (name, v) in self.variants: - file.write('* `{}`: '.format(snake_to_camel(name))) - out = io.StringIO() - v.write(out) - file.write(out.getvalue().lstrip()) - file.write('\n') - - -class StructSchema(HTMLParser): - def __init__(self, name): - super().__init__() - self.name = name - self.fields = [] - self.next_field = None - self.type_parser = None - self.field_parser = None - - def handle_starttag(self, tag, attrs): - if self.next_field is None: - if tag == 'span': - attrs_dict = dict(attrs) - if 'id' in attrs_dict and attrs_dict['id'].startswith('structfield.'): - self.next_field = attrs_dict['id'].split('.')[1] - self.type_parser = RPCVar() - elif not self.type_parser.completed(): - self.type_parser.handle_starttag(tag, attrs) - elif self.field_parser is None: - if tag == 'div' and attrs == [("class", "docblock")]: - self.field_parser = MarkdownParser(title_level=3) - self.field_parser.indent_level = 4 - else: - self.field_parser.handle_starttag(tag, attrs) - - def handle_endtag(self, tag): - if self.type_parser is not None and not self.type_parser.completed(): - self.type_parser.handle_endtag(tag) - elif self.field_parser is not None: - self.field_parser.handle_endtag(tag) - if self.field_parser.completed(): - self.fields.append( - (self.next_field, self.type_parser, self.field_parser)) - self.next_field = None - self.type_parser = None - self.field_parser = None - - def handle_data(self, data): - if self.type_parser is not None and not self.type_parser.completed(): - self.type_parser.handle_data(data) - elif self.field_parser is not None: - self.field_parser.handle_data(data) - - def write(self, file): - if len(self.fields) == 0: - return - - file.write('#### Fields\n\n') - file.write( - '`{}` is a JSON object with the following fields.\n'.format(self.name)) - - for t in self.fields: - file.write('\n* `{}`: {} - '.format(t[0], t[1].ty)) - out = io.StringIO() - t[2].write(out) - file.write(out.getvalue().lstrip()) - file.write('\n') - - -class RPCType(HTMLParser): - def __init__(self, name, path): - super().__init__() - self.name = name - self.path = path - self.module_doc = None - - if '/enum.' in path and self.name != 'RawTxPool': - self.schema = EnumSchema(self.name) - elif '/struct.' in path and self.name != 'ProposalShortId': - self.schema = StructSchema(self.name) - else: - self.schema = None - - def handle_starttag(self, tag, attrs): - if self.module_doc is None: - if tag == 'div' and attrs == [("class", "docblock")]: - self.module_doc = MarkdownParser(title_level=3) - elif not self.module_doc.completed(): - self.module_doc.handle_starttag(tag, attrs) - elif self.schema is not None: - self.schema.handle_starttag(tag, attrs) - - def handle_endtag(self, tag): - if self.module_doc is None: - return - elif not self.module_doc.completed(): - self.module_doc.handle_endtag(tag) - elif self.schema is not None: - self.schema.handle_endtag(tag) - - def handle_data(self, data): - if self.module_doc is None: - return - elif not self.module_doc.completed(): - self.module_doc.handle_data(data) - elif self.schema is not None: - self.schema.handle_data(data) - - def write(self, file): - self.module_doc.write(file) - file.write('\n') - - if self.schema is not None: - file.write('\n') - self.schema.write(file) - file.write('\n') - - -class DummyRPCType(): - def __init__(self, name, module_doc): - super().__init__() - self.name = name - self.module_doc = module_doc - - def write(self, file): - file.write('\n') - file.write(self.module_doc) - file.write('\n') - - -class RPCDoc(object): - def __init__(self): - self.modules = [] - self.errors = RPCErrorParser() - self.parsed_types = set() - - self.types = [ - DummyRPCType( - "SerializedHeader", "This is a 0x-prefix hex string. It is the block header serialized by molecule using the schema `table Header`."), - DummyRPCType( - "SerializedBlock", "This is a 0x-prefix hex string. It is the block serialized by molecule using the schema `table Block`."), - DummyRPCType( - "U256", "The 256-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON."), - DummyRPCType( - "H256", "The 256-bit binary data encoded as a 0x-prefixed hex string in JSON."), - DummyRPCType( - "Byte32", "The fixed-length 32 bytes binary encoded as a 0x-prefixed hex string in JSON."), - DummyRPCType( - "RationalU256", """The ratio which numerator and denominator are both 256-bit unsigned integers. - -#### Example - -``` -{ - "denom": "0x28", - "numer": "0x1" -} -``` -""") - ] - - def collect(self): - for path in sorted(glob.glob("target/doc/ckb_rpc/module/trait.*Rpc.html")): - module_name = path.split('.')[1][:-3] - module = RPCModule(module_name) - self.modules.append(module) - with open(path) as file: - module.feed(file.read()) - - with open('target/doc/ckb_rpc/enum.RPCError.html') as file: - self.errors.feed(file.read()) - - global PENDING_TYPES - while len(PENDING_TYPES) > 0: - pending = PENDING_TYPES - PENDING_TYPES = set() - - for path in pending: - self.collect_type(path) - - # Referenced by subscription RPC. - self.collect_type('ckb_jsonrpc_types/struct.PoolTransactionEntry.html') - self.collect_type('ckb_jsonrpc_types/enum.PoolTransactionReject.html') - # Referenced by RawTxPool - self.collect_type('ckb_jsonrpc_types/struct.TxPoolIds.html') - self.collect_type('ckb_jsonrpc_types/struct.TxPoolEntries.html') - self.collect_type('ckb_jsonrpc_types/struct.TxPoolEntry.html') - self.types.sort(key=lambda t: t.name) - - def collect_type(self, path): - while path.startswith('../'): - path = path[3:] - path = 'target/doc/' + path - - if path in self.parsed_types: - return - self.parsed_types.add(path) - - if 'ckb_types/packed' in path: - return - if path.split('/')[-1] in ['type.Result.html', 'struct.Subscriber.html', 'enum.SubscriptionId.html', 'enum.Topic.html']: - return - - with open(path) as file: - content = file.read() - - if 'http-equiv="refresh"' in content: - path = content.split('0;URL=')[1].split('"')[0] - return self.collect_type(path) - - name = path.split('.')[1] - if name not in ['U256', 'RationalU256', 'H256', 'Byte32']: - parser = RPCType(name, path) - parser.feed(content) - - self.types.append(parser) - - def write(self, file): - file.write(PREAMBLE) - file.write("\n## Table of Contents\n\n") - - file.write("* [RPC Methods](#rpc-methods)\n") - for m in self.modules: - file.write( - " * [Module {}](#module-{})\n".format(m.name, m.name.lower())) - for f in m.methods: - file.write( - " * [Method `{}`](#method-{})\n".format(f.name, f.name.lower())) - file.write("* [RPC Errors](#rpc-errors)\n") - file.write("* [RPC Types](#rpc-types)\n") - for t in self.types: - file.write( - " * [Type `{}`](#type-{})\n".format(t.name, t.name.lower())) - - file.write("\n## RPC Methods\n\n") - - for m in self.modules: - m.write(file) - file.write("\n") - - file.write("\n## RPC Errors\n") - self.errors.write(file) - - file.write("\n## RPC Types\n") - for ty in self.types: - file.write("\n### Type `{}`\n".format(ty.name)) - ty.write(file) - - -def main(): - if not os.path.exists("target/doc/ckb_rpc/module/index.html"): - print("Please run cargo doc first:\n cargo doc --workspace", file=sys.stderr) - sys.exit(128) - - doc = RPCDoc() - doc.collect() - doc.write(sys.stdout) - - -if __name__ == '__main__': - main() diff --git a/devtools/windows/make.ps1 b/devtools/windows/make.ps1 index f5b764ed0c..3629e57b8b 100644 --- a/devtools/windows/make.ps1 +++ b/devtools/windows/make.ps1 @@ -142,9 +142,10 @@ function run-integration-directly { } function run-gen-rpc-doc { - rm -ErrorAction SilentlyContinue -Force target/doc/ckb_rpc/module/trait.*.html - cargo doc --workspace - python3 ./devtools/doc/rpc.py > rpc/README.md + pushd devtools/doc/rpc-gen/ + cargo build + popd + ./target/debug/rpc-gen rpc/README.md } try { diff --git a/docs/ckb_rpc_openrpc b/docs/ckb_rpc_openrpc new file mode 160000 index 0000000000..e7b5c1c42c --- /dev/null +++ b/docs/ckb_rpc_openrpc @@ -0,0 +1 @@ +Subproject commit e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index abc6743a4c..9493c673bb 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -48,6 +48,8 @@ futures-util = { version = "0.3.21" } tower-http = { version = "0.3.5", features = ["timeout", "cors"] } async-stream = "0.3.3" ckb-async-runtime = { path = "../util/runtime", version = "= 0.114.0-pre" } +# issue tracking: https://github.com/GREsau/schemars/pull/251 +schemars = { version = "0.8.16", package = "ckb_schemars" } [dev-dependencies] reqwest = { version = "=0.11.20", features = ["blocking", "json"] } diff --git a/rpc/README.md b/rpc/README.md index 315b5eeb40..543ac7b838 100644 --- a/rpc/README.md +++ b/rpc/README.md @@ -1,7 +1,5 @@ # CKB JSON-RPC Protocols - - The RPC interface shares the version of the node version, which is returned in `local_node_info`. The interface is fully compatible between patch versions, for example, a client for 0.25.0 should work with 0.25.x for any x. Allowing arbitrary machines to access the JSON-RPC port (using the `rpc.listen_address` configuration option) is **dangerous and strongly discouraged**. Please strictly limit the access to only trusted machines. @@ -29,10 +27,13 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1. ## Table of Contents + + * [RPC Methods](#rpc-methods) - * [Module Alert](#module-alert) + + * [Module Alert](#module-alert) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Alert&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/alert_rpc_doc.json) * [Method `send_alert`](#method-send_alert) - * [Module Chain](#module-chain) + * [Module Chain](#module-chain) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Chain&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/chain_rpc_doc.json) * [Method `get_block`](#method-get_block) * [Method `get_block_by_number`](#method-get_block_by_number) * [Method `get_header`](#method-get_header) @@ -56,15 +57,19 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1. * [Method `estimate_cycles`](#method-estimate_cycles) * [Method `get_fee_rate_statics`](#method-get_fee_rate_statics) * [Method `get_fee_rate_statistics`](#method-get_fee_rate_statistics) - * [Module Experiment](#module-experiment) + * [Module Debug](#module-debug) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Debug&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/debug_rpc_doc.json) + * [Method `jemalloc_profiling_dump`](#method-jemalloc_profiling_dump) + * [Method `update_main_logger`](#method-update_main_logger) + * [Method `set_extra_logger`](#method-set_extra_logger) + * [Module Experiment](#module-experiment) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Experiment&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/experiment_rpc_doc.json) * [Method `dry_run_transaction`](#method-dry_run_transaction) * [Method `calculate_dao_maximum_withdraw`](#method-calculate_dao_maximum_withdraw) - * [Module Indexer](#module-indexer) + * [Module Indexer](#module-indexer) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Indexer&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/indexer_rpc_doc.json) * [Method `get_indexer_tip`](#method-get_indexer_tip) * [Method `get_cells`](#method-get_cells) * [Method `get_transactions`](#method-get_transactions) * [Method `get_cells_capacity`](#method-get_cells_capacity) - * [Module IntegrationTest](#module-integrationtest) + * [Module Integration_test](#module-integration_test) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Integration_test&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/integration_test_rpc_doc.json) * [Method `process_block_without_verify`](#method-process_block_without_verify) * [Method `truncate`](#method-truncate) * [Method `generate_block`](#method-generate_block) @@ -72,10 +77,10 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1. * [Method `notify_transaction`](#method-notify_transaction) * [Method `generate_block_with_template`](#method-generate_block_with_template) * [Method `calculate_dao_field`](#method-calculate_dao_field) - * [Module Miner](#module-miner) + * [Module Miner](#module-miner) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Miner&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/miner_rpc_doc.json) * [Method `get_block_template`](#method-get_block_template) * [Method `submit_block`](#method-submit_block) - * [Module Net](#module-net) + * [Module Net](#module-net) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Net&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/net_rpc_doc.json) * [Method `local_node_info`](#method-local_node_info) * [Method `get_peers`](#method-get_peers) * [Method `get_banned_addresses`](#method-get_banned_addresses) @@ -86,7 +91,7 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1. * [Method `add_node`](#method-add_node) * [Method `remove_node`](#method-remove_node) * [Method `ping_peers`](#method-ping_peers) - * [Module Pool](#module-pool) + * [Module Pool](#module-pool) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Pool&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/pool_rpc_doc.json) * [Method `send_transaction`](#method-send_transaction) * [Method `remove_transaction`](#method-remove_transaction) * [Method `tx_pool_info`](#method-tx_pool_info) @@ -94,29 +99,29 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1. * [Method `get_raw_tx_pool`](#method-get_raw_tx_pool) * [Method `get_pool_tx_detail_info`](#method-get_pool_tx_detail_info) * [Method `tx_pool_ready`](#method-tx_pool_ready) - * [Module Stats](#module-stats) + * [Module Stats](#module-stats) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Stats&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/stats_rpc_doc.json) * [Method `get_blockchain_info`](#method-get_blockchain_info) * [Method `get_deployments_info`](#method-get_deployments_info) - * [Module Subscription](#module-subscription) + * [Module Subscription](#module-subscription) [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Subscription&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/subscription_rpc_doc.json) * [Method `subscribe`](#method-subscribe) -* [RPC Errors](#rpc-errors) + * [Method `unsubscribe`](#method-unsubscribe) * [RPC Types](#rpc-types) + * [Type `Alert`](#type-alert) * [Type `AlertId`](#type-alertid) * [Type `AlertMessage`](#type-alertmessage) - * [Type `AlertPriority`](#type-alertpriority) * [Type `AncestorsScoreSortKey`](#type-ancestorsscoresortkey) * [Type `BannedAddr`](#type-bannedaddr) * [Type `Block`](#type-block) * [Type `BlockEconomicState`](#type-blockeconomicstate) * [Type `BlockFilter`](#type-blockfilter) * [Type `BlockIssuance`](#type-blockissuance) - * [Type `BlockNumber`](#type-blocknumber) * [Type `BlockResponse`](#type-blockresponse) * [Type `BlockTemplate`](#type-blocktemplate) * [Type `BlockView`](#type-blockview) + * [Type `BlockWithCyclesResponse`](#type-blockwithcyclesresponse) + * [Type `Buried`](#type-buried) * [Type `Byte32`](#type-byte32) - * [Type `Capacity`](#type-capacity) * [Type `CellData`](#type-celldata) * [Type `CellDep`](#type-celldep) * [Type `CellInfo`](#type-cellinfo) @@ -126,61 +131,61 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1. * [Type `CellbaseTemplate`](#type-cellbasetemplate) * [Type `ChainInfo`](#type-chaininfo) * [Type `Consensus`](#type-consensus) - * [Type `Cycle`](#type-cycle) * [Type `DaoWithdrawingCalculationKind`](#type-daowithdrawingcalculationkind) * [Type `DepType`](#type-deptype) + * [Type `Deployment`](#type-deployment) * [Type `DeploymentInfo`](#type-deploymentinfo) - * [Type `DeploymentPos`](#type-deploymentpos) * [Type `DeploymentState`](#type-deploymentstate) * [Type `DeploymentsInfo`](#type-deploymentsinfo) - * [Type `Either`](#type-either) - * [Type `EpochNumber`](#type-epochnumber) - * [Type `EpochNumberWithFraction`](#type-epochnumberwithfraction) + * [Type `Either_for_BlockView_and_JsonBytes`](#type-either_for_blockview_and_jsonbytes) + * [Type `Either_for_HeaderView_and_JsonBytes`](#type-either_for_headerview_and_jsonbytes) + * [Type `Either_for_TransactionView_and_JsonBytes`](#type-either_for_transactionview_and_jsonbytes) * [Type `EpochView`](#type-epochview) * [Type `EstimateCycles`](#type-estimatecycles) + * [Type `ExtraLoggerConfig`](#type-extraloggerconfig) * [Type `FeeRateStatistics`](#type-feeratestatistics) * [Type `H256`](#type-h256) - * [Type `HardForks`](#type-hardforks) + * [Type `HardForkFeature`](#type-hardforkfeature) * [Type `Header`](#type-header) * [Type `HeaderView`](#type-headerview) * [Type `IndexerCell`](#type-indexercell) + * [Type `IndexerCellType`](#type-indexercelltype) * [Type `IndexerCellsCapacity`](#type-indexercellscapacity) * [Type `IndexerOrder`](#type-indexerorder) - * [Type `IndexerRange`](#type-indexerrange) + * [Type `IndexerPagination_for_IndexerCell`](#type-indexerpagination_for_indexercell) + * [Type `IndexerPagination_for_IndexerTx`](#type-indexerpagination_for_indexertx) * [Type `IndexerScriptType`](#type-indexerscripttype) * [Type `IndexerSearchKey`](#type-indexersearchkey) * [Type `IndexerSearchKeyFilter`](#type-indexersearchkeyfilter) * [Type `IndexerSearchMode`](#type-indexersearchmode) * [Type `IndexerTip`](#type-indexertip) * [Type `IndexerTx`](#type-indexertx) + * [Type `IndexerTxWithCell`](#type-indexertxwithcell) + * [Type `IndexerTxWithCells`](#type-indexertxwithcells) * [Type `JsonBytes`](#type-jsonbytes) * [Type `LocalNode`](#type-localnode) * [Type `LocalNodeProtocol`](#type-localnodeprotocol) + * [Type `MainLoggerConfig`](#type-mainloggerconfig) * [Type `MerkleProof`](#type-merkleproof) * [Type `MinerReward`](#type-minerreward) * [Type `NodeAddress`](#type-nodeaddress) * [Type `OutPoint`](#type-outpoint) * [Type `OutputsValidator`](#type-outputsvalidator) * [Type `PeerSyncState`](#type-peersyncstate) - * [Type `PoolTransactionEntry`](#type-pooltransactionentry) - * [Type `PoolTransactionReject`](#type-pooltransactionreject) * [Type `PoolTxDetailInfo`](#type-pooltxdetailinfo) * [Type `ProposalShortId`](#type-proposalshortid) * [Type `ProposalWindow`](#type-proposalwindow) * [Type `Ratio`](#type-ratio) - * [Type `RationalU256`](#type-rationalu256) * [Type `RawTxPool`](#type-rawtxpool) * [Type `RemoteNode`](#type-remotenode) * [Type `RemoteNodeProtocol`](#type-remotenodeprotocol) - * [Type `ResponseFormat`](#type-responseformat) + * [Type `Rfc0043`](#type-rfc0043) * [Type `Script`](#type-script) * [Type `ScriptHashType`](#type-scripthashtype) - * [Type `SerializedBlock`](#type-serializedblock) - * [Type `SerializedHeader`](#type-serializedheader) * [Type `SoftFork`](#type-softfork) + * [Type `SoftForkStatus`](#type-softforkstatus) * [Type `Status`](#type-status) * [Type `SyncState`](#type-syncstate) - * [Type `Timestamp`](#type-timestamp) * [Type `Transaction`](#type-transaction) * [Type `TransactionAndWitnessProof`](#type-transactionandwitnessproof) * [Type `TransactionProof`](#type-transactionproof) @@ -192,24 +197,24 @@ The crate `ckb-rpc`'s minimum supported rustc version is 1.71.1. * [Type `TxPoolIds`](#type-txpoolids) * [Type `TxPoolInfo`](#type-txpoolinfo) * [Type `TxStatus`](#type-txstatus) - * [Type `U256`](#type-u256) * [Type `Uint128`](#type-uint128) - * [Type `Uint32`](#type-uint32) * [Type `Uint64`](#type-uint64) * [Type `UncleBlock`](#type-uncleblock) * [Type `UncleBlockView`](#type-uncleblockview) * [Type `UncleTemplate`](#type-uncletemplate) - * [Type `Version`](#type-version) +* [RPC Errors](#rpc-errors) -## RPC Methods +## RPC Modules -### Module Alert +### Module `Alert` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Alert&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/alert_rpc_doc.json) RPC Module Alert for network alerts. An alert is a message about critical problems to be broadcast to all nodes via the p2p network. -The alerts must be signed by 2-of-4 signatures, where the public keys are hard-coded in the source code and belong to early CKB developers. +The alerts must be signed by 2-of-4 signatures, where the public keys are hard-coded in the source code +and belong to early CKB developers. #### Method `send_alert` * `send_alert(alert)` @@ -222,18 +227,15 @@ This RPC returns `null` on success. ###### Errors -* [`AlertFailedToVerifySignatures (-1000)`](#error-alertfailedtoverifysignatures) - Some signatures in the request are invalid. - -* [`P2PFailedToBroadcast (-101)`](#error-p2pfailedtobroadcast) - Alert is saved locally but has failed to broadcast to the P2P network. - -* `InvalidParams (-32602)` - The time specified in `alert.notice_until` must be in the future. +* [`AlertFailedToVerifySignatures (-1000)`](../enum.RPCError.html#variant.AlertFailedToVerifySignatures) - Some signatures in the request are invalid. +* [`P2PFailedToBroadcast (-101)`](../enum.RPCError.html#variant.P2PFailedToBroadcast) - Alert is saved locally but has failed to broadcast to the P2P network. +* `InvalidParams (-32602)` - The time specified in `alert.notice_until` must be in the future. ###### Examples Request - -``` +```json { "jsonrpc": "2.0", "method": "send_alert", @@ -254,11 +256,9 @@ Request } ``` - Response - -``` +```json { "error": { "code": -1000, @@ -271,8 +271,8 @@ Response } ``` - -### Module Chain +### Module `Chain` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Chain&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/chain_rpc_doc.json) RPC Module Chain for methods related to the canonical chain. @@ -280,24 +280,27 @@ This module queries information about the canonical chain. ##### Canonical Chain -A canonical chain is the one with the most accumulated work. The accumulated work is the sum of difficulties of all the blocks in the chain. +A canonical chain is the one with the most accumulated work. The accumulated work is +the sum of difficulties of all the blocks in the chain. ##### Chain Reorganization -Chain Reorganization happens when CKB found a chain that has accumulated more work than the canonical chain. The reorganization reverts the blocks in the current canonical chain if needed, and switch the canonical chain to that better chain. +Chain Reorganization happens when CKB found a chain that has accumulated more work than the +canonical chain. The reorganization revert the blocks in the current canonical chain if needed, +and switch the canonical chain to that better chain. ##### Live Cell A cell is live if -* it is found as an output in any transaction in the [canonical chain](#canonical-chain), and - -* it is not found as an input in any transaction in the canonical chain. +* it is found as an output in any transaction in the [canonical chain](#canonical-chain), +and +* it is not found as an input in any transaction in the canonical chain. #### Method `get_block` * `get_block(block_hash, verbosity, with_cycles)` * `block_hash`: [`H256`](#type-h256) - * `verbosity`: [`Uint32`](#type-uint32) `|` `null` + * `verbosity`: [`AlertId`](#type-alertid) `|` `null` * `with_cycles`: `boolean` `|` `null` * result: [`BlockResponse`](#type-blockresponse) `|` `null` @@ -305,28 +308,32 @@ Returns the information about a block by hash. ###### Params -* `block_hash` - the block hash. - -* `verbosity` - result format which allows 0 and 2. (**Optional**, the default is 2.) - -* `with_cycles` - whether the return cycles of block transactions. (**Optional**, default false.) +* `block_hash` - the block hash. +* `verbosity` - result format which allows 0 and 2. (**Optional**, the default is 2.) +* `with_cycles` - whether the return cycles of block transactions. (**Optional**, default false.) ###### Returns -The RPC returns a block or null. When the RPC returns a block, the block hash must equal to the parameter `block_hash`. +The RPC returns a block or null. When the RPC returns a block, the block hash must equal to +the parameter `block_hash`. -If the block is in the [canonical chain](#canonical-chain), the RPC must return the block information. Otherwise, the behavior is undefined. The RPC may return blocks found in local storage or simply returns null for all blocks that are not in the canonical chain. And because of [chain reorganization](#chain-reorganization), for the same `block_hash`, the RPC may sometimes return null and sometimes return the block. +If the block is in the [canonical chain](#canonical-chain), the RPC must return the block +information. Otherwise, the behavior is undefined. The RPC may return blocks found in local +storage or simply returns null for all blocks that are not in the canonical chain. And +because of [chain reorganization](#chain-reorganization), for the same `block_hash`, the +RPC may sometimes return null and sometimes return the block. -When `verbosity` is 2, it returns a JSON object as the `result`. See `BlockView` for the schema. +When `verbosity` is 2, it returns a JSON object as the `result`. See `BlockView` for the +schema. -When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string encodes the block serialized by molecule using schema `table Block`. +When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string +encodes the block serialized by molecule using schema `table Block`. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -337,11 +344,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -400,11 +405,9 @@ Response } ``` - The response looks like below when `verbosity` is 0. - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -412,11 +415,9 @@ The response looks like below when `verbosity` is 0. } ``` - When specifying with_cycles, the response object will be different like below: - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -427,11 +428,10 @@ When specifying with_cycles, the response object will be different like below: } ``` - #### Method `get_block_by_number` * `get_block_by_number(block_number, verbosity, with_cycles)` - * `block_number`: [`BlockNumber`](#type-blocknumber) - * `verbosity`: [`Uint32`](#type-uint32) `|` `null` + * `block_number`: [`Uint64`](#type-uint64) + * `verbosity`: [`AlertId`](#type-alertid) `|` `null` * `with_cycles`: `boolean` `|` `null` * result: [`BlockResponse`](#type-blockresponse) `|` `null` @@ -439,34 +439,35 @@ Returns the block in the [canonical chain](#canonical-chain) with the specific b ###### Params -* `block_number` - the block number. - -* `verbosity` - result format which allows 0 and 2. (**Optional**, the default is 2.) - -* `with_cycles` - whether the return cycles of block transactions. (**Optional**, default false.) +* `block_number` - the block number. +* `verbosity` - result format which allows 0 and 2. (**Optional**, the default is 2.) +* `with_cycles` - whether the return cycles of block transactions. (**Optional**, default false.) ###### Returns -The RPC returns the block when `block_number` is less than or equal to the tip block number returned by [`get_tip_block_number`](#method-get_tip_block_number) and returns null otherwise. +The RPC returns the block when `block_number` is less than or equal to the tip block +number returned by [`get_tip_block_number`](#tymethod.get_tip_block_number) and returns +null otherwise. -Because of [chain reorganization](#chain-reorganization), the PRC may return null or even different blocks in different invocations with the same `block_number`. +Because of [chain reorganization](#chain-reorganization), the PRC may return null or even +different blocks in different invocations with the same `block_number`. -When `verbosity` is 2, it returns a JSON object as the `result`. See `BlockView` for the schema. +When `verbosity` is 2, it returns a JSON object as the `result`. See `BlockView` for the +schema. -When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string encodes the block serialized by molecule using schema `table Block`. +When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string +encodes the block serialized by molecule using schema `table Block`. ###### Errors -* [`ChainIndexIsInconsistent (-201)`](#error-chainindexisinconsistent) - The index is inconsistent. It says a block hash is in the main chain, but cannot read it from the database. - -* [`DatabaseIsCorrupt (-202)`](#error-databaseiscorrupt) - The data read from database is dirty. Please report it as a bug. +* [`ChainIndexIsInconsistent (-201)`](../enum.RPCError.html#variant.ChainIndexIsInconsistent) - The index is inconsistent. It says a block hash is in the main chain, but cannot read it from the database. +* [`DatabaseIsCorrupt (-202)`](../enum.RPCError.html#variant.DatabaseIsCorrupt) - The data read from database is dirty. Please report it as a bug. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -477,11 +478,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -540,11 +539,9 @@ Response } ``` - The response looks like below when `verbosity` is 0. - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -552,11 +549,9 @@ The response looks like below when `verbosity` is 0. } ``` - When specifying with_cycles, the response object will be different like below: - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -567,37 +562,41 @@ When specifying with_cycles, the response object will be different like below: } ``` - #### Method `get_header` * `get_header(block_hash, verbosity)` * `block_hash`: [`H256`](#type-h256) - * `verbosity`: [`Uint32`](#type-uint32) `|` `null` -* result: [`HeaderView`](#type-headerview) `|` [`SerializedHeader`](#type-serializedheader) `|` `null` + * `verbosity`: [`AlertId`](#type-alertid) `|` `null` +* result: [`Either_for_HeaderView_and_JsonBytes`](#type-either_for_headerview_and_jsonbytes) `|` `null` Returns the information about a block header by hash. ###### Params -* `block_hash` - the block hash. - -* `verbosity` - result format which allows 0 and 1. (**Optional**, the default is 1.) +* `block_hash` - the block hash. +* `verbosity` - result format which allows 0 and 1. (**Optional**, the default is 1.) ###### Returns -The RPC returns a header or null. When the RPC returns a header, the block hash must equal to the parameter `block_hash`. +The RPC returns a header or null. When the RPC returns a header, the block hash must equal to +the parameter `block_hash`. -If the block is in the [canonical chain](#canonical-chain), the RPC must return the header information. Otherwise, the behavior is undefined. The RPC may return blocks found in local storage or simply returns null for all blocks that are not in the canonical chain. And because of [chain reorganization](#chain-reorganization), for the same `block_hash`, the RPC may sometimes return null and sometimes return the block header. +If the block is in the [canonical chain](#canonical-chain), the RPC must return the header +information. Otherwise, the behavior is undefined. The RPC may return blocks found in local +storage or simply returns null for all blocks that are not in the canonical chain. And +because of [chain reorganization](#chain-reorganization), for the same `block_hash`, the +RPC may sometimes return null and sometimes return the block header. -When `verbosity` is 1, it returns a JSON object as the `result`. See `HeaderView` for the schema. +When `verbosity` is 1, it returns a JSON object as the `result`. See `HeaderView` for the +schema. -When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string encodes the block header serialized by molecule using schema `table Header`. +When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string +encodes the block header serialized by molecule using schema `table Header`. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -608,11 +607,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -633,11 +630,9 @@ Response } ``` - The response looks like below when `verbosity` is 0. - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -645,41 +640,44 @@ The response looks like below when `verbosity` is 0. } ``` - #### Method `get_header_by_number` * `get_header_by_number(block_number, verbosity)` - * `block_number`: [`BlockNumber`](#type-blocknumber) - * `verbosity`: [`Uint32`](#type-uint32) `|` `null` -* result: [`HeaderView`](#type-headerview) `|` [`SerializedHeader`](#type-serializedheader) `|` `null` + * `block_number`: [`Uint64`](#type-uint64) + * `verbosity`: [`AlertId`](#type-alertid) `|` `null` +* result: [`Either_for_HeaderView_and_JsonBytes`](#type-either_for_headerview_and_jsonbytes) `|` `null` -Returns the block header in the [canonical chain](#canonical-chain) with the specific block number. +Returns the block header in the [canonical chain](#canonical-chain) with the specific block +number. ###### Params -* `block_number` - Number of a block - -* `verbosity` - result format which allows 0 and 1. (**Optional**, the default is 1.) +* `block_number` - Number of a block +* `verbosity` - result format which allows 0 and 1. (**Optional**, the default is 1.) ###### Returns -The RPC returns the block header when `block_number` is less than or equal to the tip block number returned by [`get_tip_block_number`](#method-get_tip_block_number) and returns null otherwise. +The RPC returns the block header when `block_number` is less than or equal to the tip block +number returned by [`get_tip_block_number`](#tymethod.get_tip_block_number) and returns +null otherwise. -Because of [chain reorganization](#chain-reorganization), the PRC may return null or even different block headers in different invocations with the same `block_number`. +Because of [chain reorganization](#chain-reorganization), the PRC may return null or even +different block headers in different invocations with the same `block_number`. -When `verbosity` is 1, it returns a JSON object as the `result`. See `HeaderView` for the schema. +When `verbosity` is 1, it returns a JSON object as the `result`. See `HeaderView` for the +schema. -When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string encodes the block header serialized by molecule using schema `table Header`. +When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string +encodes the block header serialized by molecule using schema `table Header`. ###### Errors -* [`ChainIndexIsInconsistent (-201)`](#error-chainindexisinconsistent) - The index is inconsistent. It says a block hash is in the main chain, but cannot read it from the database. +* [`ChainIndexIsInconsistent (-201)`](../enum.RPCError.html#variant.ChainIndexIsInconsistent) - The index is inconsistent. It says a block hash is in the main chain, but cannot read it from the database. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -690,11 +688,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -715,11 +711,9 @@ Response } ``` - The response looks like below when `verbosity` is 0. - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -727,7 +721,6 @@ The response looks like below when `verbosity` is 0. } ``` - #### Method `get_block_filter` * `get_block_filter(block_hash)` * `block_hash`: [`H256`](#type-h256) @@ -737,7 +730,7 @@ Returns the block filter by block hash. ###### Params -* `block_hash` - the block hash. +* `block_hash` - the block hash. ###### Returns @@ -747,8 +740,7 @@ The block filter data Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -759,11 +751,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -771,11 +761,9 @@ Response } ``` - The response looks like below when the block have block filter. - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -786,11 +774,10 @@ The response looks like below when the block have block filter. } ``` - #### Method `get_transaction` * `get_transaction(tx_hash, verbosity, only_committed)` * `tx_hash`: [`H256`](#type-h256) - * `verbosity`: [`Uint32`](#type-uint32) `|` `null` + * `verbosity`: [`AlertId`](#type-alertid) `|` `null` * `only_committed`: `boolean` `|` `null` * result: [`TransactionWithStatusResponse`](#type-transactionwithstatusresponse) @@ -798,32 +785,32 @@ Returns the information about a transaction requested by transaction hash. ###### Returns -This RPC returns `null` if the transaction is not committed in the [canonical chain](#canonical-chain) nor the transaction memory pool. +This RPC returns `null` if the transaction is not committed in the +[canonical chain](#canonical-chain) nor the transaction memory pool. If the transaction is in the chain, the block hash is also returned. ###### Params -* `tx_hash` - Hash of a transaction - -* `verbosity` - result format which allows 0, 1 and 2. (**Optional**, the defaults to 2.) - -* `only_committed` - whether to query committed transaction only. (**Optional**, if not set, it will query all status of transactions.) +* `tx_hash` - Hash of a transaction +* `verbosity` - result format which allows 0, 1 and 2. (**Optional**, the defaults to 2.) +* `only_committed` - whether to query committed transaction only. (**Optional**, if not set, it will query all status of transactions.) ###### Returns -When verbosity=0, it’s response value is as same as verbosity=2, but it return a 0x-prefixed hex encoded molecule packed::Transaction on `transaction` field +When verbosity=0, it's response value is as same as verbosity=2, but it +return a 0x-prefixed hex encoded molecule packed::Transaction on `transaction` field When verbosity is 1: The RPC does not return the transaction content and the field transaction must be null. -When verbosity is 2: if tx_status.status is pending, proposed, or committed, the RPC returns the transaction content as field transaction, otherwise the field is null. +When verbosity is 2: if tx_status.status is pending, proposed, or committed, +the RPC returns the transaction content as field transaction, otherwise the field is null. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -834,11 +821,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -900,8 +885,7 @@ Response The response looks like below when `verbosity` is 0. - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -918,30 +902,32 @@ The response looks like below when `verbosity` is 0. } ``` - #### Method `get_block_hash` * `get_block_hash(block_number)` - * `block_number`: [`BlockNumber`](#type-blocknumber) + * `block_number`: [`Uint64`](#type-uint64) * result: [`H256`](#type-h256) `|` `null` -Returns the hash of a block in the [canonical chain](#canonical-chain) with the specified `block_number`. +Returns the hash of a block in the [canonical chain](#canonical-chain) with the specified +`block_number`. ###### Params -* `block_number` - Block number +* `block_number` - Block number ###### Returns -The RPC returns the block hash when `block_number` is less than or equal to the tip block number returned by [`get_tip_block_number`](#method-get_tip_block_number) and returns null otherwise. +The RPC returns the block hash when `block_number` is less than or equal to the tip block +number returned by [`get_tip_block_number`](#tymethod.get_tip_block_number) and returns +null otherwise. -Because of [chain reorganization](#chain-reorganization), the PRC may return null or even different block hashes in different invocations with the same `block_number`. +Because of [chain reorganization](#chain-reorganization), the PRC may return null or even +different block hashes in different invocations with the same `block_number`. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -952,11 +938,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -964,32 +948,34 @@ Response } ``` - #### Method `get_tip_header` * `get_tip_header(verbosity)` - * `verbosity`: [`Uint32`](#type-uint32) `|` `null` -* result: [`HeaderView`](#type-headerview) `|` [`SerializedHeader`](#type-serializedheader) + * `verbosity`: [`AlertId`](#type-alertid) `|` `null` +* result: [`Either_for_HeaderView_and_JsonBytes`](#type-either_for_headerview_and_jsonbytes) Returns the header with the highest block number in the [canonical chain](#canonical-chain). -Because of [chain reorganization](#chain-reorganization), the block number returned can be less than previous invocations and different invocations may return different block headers with the same block number. +Because of [chain reorganization](#chain-reorganization), the block number returned can be +less than previous invocations and different invocations may return different block headers +with the same block number. ###### Params -* `verbosity` - result format which allows 0 and 1. (**Optional**, the default is 1.) +* `verbosity` - result format which allows 0 and 1. (**Optional**, the default is 1.) ###### Returns -When `verbosity` is 1, the RPC returns a JSON object as the `result`. See HeaderView for the schema. +When `verbosity` is 1, the RPC returns a JSON object as the `result`. See HeaderView for the +schema. -When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string encodes the header serialized by molecule using schema `table Header`. +When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string +encodes the header serialized by molecule using schema `table Header`. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -998,11 +984,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -1023,11 +1007,9 @@ Response } ``` - The response looks like below when `verbosity` is 0. - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -1035,7 +1017,6 @@ The response looks like below when `verbosity` is 0. } ``` - #### Method `get_live_cell` * `get_live_cell(out_point, with_data)` * `out_point`: [`OutPoint`](#type-outpoint) @@ -1048,22 +1029,23 @@ Returns the status of a cell. The RPC returns extra information if it is a [live This RPC tells whether a cell is live or not. -If the cell is live, the RPC will return details about the cell. Otherwise, the field `cell` is null in the result. +If the cell is live, the RPC will return details about the cell. Otherwise, the field `cell` is +null in the result. -If the cell is live and `with_data` is set to `false`, the field `cell.data` is null in the result. +If the cell is live and `with_data` is set to `false`, the field `cell.data` is null in the +result. ###### Params -* `out_point` - Reference to the cell by transaction hash and output index. - -* `with_data` - Whether the RPC should return cell data. Cell data can be huge, if the client does not need the data, it should set this to `false` to save bandwidth. +* `out_point` - Reference to the cell by transaction hash and output index. +* `with_data` - Whether the RPC should return cell data. Cell data can be huge, if the client +does not need the data, it should set this to `false` to save bandwidth. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1078,11 +1060,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1107,21 +1087,21 @@ Response } ``` - #### Method `get_tip_block_number` * `get_tip_block_number()` -* result: [`BlockNumber`](#type-blocknumber) + +* result: [`Uint64`](#type-uint64) Returns the highest block number in the [canonical chain](#canonical-chain). -Because of [chain reorganization](#chain-reorganization), the returned block number may be less than a value returned in the previous invocation. +Because of [chain reorganization](#chain-reorganization), the returned block number may be +less than a value returned in the previous invocation. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1130,11 +1110,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1142,21 +1120,22 @@ Response } ``` - #### Method `get_current_epoch` * `get_current_epoch()` + * result: [`EpochView`](#type-epochview) Returns the epoch with the highest number in the [canonical chain](#canonical-chain). -Pay attention that like blocks with the specific block number may change because of [chain reorganization](#chain-reorganization), This RPC may return different epochs which have the same epoch number. +Pay attention that like blocks with the specific block number may change because of [chain +reorganization](#chain-reorganization), This RPC may return different epochs which have +the same epoch number. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1165,11 +1144,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1182,30 +1159,30 @@ Response } ``` - #### Method `get_epoch_by_number` * `get_epoch_by_number(epoch_number)` - * `epoch_number`: [`EpochNumber`](#type-epochnumber) + * `epoch_number`: [`Uint64`](#type-uint64) * result: [`EpochView`](#type-epochview) `|` `null` Returns the epoch in the [canonical chain](#canonical-chain) with the specific epoch number. ###### Params -* `epoch_number` - Epoch number +* `epoch_number` - Epoch number ###### Returns -The RPC returns the epoch when `epoch_number` is less than or equal to the current epoch number returned by [`get_current_epoch`](#method-get_current_epoch) and returns null otherwise. +The RPC returns the epoch when `epoch_number` is less than or equal to the current epoch number +returned by [`get_current_epoch`](#tymethod.get_current_epoch) and returns null otherwise. -Because of [chain reorganization](#chain-reorganization), for the same `epoch_number`, this RPC may return null or different epochs in different invocations. +Because of [chain reorganization](#chain-reorganization), for the same `epoch_number`, this +RPC may return null or different epochs in different invocations. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1216,11 +1193,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1233,7 +1208,6 @@ Response } ``` - #### Method `get_block_economic_state` * `get_block_economic_state(block_hash)` * `block_hash`: [`H256`](#type-h256) @@ -1243,26 +1217,31 @@ Returns increased issuance, miner reward, and the total transaction fee of a blo This RPC returns null if the block is not in the [canonical chain](#canonical-chain). -CKB delays CKB creation for miners. The output cells in the cellbase of block N are for the miner creating block `N - 1 - ProposalWindow.farthest`. +CKB delays CKB creation for miners. The output cells in the cellbase of block N are for the +miner creating block `N - 1 - ProposalWindow.farthest`. -In mainnet, `ProposalWindow.farthest` is 10, so the outputs in block 100 are rewards for miner creating block 89. +In mainnet, `ProposalWindow.farthest` is 10, so the outputs in block 100 are rewards for +miner creating block 89. -Because of the delay, this RPC returns null if the block rewards are not finalized yet. For example, the economic state for block 89 is only available when the number returned by [`get_tip_block_number`](#method-get_tip_block_number) is greater than or equal to 100. +Because of the delay, this RPC returns null if the block rewards are not finalized yet. For +example, the economic state for block 89 is only available when the number returned by +[`get_tip_block_number`](#tymethod.get_tip_block_number) is greater than or equal to 100. ###### Params -* `block_hash` - Specifies the block hash which rewards should be analyzed. +* `block_hash` - Specifies the block hash which rewards should be analyzed. ###### Returns -If the block with the hash `block_hash` is in the [canonical chain](#canonical-chain) and its rewards have been finalized, return the block rewards analysis for this block. A special case is that the return value for genesis block is null. +If the block with the hash `block_hash` is in the [canonical chain](#canonical-chain) and +its rewards have been finalized, return the block rewards analysis for this block. A special +case is that the return value for genesis block is null. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1273,11 +1252,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1298,7 +1275,6 @@ Response } ``` - #### Method `get_transaction_proof` * `get_transaction_proof(tx_hashes, block_hash)` * `tx_hashes`: `Array<` [`H256`](#type-h256) `>` @@ -1309,16 +1285,14 @@ Returns a Merkle proof that transactions are included in a block. ###### Params -* `tx_hashes` - Transaction hashes, all transactions must be in the same block - -* `block_hash` - An optional parameter, if specified, looks for transactions in the block with this hash +* `tx_hashes` - Transaction hashes, all transactions must be in the same block +* `block_hash` - An optional parameter, if specified, looks for transactions in the block with this hash ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1329,11 +1303,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1348,7 +1320,6 @@ Response } ``` - #### Method `verify_transaction_proof` * `verify_transaction_proof(tx_proof)` * `tx_proof`: [`TransactionProof`](#type-transactionproof) @@ -1358,14 +1329,13 @@ Verifies that a proof points to transactions in a block, returning the transacti ###### Parameters -* `transaction_proof` - proof generated by [`get_transaction_proof`](#method-get_transaction_proof). +* `transaction_proof` - proof generated by [`get_transaction_proof`](#tymethod.get_transaction_proof). ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1383,11 +1353,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1397,27 +1365,24 @@ Response } ``` - #### Method `get_transaction_and_witness_proof` * `get_transaction_and_witness_proof(tx_hashes, block_hash)` * `tx_hashes`: `Array<` [`H256`](#type-h256) `>` * `block_hash`: [`H256`](#type-h256) `|` `null` * result: [`TransactionAndWitnessProof`](#type-transactionandwitnessproof) -Returns a Merkle proof of transactions’ witness included in a block. +Returns a Merkle proof of transactions' witness included in a block. ###### Params -* `tx_hashes` - Transaction hashes, all transactions must be in the same block - -* `block_hash` - An optional parameter, if specified, looks for transactions in the block with this hash +* `tx_hashes` - Transaction hashes, all transactions must be in the same block +* `block_hash` - An optional parameter, if specified, looks for transactions in the block with this hash ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1428,11 +1393,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -1452,7 +1415,6 @@ Response } ``` - #### Method `verify_transaction_and_witness_proof` * `verify_transaction_and_witness_proof(tx_proof)` * `tx_proof`: [`TransactionAndWitnessProof`](#type-transactionandwitnessproof) @@ -1462,14 +1424,13 @@ Verifies that a proof points to transactions in a block, returning the transacti ###### Parameters -* `tx_proof` - proof generated by [`get_transaction_and_witness_proof`](#method-get_transaction_and_witness_proof). +* `tx_proof` - proof generated by [`get_transaction_and_witness_proof`](#tymethod.get_transaction_and_witness_proof). ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1492,11 +1453,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1506,37 +1465,40 @@ Response } ``` - #### Method `get_fork_block` * `get_fork_block(block_hash, verbosity)` * `block_hash`: [`H256`](#type-h256) - * `verbosity`: [`Uint32`](#type-uint32) `|` `null` -* result: [`BlockView`](#type-blockview) `|` [`SerializedBlock`](#type-serializedblock) `|` `null` + * `verbosity`: [`AlertId`](#type-alertid) `|` `null` +* result: [`Either_for_BlockView_and_JsonBytes`](#type-either_for_blockview_and_jsonbytes) `|` `null` Returns the information about a fork block by hash. ###### Params -* `block_hash` - the fork block hash. - -* `verbosity` - result format which allows 0 and 2. (**Optional**, the default is 2.) +* `block_hash` - the fork block hash. +* `verbosity` - result format which allows 0 and 2. (**Optional**, the default is 2.) ###### Returns -The RPC returns a fork block or null. When the RPC returns a block, the block hash must equal to the parameter `block_hash`. +The RPC returns a fork block or null. When the RPC returns a block, the block hash must equal to +the parameter `block_hash`. -Please note that due to the technical nature of the peer to peer sync, the RPC may return null or a fork block result on different nodes with same `block_hash` even they are fully synced to the [canonical chain](#canonical-chain). And because of [chain reorganization](#chain-reorganization), for the same `block_hash`, the RPC may sometimes return null and sometimes return the fork block. +Please note that due to the technical nature of the peer to peer sync, the RPC may return null or a fork block +result on different nodes with same `block_hash` even they are fully synced to the [canonical chain](#canonical-chain). +And because of [chain reorganization](#chain-reorganization), for the same `block_hash`, the +RPC may sometimes return null and sometimes return the fork block. -When `verbosity` is 2, it returns a JSON object as the `result`. See `BlockView` for the schema. +When `verbosity` is 2, it returns a JSON object as the `result`. See `BlockView` for the +schema. -When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string encodes the block serialized by molecule using schema `table Block`. +When `verbosity` is 0, it returns a 0x-prefixed hex string as the `result`. The string +encodes the block serialized by molecule using schema `table Block`. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1547,11 +1509,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1610,11 +1570,9 @@ Response } ``` - The response looks like below when `verbosity` is 0. - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -1622,9 +1580,9 @@ The response looks like below when `verbosity` is 0. } ``` - #### Method `get_consensus` * `get_consensus()` + * result: [`Consensus`](#type-consensus) Return various consensus parameters. @@ -1637,8 +1595,7 @@ If any hardfork feature has `epoch=null`, it means the feature will never be act Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1647,11 +1604,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1718,21 +1673,21 @@ Response } ``` - #### Method `get_block_median_time` * `get_block_median_time(block_hash)` * `block_hash`: [`H256`](#type-h256) -* result: [`Timestamp`](#type-timestamp) `|` `null` +* result: [`Uint64`](#type-uint64) `|` `null` Returns the past median time by block hash. ###### Params -* `block_hash` - A median time is calculated for a consecutive block sequence. `block_hash` indicates the highest block of the sequence. +* `block_hash` - A median time is calculated for a consecutive block sequence. `block_hash` indicates the highest block of the sequence. ###### Returns -When the given block hash is not on the current canonical chain, this RPC returns null; otherwise returns the median time of the consecutive 37 blocks where the given block_hash has the highest height. +When the given block hash is not on the current canonical chain, this RPC returns null; +otherwise returns the median time of the consecutive 37 blocks where the given block_hash has the highest height. Note that the given block is included in the median time. The included block number range is `[MAX(block - 36, 0), block]`. @@ -1740,8 +1695,7 @@ Note that the given block is included in the median time. The included block num Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1752,11 +1706,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1764,7 +1716,6 @@ Response } ``` - #### Method `estimate_cycles` * `estimate_cycles(tx)` * `tx`: [`Transaction`](#type-transaction) @@ -1772,22 +1723,21 @@ Response `estimate_cycles` run a transaction and return the execution consumed cycles. -This method will not check the transaction validity, but only run the lock script and type script and then return the execution cycles. +This method will not check the transaction validity, but only run the lock script +and type script and then return the execution cycles. It is used to estimate how many cycles the scripts consume. ###### Errors -* [`TransactionFailedToResolve (-301)`](#error-transactionfailedtoresolve) - Failed to resolve the referenced cells and headers used in the transaction, as inputs or dependencies. - -* [`TransactionFailedToVerify (-302)`](#error-transactionfailedtoverify) - There is a script returns with an error. +* [`TransactionFailedToResolve (-301)`](../enum.RPCError.html#variant.TransactionFailedToResolve) - Failed to resolve the referenced cells and headers used in the transaction, as inputs or dependencies. +* [`TransactionFailedToVerify (-302)`](../enum.RPCError.html#variant.TransactionFailedToVerify) - There is a script returns with an error. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1836,11 +1786,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1850,30 +1798,30 @@ Response } ``` - #### Method `get_fee_rate_statics` * `get_fee_rate_statics(target)` * `target`: [`Uint64`](#type-uint64) `|` `null` * result: [`FeeRateStatistics`](#type-feeratestatistics) `|` `null` -👎Deprecated since 0.109.0: Please use the RPC method [`get_fee_rate_statistics`](#method-get_fee_rate_statistics) instead - Returns the fee_rate statistics of confirmed blocks on the chain ###### Params -* `target` - Specify the number (1 - 101) of confirmed blocks to be counted. If the number is even, automatically add one. If not specified, defaults to 21 +* `target` - Specify the number (1 - 101) of confirmed blocks to be counted. + If the number is even, automatically add one. If not specified, defaults to 21 ###### Returns -If the query finds the corresponding historical data, the corresponding statistics are returned, containing the mean and median, in shannons per kilo-weight. If not, it returns null. +If the query finds the corresponding historical data, +the corresponding statistics are returned, +containing the mean and median, in shannons per kilo-weight. +If not, it returns null. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1882,11 +1830,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1897,7 +1843,6 @@ Response } ``` - #### Method `get_fee_rate_statistics` * `get_fee_rate_statistics(target)` * `target`: [`Uint64`](#type-uint64) `|` `null` @@ -1907,18 +1852,21 @@ Returns the fee_rate statistics of confirmed blocks on the chain ###### Params -* `target` - Specify the number (1 - 101) of confirmed blocks to be counted. If the number is even, automatically add one. If not specified, defaults to 21 +* `target` - Specify the number (1 - 101) of confirmed blocks to be counted. + If the number is even, automatically add one. If not specified, defaults to 21 ###### Returns -If the query finds the corresponding historical data, the corresponding statistics are returned, containing the mean and median, in shannons per kilo-weight. If not, it returns null. +If the query finds the corresponding historical data, +the corresponding statistics are returned, +containing the mean and median, in shannons per kilo-weight. +If not, it returns null. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1927,11 +1875,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -1942,8 +1888,51 @@ Response } ``` +### Module `Debug` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Debug&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/debug_rpc_doc.json) + +RPC Module Debug for internal RPC methods. + +**This module is for CKB developers and will not guarantee compatibility.** The methods here +will be changed or removed without advanced notification. + +#### Method `jemalloc_profiling_dump` +* `jemalloc_profiling_dump()` + +* result: `string` + +Dumps jemalloc memory profiling information into a file. + +The file is stored in the server running the CKB node. + +The RPC returns the path to the dumped file on success or returns an error on failure. + +#### Method `update_main_logger` +* `update_main_logger(config)` + * `config`: [`MainLoggerConfig`](#type-mainloggerconfig) +* result: `null` + +Changes main logger config options while CKB is running. + +#### Method `set_extra_logger` +* `set_extra_logger(name, config_opt)` + * `name`: `string` + * `config_opt`: [`ExtraLoggerConfig`](#type-extraloggerconfig) `|` `null` +* result: `null` + +Sets logger config options for extra loggers. + +CKB nodes allow setting up extra loggers. These loggers will have their own log files and +they only append logs to their log files. + +###### Params -### Module Experiment +* `name` - Extra logger name +* `config_opt` - Adds a new logger or update an existing logger when this is not null. +Removes the logger when this is null. + +### Module `Experiment` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Experiment&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/experiment_rpc_doc.json) RPC Module Experiment for experimenting methods. @@ -1956,26 +1945,23 @@ The methods here may be removed or changed in future releases without prior noti * `tx`: [`Transaction`](#type-transaction) * result: [`EstimateCycles`](#type-estimatecycles) -👎Deprecated since 0.105.1: Please use the RPC method [`estimate_cycles`](#method-estimate_cycles) instead - Dry run a transaction and return the execution cycles. -This method will not check the transaction validity, but only run the lock script and type script and then return the execution cycles. +This method will not check the transaction validity, but only run the lock script +and type script and then return the execution cycles. It is used to debug transaction scripts and query how many cycles the scripts consume. ###### Errors -* [`TransactionFailedToResolve (-301)`](#error-transactionfailedtoresolve) - Failed to resolve the referenced cells and headers used in the transaction, as inputs or dependencies. - -* [`TransactionFailedToVerify (-302)`](#error-transactionfailedtoverify) - There is a script returns with an error. +* [`TransactionFailedToResolve (-301)`](../enum.RPCError.html#variant.TransactionFailedToResolve) - Failed to resolve the referenced cells and headers used in the transaction, as inputs or dependencies. +* [`TransactionFailedToVerify (-302)`](../enum.RPCError.html#variant.TransactionFailedToVerify) - There is a script returns with an error. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -2024,11 +2010,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -2038,43 +2022,43 @@ Response } ``` - #### Method `calculate_dao_maximum_withdraw` * `calculate_dao_maximum_withdraw(out_point, kind)` * `out_point`: [`OutPoint`](#type-outpoint) * `kind`: [`DaoWithdrawingCalculationKind`](#type-daowithdrawingcalculationkind) -* result: [`Capacity`](#type-capacity) +* result: [`Uint64`](#type-uint64) -Calculates the maximum withdrawal one can get, given a referenced DAO cell, and a withdrawing block hash. +Calculates the maximum withdrawal one can get, given a referenced DAO cell, and +a withdrawing block hash. ###### Params -* `out_point` - Reference to the DAO cell, the depositing transaction’s output. - -* `kind` - Two kinds of dao withdrawal amount calculation option. +* `out_point` - Reference to the DAO cell, the depositing transaction's output. +* `kind` - Two kinds of dao withdrawal amount calculation option. -option 1, the assumed reference block hash for withdrawing phase 1 transaction, this block must be in the [canonical chain](#canonical-chain), the calculation of occupied capacity will be based on the depositing transaction’s output, assuming the output of phase 1 transaction is the same as the depositing transaction’s output. +option 1, the assumed reference block hash for withdrawing phase 1 transaction, this block must be in the +[canonical chain](trait.ChainRpc.html#canonical-chain), the calculation of occupied capacity will be based on the depositing transaction's output, assuming the output of phase 1 transaction is the same as the depositing transaction's output. -option 2, the out point of the withdrawing phase 1 transaction, the calculation of occupied capacity will be based on corresponding phase 1 transaction’s output. +option 2, the out point of the withdrawing phase 1 transaction, the calculation of occupied capacity will be based on corresponding phase 1 transaction's output. ###### Returns The RPC returns the final capacity when the cell `out_point` is withdrawn using the block hash or withdrawing phase 1 transaction out point as the reference. -In CKB, scripts cannot get the information about in which block the transaction is committed. A workaround is letting the transaction reference a block hash so the script knows that the transaction is committed at least after the reference block. +In CKB, scripts cannot get the information about in which block the transaction is +committed. A workaround is letting the transaction reference a block hash so the script +knows that the transaction is committed at least after the reference block. ###### Errors -* [`DaoError (-5)`](#error-daoerror) - The given out point is not a valid cell for DAO computation. - -* [`CKBInternalError (-1)`](#error-ckbinternalerror) - Mathematics overflow. +* [`DaoError (-5)`](../enum.RPCError.html#variant.DaoError) - The given out point is not a valid cell for DAO computation. +* [`CKBInternalError (-1)`](../enum.RPCError.html#variant.CKBInternalError) - Mathematics overflow. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -2089,11 +2073,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -2101,29 +2083,27 @@ Response } ``` - -### Module Indexer +### Module `Indexer` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Indexer&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/indexer_rpc_doc.json) RPC Module Indexer. #### Method `get_indexer_tip` * `get_indexer_tip()` + * result: [`IndexerTip`](#type-indexertip) `|` `null` Returns the indexed tip ###### Returns - -* block_hash - indexed tip block hash - -* block_number - indexed tip block number + * block_hash - indexed tip block hash + * block_number - indexed tip block number ###### Examples Request - -``` +```json { "id": 2, "jsonrpc": "2.0", @@ -2131,11 +2111,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -2146,77 +2124,54 @@ Response } ``` - #### Method `get_cells` * `get_cells(search_key, order, limit, after)` * `search_key`: [`IndexerSearchKey`](#type-indexersearchkey) * `order`: [`IndexerOrder`](#type-indexerorder) - * `limit`: [`Uint32`](#type-uint32) + * `limit`: [`AlertId`](#type-alertid) * `after`: [`JsonBytes`](#type-jsonbytes) `|` `null` -* result: `IndexerPagination<` [`IndexerCell`](#type-indexercell) `>` +* result: [`IndexerPagination_for_IndexerCell`](#type-indexerpagination_for_indexercell) Returns the live cells collection by the lock or type script. ###### Params -* search_key: - * script - Script, supports prefix search - - * script_type - enum, lock | type - - * script_search_mode - enum, prefix | exact - - * filter - filter cells by following conditions, all conditions are optional - * script: if search script type is lock, filter cells by type script prefix, and vice versa - - * script_len_range: [u64; 2], filter cells by script len range, [inclusive, exclusive] - - * output_data: filter cells by output data - - * output_data_filter_mode: enum, prefix | exact | partial - - * output_data_len_range: [u64; 2], filter cells by output data len range, [inclusive, exclusive] - - * output_capacity_range: [u64; 2], filter cells by output capacity range, [inclusive, exclusive] - - * block_range: [u64; 2], filter cells by block number range, [inclusive, exclusive] +* search_key: + - script - Script, supports prefix search + - script_type - enum, lock | type + - script_search_mode - enum, prefix | exact + - filter - filter cells by following conditions, all conditions are optional + - script: if search script type is lock, filter cells by type script prefix, and vice versa + - script_len_range: [u64; 2], filter cells by script len range, [inclusive, exclusive] + - output_data: filter cells by output data + - output_data_filter_mode: enum, prefix | exact | partial + - output_data_len_range: [u64; 2], filter cells by output data len range, [inclusive, exclusive] + - output_capacity_range: [u64; 2], filter cells by output capacity range, [inclusive, exclusive] + - block_range: [u64; 2], filter cells by block number range, [inclusive, exclusive] + - with_data - bool, optional default is `true`, if with_data is set to false, the field of returning cell.output_data is null in the result +* order: enum, asc | desc +* limit: result size limit +* after: pagination parameter, optional +###### Returns - * with_data - bool, optional default is `true`, if with_data is set to false, the field of returning cell.output_data is null in the result +If the number of objects is less than the requested `limit`, it indicates that these are the last page of get_cells. +* objects: + - output: the fields of an output cell + - output_data: the cell data + - out_point: reference to a cell via transaction hash and output index + - block_number: the number of the transaction committed in the block + - tx_index: the position index of the transaction committed in the block +* last_cursor: pagination parameter -* order: enum, asc | desc +###### Examples -* limit: result size limit +* get cells by lock script -* after: pagination parameter, optional +Request -###### Returns - -If the number of objects is less than the requested `limit`, it indicates that these are the last page of get_cells. - -* objects: - * output: the fields of an output cell - - * output_data: the cell data - - * out_point: reference to a cell via transaction hash and output index - - * block_number: the number of the transaction committed in the block - - * tx_index: the position index of the transaction committed in the block - - -* last_cursor: pagination parameter - -###### Examples - -* get cells by lock script - -Request - - -``` +```json { "id": 2, "jsonrpc": "2.0", @@ -2236,11 +2191,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -2342,13 +2295,11 @@ Response } ``` - -* get cells by lock script and filter by type script +* get cells by lock script and filter by type script Request - -``` +```json { "id": 2, "jsonrpc": "2.0", @@ -2375,11 +2326,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -2413,13 +2362,12 @@ Response } ``` - -* get cells by lock script and filter empty type script by setting script_len_range to [0, 1), script_len is caculated by (code_hash + hash_type + args).len +* get cells by lock script and filter empty type script by setting script_len_range to +[0, 1), script_len is caculated by (code_hash + hash_type + args).len Request - -``` +```json { "id": 2, "jsonrpc": "2.0", @@ -2442,11 +2390,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -2476,13 +2422,11 @@ Response } ``` - -* get cells by lock script and filter capacity range +* get cells by lock script and filter capacity range Request - -``` +```json { "id": 2, "jsonrpc": "2.0", @@ -2505,11 +2449,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -2539,77 +2481,53 @@ Response } ``` - #### Method `get_transactions` * `get_transactions(search_key, order, limit, after)` * `search_key`: [`IndexerSearchKey`](#type-indexersearchkey) * `order`: [`IndexerOrder`](#type-indexerorder) - * `limit`: [`Uint32`](#type-uint32) + * `limit`: [`AlertId`](#type-alertid) * `after`: [`JsonBytes`](#type-jsonbytes) `|` `null` -* result: `IndexerPagination<` [`IndexerTx`](#type-indexertx) `>` +* result: [`IndexerPagination_for_IndexerTx`](#type-indexerpagination_for_indexertx) Returns the transactions collection by the lock or type script. -* search_key: - * script - Script, supports prefix search when group_by_transaction is false - - * script_type - enum, lock | type - - * script_search_mode - enum, prefix | exact - - * filter - filter cells by following conditions, all conditions are optional - * script: if search script type is lock, filter cells by type script, and vice versa - - * block_range: [u64; 2], filter cells by block number range, [inclusive, exclusive] - - - * group_by_transaction - bool, optional default is `false`, if group_by_transaction is set to true, the returning objects will be grouped by the tx hash - - -* order: enum, asc | desc - -* limit: result size limit - -* after: pagination parameter, optional +* search_key: + - script - Script, supports prefix search when group_by_transaction is false + - script_type - enum, lock | type + - script_search_mode - enum, prefix | exact + - filter - filter cells by following conditions, all conditions are optional + - script: if search script type is lock, filter cells by type script, and vice versa + - block_range: [u64; 2], filter cells by block number range, [inclusive, exclusive] + - group_by_transaction - bool, optional default is `false`, if group_by_transaction is set to true, the returning objects will be grouped by the tx hash +* order: enum, asc | desc +* limit: result size limit +* after: pagination parameter, optional ###### Returns If the number of objects is less than the requested `limit`, it indicates that these are the last page of get_transactions. -* objects - enum, ungrouped TxWithCell | grouped TxWithCells - * TxWithCell: - * tx_hash: transaction hash, - - * block_number: the number of the transaction committed in the block - - * tx_index: the position index of the transaction committed in the block - - * io_type: enum, input | output - - * io_index: the position index of the cell in the transaction inputs or outputs - - - * TxWithCells: - * tx_hash: transaction hash, - - * block_number: the number of the transaction committed in the block - - * tx_index: the position index of the transaction committed in the block - - * cells: Array [[io_type, io_index]] - - - -* last_cursor - pagination parameter + * objects - enum, ungrouped TxWithCell | grouped TxWithCells + - TxWithCell: + - tx_hash: transaction hash, + - block_number: the number of the transaction committed in the block + - tx_index: the position index of the transaction committed in the block + - io_type: enum, input | output + - io_index: the position index of the cell in the transaction inputs or outputs + - TxWithCells: + - tx_hash: transaction hash, + - block_number: the number of the transaction committed in the block + - tx_index: the position index of the transaction committed in the block + - cells: Array [[io_type, io_index]] + * last_cursor - pagination parameter ###### Examples -* get transactions by lock script +* get transactions by lock script Request - -``` +```json { "id": 2, "jsonrpc": "2.0", @@ -2629,11 +2547,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -2785,13 +2701,11 @@ Response } ``` - -* get transactions by lock script and group by tx hash +* get transactions by lock script and group by tx hash Request - -``` +```json { "id": 2, "jsonrpc": "2.0", @@ -2812,11 +2726,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -2985,7 +2897,6 @@ Response } ``` - #### Method `get_cells_capacity` * `get_cells_capacity(search_key)` * `search_key`: [`IndexerSearchKey`](#type-indexersearchkey) @@ -2995,44 +2906,30 @@ Returns the live cells capacity by the lock or type script. ###### Parameters -* search_key: - * script - Script - - * script_type - enum, lock | type - - * script_search_mode - enum, prefix | exact - - * filter - filter cells by following conditions, all conditions are optional - * script: if search script type is lock, filter cells by type script prefix, and vice versa - - * script_len_range: [u64; 2], filter cells by script len range, [inclusive, exclusive] - - * output_data: filter cells by output data - - * output_data_filter_mode: enum, prefix | exact | partial - - * output_data_len_range: [u64; 2], filter cells by output data len range, [inclusive, exclusive] - - * output_capacity_range: [u64; 2], filter cells by output capacity range, [inclusive, exclusive] - - * block_range: [u64; 2], filter cells by block number range, [inclusive, exclusive] - - +* search_key: + - script - Script + - script_type - enum, lock | type + - script_search_mode - enum, prefix | exact + - filter - filter cells by following conditions, all conditions are optional + - script: if search script type is lock, filter cells by type script prefix, and vice versa + - script_len_range: [u64; 2], filter cells by script len range, [inclusive, exclusive] + - output_data: filter cells by output data + - output_data_filter_mode: enum, prefix | exact | partial + - output_data_len_range: [u64; 2], filter cells by output data len range, [inclusive, exclusive] + - output_capacity_range: [u64; 2], filter cells by output capacity range, [inclusive, exclusive] + - block_range: [u64; 2], filter cells by block number range, [inclusive, exclusive] ###### Returns -* capacity - total capacity - -* block_hash - indexed tip block hash - -* block_number - indexed tip block number + * capacity - total capacity + * block_hash - indexed tip block hash + * block_number - indexed tip block number ###### Examples Request - -``` +```json { "id": 2, "jsonrpc": "2.0", @@ -3050,11 +2947,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -3066,8 +2961,8 @@ Response } ``` - -### Module IntegrationTest +### Module `Integration_test` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Integration_test&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/integration_test_rpc_doc.json) RPC for Integration Test. @@ -3081,20 +2976,15 @@ process block without any block verification. ###### Params -* - `data` - block data(in binary). - - -* - `broadcast` - true to enable broadcast(relay) the block to other peers. +* `data` - block data(in binary). +* `broadcast` - true to enable broadcast(relay) the block to other peers. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3149,11 +3039,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3161,7 +3049,6 @@ Response } ``` - #### Method `truncate` * `truncate(target_tip_hash)` * `target_tip_hash`: [`H256`](#type-h256) @@ -3171,14 +3058,13 @@ Truncate chain to specified tip hash, can only truncate less then 50000 blocks e ###### Params -* `target_tip_hash` - specified header hash +* `target_tip_hash` - specified header hash ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3189,11 +3075,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3201,9 +3085,9 @@ Response } ``` - #### Method `generate_block` * `generate_block()` + * result: [`H256`](#type-h256) Generate block(with verification) and broadcast the block. @@ -3214,8 +3098,7 @@ Note that if called concurrently, it may return the hash of the same block. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3224,11 +3107,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3236,19 +3117,19 @@ Response } ``` - #### Method `generate_epochs` * `generate_epochs(num_epochs)` - * `num_epochs`: [`EpochNumberWithFraction`](#type-epochnumberwithfraction) -* result: [`EpochNumberWithFraction`](#type-epochnumberwithfraction) + * `num_epochs`: [`Uint64`](#type-uint64) +* result: [`Uint64`](#type-uint64) -Generate epochs during development, can be useful for scenarios like testing DAO-related functionalities. +Generate epochs during development, can be useful for scenarios +like testing DAO-related functionalities. Returns the updated epoch number after generating the specified number of epochs. ###### Params -* `num_epochs` - The number of epochs to generate. +* `num_epochs` - The number of epochs to generate. ###### Examples @@ -3256,8 +3137,7 @@ Request Generating 2 epochs: - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3266,13 +3146,14 @@ Generating 2 epochs: } ``` - -The input parameter “0x2” will be normalized to “0x10000000002”(the correct [`EpochNumberWithFraction`](#type-epochnumberwithfraction) type) within the method. Therefore, if you want to generate epochs as integers, you can simply pass an integer as long as it does not exceed 16777215 (24 bits). +The input parameter "0x2" will be normalized to "0x10000000002"(the correct +[`EpochNumberWithFraction`](#type-epochnumberwithfraction) type) within the method. +Therefore, if you want to generate epochs as integers, you can simply pass an integer +as long as it does not exceed 16777215 (24 bits). Generating 1/2 epoch: - -``` +```text { "id": 42, "jsonrpc": "2.0", @@ -3281,11 +3162,9 @@ Generating 1/2 epoch: } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3293,7 +3172,6 @@ Response } ``` - #### Method `notify_transaction` * `notify_transaction(transaction)` * `transaction`: [`Transaction`](#type-transaction) @@ -3303,14 +3181,13 @@ Add transaction to tx-pool. ###### Params -* `transaction` - specified transaction to add +* `transaction` - specified transaction to add ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3354,11 +3231,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3366,7 +3241,6 @@ Response } ``` - #### Method `generate_block_with_template` * `generate_block_with_template(block_template)` * `block_template`: [`BlockTemplate`](#type-blocktemplate) @@ -3378,14 +3252,13 @@ then process block and broadcast the block. ###### Params -* `block_template` - specified transaction to add +* `block_template` - specified transaction to add ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3466,11 +3339,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3478,7 +3349,6 @@ Response } ``` - #### Method `calculate_dao_field` * `calculate_dao_field(block_template)` * `block_template`: [`BlockTemplate`](#type-blocktemplate) @@ -3488,14 +3358,13 @@ Return calculated dao field according to specified block template. ###### Params -* `block_template` - specified block template +* `block_template` - specified block template ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3576,11 +3445,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3588,38 +3455,40 @@ Response } ``` - -### Module Miner +### Module `Miner` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Miner&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/miner_rpc_doc.json) RPC Module Miner for miners. -A miner gets a template from CKB, optionally selects transactions, resolves the PoW puzzle, and submits the found new block. +A miner gets a template from CKB, optionally selects transactions, resolves the PoW puzzle, and +submits the found new block. #### Method `get_block_template` * `get_block_template(bytes_limit, proposals_limit, max_version)` * `bytes_limit`: [`Uint64`](#type-uint64) `|` `null` * `proposals_limit`: [`Uint64`](#type-uint64) `|` `null` - * `max_version`: [`Version`](#type-version) `|` `null` + * `max_version`: [`AlertId`](#type-alertid) `|` `null` * result: [`BlockTemplate`](#type-blocktemplate) Returns block template for miners. -Miners can assemble the new block from the template. The RPC is designed to allow miners to remove transactions and adding new transactions to the block. +Miners can assemble the new block from the template. The RPC is designed to allow miners +to remove transactions and adding new transactions to the block. ###### Params -* `bytes_limit` - the max serialization size in bytes of the block. (**Optional:** the default is the consensus limit.) - -* `proposals_limit` - the max count of proposals. (**Optional:** the default is the consensus limit.) - -* `max_version` - the max block version. (**Optional:** the default is one configured in the current client version.) +* `bytes_limit` - the max serialization size in bytes of the block. + (**Optional:** the default is the consensus limit.) +* `proposals_limit` - the max count of proposals. + (**Optional:** the default is the consensus limit.) +* `max_version` - the max block version. + (**Optional:** the default is one configured in the current client version.) ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3632,11 +3501,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3714,7 +3581,6 @@ Response } ``` - #### Method `submit_block` * `submit_block(work_id, block)` * `work_id`: `string` @@ -3725,16 +3591,14 @@ Submit new block to the network. ###### Params -* `work_id` - The same work ID returned from [`get_block_template`](#method-get_block_template). - -* `block` - The assembled block from the block template and which PoW puzzle has been resolved. +* `work_id` - The same work ID returned from [`get_block_template`](#tymethod.get_block_template). +* `block` - The assembled block from the block template and which PoW puzzle has been resolved. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3795,11 +3659,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3807,13 +3669,14 @@ Response } ``` - -### Module Net +### Module `Net` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Net&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/net_rpc_doc.json) RPC Module Net for P2P network. #### Method `local_node_info` * `local_node_info()` + * result: [`LocalNode`](#type-localnode) Returns the local node information. @@ -3824,8 +3687,7 @@ The local node means the node itself which is serving the RPC. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3834,11 +3696,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3877,19 +3737,18 @@ Response } ``` - #### Method `get_peers` * `get_peers()` + * result: `Array<` [`RemoteNode`](#type-remotenode) `>` -Returns the connected peers’ information. +Returns the connected peers' information. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -3898,11 +3757,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4027,9 +3884,9 @@ Response } ``` - #### Method `get_banned_addresses` * `get_banned_addresses()` + * result: `Array<` [`BannedAddr`](#type-bannedaddr) `>` Returns all banned IPs/Subnets. @@ -4038,8 +3895,7 @@ Returns all banned IPs/Subnets. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4048,11 +3904,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4067,9 +3921,9 @@ Response } ``` - #### Method `clear_banned_addresses` * `clear_banned_addresses()` + * result: `null` Clears all banned IPs/Subnets. @@ -4078,8 +3932,7 @@ Clears all banned IPs/Subnets. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4088,11 +3941,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4100,12 +3951,11 @@ Response } ``` - #### Method `set_ban` * `set_ban(address, command, ban_time, absolute, reason)` * `address`: `string` * `command`: `string` - * `ban_time`: [`Timestamp`](#type-timestamp) `|` `null` + * `ban_time`: [`Uint64`](#type-uint64) `|` `null` * `absolute`: `boolean` `|` `null` * `reason`: `string` `|` `null` * result: `null` @@ -4114,34 +3964,25 @@ Inserts or deletes an IP/Subnet from the banned list ###### Params -* `address` - The IP/Subnet with an optional netmask (default is /32 = single IP). Examples: - * “192.168.0.2” bans a single IP - - * “192.168.0.0/24” bans IP from “192.168.0.0” to “192.168.0.255”. - - -* `command` - `insert` to insert an IP/Subnet to the list, `delete` to delete an IP/Subnet from the list. - -* `ban_time` - Time in milliseconds how long (or until when if [absolute] is set) the IP is banned, optional parameter, null means using the default time of 24h - -* `absolute` - If set, the `ban_time` must be an absolute timestamp in milliseconds since epoch, optional parameter. - -* `reason` - Ban reason, optional parameter. +* `address` - The IP/Subnet with an optional netmask (default is /32 = single IP). Examples: + * "192.168.0.2" bans a single IP + * "192.168.0.0/24" bans IP from "192.168.0.0" to "192.168.0.255". +* `command` - `insert` to insert an IP/Subnet to the list, `delete` to delete an IP/Subnet from the list. +* `ban_time` - Time in milliseconds how long (or until when if \[absolute\] is set) the IP is banned, optional parameter, null means using the default time of 24h +* `absolute` - If set, the `ban_time` must be an absolute timestamp in milliseconds since epoch, optional parameter. +* `reason` - Ban reason, optional parameter. ###### Errors -* [`InvalidParams (-32602)`](#error-invalidparams) - * Expected `address` to be a valid IP address with an optional netmask. - - * Expected `command` to be in the list [insert, delete]. - +* [`InvalidParams (-32602)`](../enum.RPCError.html#variant.InvalidParams) + * Expected `address` to be a valid IP address with an optional netmask. + * Expected `command` to be in the list [insert, delete]. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4156,11 +3997,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4168,9 +4007,9 @@ Response } ``` - #### Method `sync_state` * `sync_state()` + * result: [`SyncState`](#type-syncstate) Returns chain synchronization state of this node. @@ -4179,8 +4018,7 @@ Returns chain synchronization state of this node. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4189,11 +4027,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4210,7 +4046,6 @@ Response } ``` - #### Method `set_network_active` * `set_network_active(state)` * `state`: `boolean` @@ -4220,14 +4055,13 @@ Disable/enable all p2p network activity ###### Params -* `state` - true to enable networking, false to disable +* `state` - true to enable networking, false to disable ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4238,11 +4072,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4250,7 +4082,6 @@ Response } ``` - #### Method `add_node` * `add_node(peer_id, address)` * `peer_id`: `string` @@ -4261,23 +4092,19 @@ Attempts to add a node to the peers list and try connecting to it. ###### Params -* `peer_id` - The node id of the node. - -* `address` - The address of the node. +* `peer_id` - The node id of the node. +* `address` - The address of the node. The full P2P address is usually displayed as `address/peer_id`, for example in the log - -``` +```text 2020-09-16 15:31:35.191 +08:00 NetworkRuntime INFO ckb_network::network Listen on address: /ip4/192.168.2.100/tcp/8114/QmUsZHPbjjzU627UZFt4k8j6ycEcNvXRnVGxCPKqwbAfQS ``` - And in RPC `local_node_info`: - -``` +```json { "addresses": [ { @@ -4288,19 +4115,16 @@ And in RPC `local_node_info`: } ``` - In both of these examples, -* `peer_id` is `QmUsZHPbjjzU627UZFt4k8j6ycEcNvXRnVGxCPKqwbAfQS`, - -* and `address` is `/ip4/192.168.2.100/tcp/8114` +* `peer_id` is `QmUsZHPbjjzU627UZFt4k8j6ycEcNvXRnVGxCPKqwbAfQS`, +* and `address` is `/ip4/192.168.2.100/tcp/8114` ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4312,11 +4136,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4324,7 +4146,6 @@ Response } ``` - #### Method `remove_node` * `remove_node(peer_id)` * `peer_id`: `string` @@ -4334,16 +4155,17 @@ Attempts to remove a node from the peers list and try disconnecting from it. ###### Params -* `peer_id` - The peer id of the node. +* `peer_id` - The peer id of the node. -This is the last part of a full P2P address. For example, in address “/ip4/192.168.2.100/tcp/8114/QmUsZHPbjjzU627UZFt4k8j6ycEcNvXRnVGxCPKqwbAfQS”, the `peer_id` is `QmUsZHPbjjzU627UZFt4k8j6ycEcNvXRnVGxCPKqwbAfQS`. +This is the last part of a full P2P address. For example, in address +"/ip4/192.168.2.100/tcp/8114/QmUsZHPbjjzU627UZFt4k8j6ycEcNvXRnVGxCPKqwbAfQS", the `peer_id` +is `QmUsZHPbjjzU627UZFt4k8j6ycEcNvXRnVGxCPKqwbAfQS`. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4354,11 +4176,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4366,9 +4186,9 @@ Response } ``` - #### Method `ping_peers` * `ping_peers()` + * result: `null` Requests that a ping is sent to all connected peers, to measure ping time. @@ -4377,8 +4197,7 @@ Requests that a ping is sent to all connected peers, to measure ping time. Requests - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4387,11 +4206,9 @@ Requests } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4399,8 +4216,8 @@ Response } ``` - -### Module Pool +### Module `Pool` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Pool&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/pool_rpc_doc.json) RPC Module Pool for transaction memory pool. @@ -4410,38 +4227,33 @@ RPC Module Pool for transaction memory pool. * `outputs_validator`: [`OutputsValidator`](#type-outputsvalidator) `|` `null` * result: [`H256`](#type-h256) -Submits a new transaction into the transaction pool. If the transaction is already in the pool, rebroadcast it to peers. +Submits a new transaction into the transaction pool. If the transaction is already in the +pool, rebroadcast it to peers. -Please note that `send_transaction` is an asynchronous process. The return of `send_transaction` does NOT indicate that the transaction have been fully verified. If you want to track the status of the transaction, please use the `get_transaction`rpc. +Please note that `send_transaction` is an asynchronous process. +The return of `send_transaction` does NOT indicate that the transaction have been fully verified. +If you want to track the status of the transaction, please use the `get_transaction`rpc. ###### Params -* `transaction` - The transaction. - -* `outputs_validator` - Validates the transaction outputs before entering the tx-pool. (**Optional**, default is “passthrough”). +* `transaction` - The transaction. +* `outputs_validator` - Validates the transaction outputs before entering the tx-pool. (**Optional**, default is "passthrough"). ###### Errors -* [`PoolRejectedTransactionByOutputsValidator (-1102)`](#error-poolrejectedtransactionbyoutputsvalidator) - The transaction is rejected by the validator specified by `outputs_validator`. If you really want to send transactions with advanced scripts, please set `outputs_validator` to “passthrough”. - -* [`PoolRejectedTransactionByMinFeeRate (-1104)`](#error-poolrejectedtransactionbyminfeerate) - The transaction fee rate must be greater than or equal to the config option `tx_pool.min_fee_rate`. - -* [`PoolRejectedTransactionByMaxAncestorsCountLimit (-1105)`](#error-poolrejectedtransactionbymaxancestorscountlimit) - The ancestors count must be greater than or equal to the config option `tx_pool.max_ancestors_count`. - -* [`PoolIsFull (-1106)`](#error-poolisfull) - Pool is full. - -* [`PoolRejectedDuplicatedTransaction (-1107)`](#error-poolrejectedduplicatedtransaction) - The transaction is already in the pool. - -* [`TransactionFailedToResolve (-301)`](#error-transactionfailedtoresolve) - Failed to resolve the referenced cells and headers used in the transaction, as inputs or dependencies. - -* [`TransactionFailedToVerify (-302)`](#error-transactionfailedtoverify) - Failed to verify the transaction. +* [`PoolRejectedTransactionByOutputsValidator (-1102)`](../enum.RPCError.html#variant.PoolRejectedTransactionByOutputsValidator) - The transaction is rejected by the validator specified by `outputs_validator`. If you really want to send transactions with advanced scripts, please set `outputs_validator` to "passthrough". +* [`PoolRejectedTransactionByMinFeeRate (-1104)`](../enum.RPCError.html#variant.PoolRejectedTransactionByMinFeeRate) - The transaction fee rate must be greater than or equal to the config option `tx_pool.min_fee_rate`. +* [`PoolRejectedTransactionByMaxAncestorsCountLimit (-1105)`](../enum.RPCError.html#variant.PoolRejectedTransactionByMaxAncestorsCountLimit) - The ancestors count must be greater than or equal to the config option `tx_pool.max_ancestors_count`. +* [`PoolIsFull (-1106)`](../enum.RPCError.html#variant.PoolIsFull) - Pool is full. +* [`PoolRejectedDuplicatedTransaction (-1107)`](../enum.RPCError.html#variant.PoolRejectedDuplicatedTransaction) - The transaction is already in the pool. +* [`TransactionFailedToResolve (-301)`](../enum.RPCError.html#variant.TransactionFailedToResolve) - Failed to resolve the referenced cells and headers used in the transaction, as inputs or dependencies. +* [`TransactionFailedToVerify (-302)`](../enum.RPCError.html#variant.TransactionFailedToVerify) - Failed to verify the transaction. ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4491,11 +4303,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4503,7 +4313,6 @@ Response } ``` - #### Method `remove_transaction` * `remove_transaction(tx_hash)` * `tx_hash`: [`H256`](#type-h256) @@ -4513,7 +4322,7 @@ Removes a transaction and all transactions which depends on it from tx pool if i ###### Params -* `tx_hash` - Hash of a transaction. +* `tx_hash` - Hash of a transaction. ###### Returns @@ -4523,8 +4332,7 @@ If the transaction exists, return true; otherwise, return false. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4535,11 +4343,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4547,9 +4353,9 @@ Response } ``` - #### Method `tx_pool_info` * `tx_pool_info()` + * result: [`TxPoolInfo`](#type-txpoolinfo) Returns the transaction pool information. @@ -4558,8 +4364,7 @@ Returns the transaction pool information. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4568,11 +4373,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4593,9 +4396,9 @@ Response } ``` - #### Method `clear_tx_pool` * `clear_tx_pool()` + * result: `null` Removes all transactions from the transaction pool. @@ -4604,8 +4407,7 @@ Removes all transactions from the transaction pool. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4614,11 +4416,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4626,24 +4426,21 @@ Response } ``` - #### Method `get_raw_tx_pool` * `get_raw_tx_pool(verbose)` * `verbose`: `boolean` `|` `null` * result: [`RawTxPool`](#type-rawtxpool) Returns all transaction ids in tx pool as a json array of string transaction ids. - ###### Params -* `verbose` - True for a json object, false for array of transaction ids, default=false +* `verbose` - True for a json object, false for array of transaction ids, default=false ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4652,11 +4449,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4678,24 +4473,21 @@ Response } ``` - #### Method `get_pool_tx_detail_info` * `get_pool_tx_detail_info(tx_hash)` * `tx_hash`: [`H256`](#type-h256) * result: [`PoolTxDetailInfo`](#type-pooltxdetailinfo) Query and returns the details of a transaction in the pool, only for trouble shooting - ###### Params -* `tx_hash` - Hash of a transaction +* `tx_hash` - Hash of a transaction ###### Examples Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4706,11 +4498,9 @@ Request } ``` - Response - -``` +```json { "jsonrpc": "2.0", "result": { @@ -4732,9 +4522,9 @@ Response } ``` - #### Method `tx_pool_ready` * `tx_pool_ready()` + * result: `boolean` Returns whether tx-pool service is started, ready for request. @@ -4743,8 +4533,7 @@ Returns whether tx-pool service is started, ready for request. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4753,11 +4542,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4765,13 +4552,14 @@ Response } ``` - -### Module Stats +### Module `Stats` +- [👉 OpenRPC spec](http://playground.open-rpc.org/?uiSchema[appBar][ui:title]=CKB-Stats&uiSchema[appBar][ui:splitView]=false&uiSchema[appBar][ui:examplesDropdown]=false&uiSchema[appBar][ui:logoUrl]=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/main/ckb-logo.jpg&schemaUrl=https://raw.githubusercontent.com/cryptape/ckb-rpc-resources/e7b5c1c42c07d4ac93acd1b02e9b29458658d3fa/json/stats_rpc_doc.json) RPC Module Stats for getting various statistic data. #### Method `get_blockchain_info` * `get_blockchain_info()` + * result: [`ChainInfo`](#type-chaininfo) Returns statistics about the chain. @@ -4780,8 +4568,7 @@ Returns statistics about the chain. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4790,11 +4577,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4816,9 +4601,9 @@ Response } ``` - #### Method `get_deployments_info` * `get_deployments_info()` + * result: [`DeploymentsInfo`](#type-deploymentsinfo) Returns statistics about the chain. @@ -4827,8 +4612,7 @@ Returns statistics about the chain. Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4837,11 +4621,9 @@ Request } ``` - Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4867,19 +4649,17 @@ Response } ``` +RPC Module Subscription that CKB node will push new messages to subscribers, support with WebSocket or TCP. -### Module Subscription +RPC subscriptions require a full duplex connection. CKB offers such connections in the form of +TCP (enable with `rpc.tcp_listen_address` configuration option) and WebSocket (enable with +`rpc.ws_listen_address`). -RPC Module Subscription that CKB node will push new messages to subscribers. - -RPC subscriptions require a full duplex connection. CKB offers such connections in the form of TCP (enable with rpc.tcp_listen_address configuration option) and WebSocket (enable with rpc.ws_listen_address). - -##### Examples +###### Examples TCP RPC subscription: - -``` +```bash telnet localhost 18114 > {"id": 2, "jsonrpc": "2.0", "method": "subscribe", "params": ["new_tip_header"]} < {"jsonrpc":"2.0","result":"0x0","id":2} @@ -4892,11 +4672,9 @@ telnet localhost 18114 < {"jsonrpc":"2.0","result":true,"id":2} ``` - WebSocket RPC subscription: - -``` +```javascript let socket = new WebSocket("ws://localhost:28114") socket.onmessage = function(event) { @@ -4908,26 +4686,22 @@ socket.send(`{"id": 2, "jsonrpc": "2.0", "method": "subscribe", "params": ["new_ socket.send(`{"id": 2, "jsonrpc": "2.0", "method": "unsubscribe", "params": ["0x0"]}`) ``` - #### Method `subscribe` -* `subscribe(topic)` - * `topic`: `string` -* result: `string` - Subscribes to a topic. ###### Params -* `topic` - Subscription topic (enum: new_tip_header | new_tip_block | new_transaction | proposed_transaction | rejected_transaction) +* `topic` - Subscription topic (enum: new_tip_header | new_tip_block | new_transaction | proposed_transaction | rejected_transaction) ###### Returns -This RPC returns the subscription ID as the result. CKB node will push messages in the subscribed topics to the current RPC connection. The subscript ID is also attached as `params.subscription` in the push messages. +This RPC returns the subscription ID as the result. CKB node will push messages in the subscribed +topics to the current RPC connection. The subscript ID is also attached as +`params.subscription` in the push messages. Example push message: - -``` +```json+skip { "jsonrpc": "2.0", "method": "subscribe", @@ -4938,32 +4712,33 @@ Example push message: } ``` - -###### Topics +##### Topics ###### `new_tip_header` -Whenever there’s a block that is appended to the canonical chain, the CKB node will publish the block header to subscribers. +Whenever there's a block that is appended to the canonical chain, the CKB node will publish the +block header to subscribers. -The type of the `params.result` in the push message is [`HeaderView`](#type-headerview). +The type of the `params.result` in the push message is [`HeaderView`](../../ckb_jsonrpc_types/struct.HeaderView.html). ###### `new_tip_block` -Whenever there’s a block that is appended to the canonical chain, the CKB node will publish the whole block to subscribers. +Whenever there's a block that is appended to the canonical chain, the CKB node will publish the +whole block to subscribers. -The type of the `params.result` in the push message is [`BlockView`](#type-blockview). +The type of the `params.result` in the push message is [`BlockView`](../../ckb_jsonrpc_types/struct.BlockView.html). ###### `new_transaction` Subscribers will get notified when a new transaction is submitted to the pool. -The type of the `params.result` in the push message is [`PoolTransactionEntry`](#type-pooltransactionentry). +The type of the `params.result` in the push message is [`PoolTransactionEntry`](../../ckb_jsonrpc_types/struct.PoolTransactionEntry.html). ###### `proposed_transaction` Subscribers will get notified when an in-pool transaction is proposed by chain. -The type of the `params.result` in the push message is [`PoolTransactionEntry`](#type-pooltransactionentry). +The type of the `params.result` in the push message is [`PoolTransactionEntry`](../../ckb_jsonrpc_types/struct.PoolTransactionEntry.html). ###### `rejected_transaction` @@ -4973,16 +4748,14 @@ The type of the `params.result` in the push message is an array contain: The type of the `params.result` in the push message is a two-elements array, where -* the first item type is [`PoolTransactionEntry`](#type-pooltransactionentry), and - -* the second item type is [`PoolTransactionReject`](#type-pooltransactionreject). +- the first item type is [`PoolTransactionEntry`](../../ckb_jsonrpc_types/struct.PoolTransactionEntry.html), and +- the second item type is [`PoolTransactionReject`](../../ckb_jsonrpc_types/struct.PoolTransactionReject.html). ###### Examples Subscribe Request - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -4993,11 +4766,9 @@ Subscribe Request } ``` - Subscribe Response - -``` +```json { "id": 42, "jsonrpc": "2.0", @@ -5005,11 +4776,21 @@ Subscribe Response } ``` +#### Method `unsubscribe` +* `unsubscribe(id)` + * `id`: `string` +* result: `boolean` -Unsubscribe Request +Unsubscribes from a subscribed topic. +###### Params +* `id` - Subscription ID -``` +###### Examples + +Unsubscribe Request + +```json { "id": 42, "jsonrpc": "2.0", @@ -5020,2348 +4801,1649 @@ Unsubscribe Request } ``` - Unsubscribe Response - -``` +```json { - "id": 42, - "jsonrpc": "2.0", - "result": true + "id": 42, + "jsonrpc": "2.0", + "result": true } ``` -## RPC Errors - -CKB RPC error codes. +## RPC Types -CKB RPC follows the JSON RPC specification about the [error object](https://www.jsonrpc.org/specification#error_object). +### Type `Alert` +An alert is a message about critical problems to be broadcast to all nodes via the p2p network. -Besides the pre-defined errors, all CKB defined errors are listed here. +###### Examples -Here is a reference to the pre-defined errors: +An example in JSON +```json + { + "id": "0x1", + "cancel": "0x0", + "min_version": "0.1.0", + "max_version": "1.0.0", + "priority": "0x1", + "message": "An example alert message!", + "notice_until": "0x24bcca57c00", + "signatures": [ + "0xbd07059aa9a3d057da294c2c4d96fa1e67eeb089837c87b523f124239e18e9fc7d11bb95b720478f7f937d073517d0e4eb9a91d12da5c88a05f750362f4c214dd0", + "0x0242ef40bb64fe3189284de91f981b17f4d740c5e24a3fc9b70059db6aa1d198a2e76da4f84ab37549880d116860976e0cf81cd039563c452412076ebffa2e4453" + ] + } +``` -| code | message | meaning | -| --- |--- |--- | -| -32700 | Parse error | Invalid JSON was received by the server. | -| -32600 | Invalid Request | The JSON sent is not a valid Request object. | -| -32601 | Method not found | The method does not exist / is not available. | -| -32602 | Invalid params | Invalid method parameter(s). | -| -32603 | Internal error | Internal JSON-RPC error. | -| -32000 to -32099 | Server error | Reserved for implementation-defined server-errors. | +#### Fields: +* `cancel`: [`AlertId`](#type-alertid) - Cancel a previous sent alert. +* `id`: [`AlertId`](#type-alertid) - The identifier of the alert. Clients use id to filter duplicated alerts. -CKB application-defined errors follow some patterns to assign the codes: +* `message`: `string` - Alert message. -* -1 ~ -999 are general errors +* `notice_until`: [`Uint64`](#type-uint64) - The alert is expired after this timestamp. -* -1000 ~ -2999 are module-specific errors. Each module generally gets 100 reserved error codes. +* `priority`: [`AlertId`](#type-alertid) - Alerts are sorted by priority, highest first. -Unless otherwise noted, all the errors return optional detailed information as `string` in the error object `data` field. +* `signatures`: `Array<` [`JsonBytes`](#type-jsonbytes) `>` - The list of required signatures. -### Error `CKBInternalError` +### Type `AlertId` +`AlertId` is `uint32` -(-1): CKB internal errors are considered to never happen or only happen when the system resources are exhausted. +### Type `AlertMessage` +An alert sent by RPC `send_alert`. -### Error `Deprecated` +#### Fields: +* `id`: [`AlertId`](#type-alertid) - The unique alert ID. -(-2): The CKB method has been deprecated and disabled. +* `message`: `string` - Alert message. -Set `rpc.enable_deprecated_rpc` to `true` in the config file to enable all deprecated methods. +* `notice_until`: [`Uint64`](#type-uint64) - The alert is expired after this timestamp. -### Error `Invalid` +* `priority`: [`AlertId`](#type-alertid) - Alerts are sorted by priority, highest first. -(-3): Error code -3 is no longer used. +### Type `AncestorsScoreSortKey` +A struct as a sorted key for tx-pool -Before v0.35.0, CKB returns all RPC errors using the error code -3. CKB no longer uses -3 since v0.35.0. +#### Fields: +* `ancestors_fee`: [`Uint64`](#type-uint64) - Ancestors fee -### Error `RPCModuleIsDisabled` +* `ancestors_weight`: [`Uint64`](#type-uint64) - Ancestors weight -(-4): The RPC method is not enabled. +* `fee`: [`Uint64`](#type-uint64) - Fee -CKB groups RPC methods into modules, and a method is enabled only when the module is explicitly enabled in the config file. +* `weight`: [`Uint64`](#type-uint64) - Weight -### Error `DaoError` +### Type `BannedAddr` +A banned P2P address. -(-5): DAO related errors. +#### Fields: +* `address`: `string` - The P2P address. -### Error `IntegerOverflow` + Example: "/ip4/192.168.0.2/tcp/8112/p2p/QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS" -(-6): Integer operation overflow. +* `ban_reason`: `string` - The reason. -### Error `ConfigError` +* `ban_until`: [`Uint64`](#type-uint64) - The address is banned until this time. -(-7): The error is caused by a config file option. +* `created_at`: [`Uint64`](#type-uint64) - When this address is banned. -Users have to edit the config file to fix the error. +### Type `Block` +The JSON view of a Block used as a parameter in the RPC. -### Error `P2PFailedToBroadcast` +#### Fields: +* `header`: [`Header`](#type-header) - The block header. -(-101): The CKB local node failed to broadcast a message to its peers. +* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - The proposal IDs in the block body. -### Error `DatabaseError` +* `transactions`: `Array<` [`Transaction`](#type-transaction) `>` - The transactions in the block body. -(-200): Internal database error. +* `uncles`: `Array<` [`UncleBlock`](#type-uncleblock) `>` - The uncles blocks in the block body. -The CKB node persists data to the database. This is the error from the underlying database module. +### Type `BlockEconomicState` +Block Economic State. -### Error `ChainIndexIsInconsistent` +It includes the rewards details and when it is finalized. -(-201): The chain index is inconsistent. +#### Fields: +* `finalized_at`: [`H256`](#type-h256) - The block hash of the block which creates the rewards as cells in its cellbase transaction. -An example of an inconsistent index is that the chain index says a block hash is in the chain but the block cannot be read from the database. +* `issuance`: [`BlockIssuance`](#type-blockissuance) - Block base rewards. -This is a fatal error usually due to a serious bug. Please back up the data directory and re-sync the chain from scratch. +* `miner_reward`: [`MinerReward`](#type-minerreward) - Block rewards for miners. -### Error `DatabaseIsCorrupt` +* `txs_fee`: [`Uint64`](#type-uint64) - The total fees of all transactions committed in the block. -(-202): The underlying database is corrupt. +### Type `BlockFilter` +Block filter data and hash. -This is a fatal error usually caused by the underlying database used by CKB. Please back up the data directory and re-sync the chain from scratch. +#### Fields: +* `data`: [`JsonBytes`](#type-jsonbytes) - The the hex-encoded filter data of the block -### Error `TransactionFailedToResolve` +* `hash`: [`Byte32`](#type-byte32) - The filter hash, blake2b hash of the parent block filter hash and the filter data, blake2b(parent_block_filter_hash | current_block_filter_data) -(-301): Failed to resolve the referenced cells and headers used in the transaction, as inputs or dependencies. +### Type `BlockIssuance` +Block base rewards. -### Error `TransactionFailedToVerify` +#### Fields: +* `primary`: [`Uint64`](#type-uint64) - The primary base rewards. -(-302): Failed to verify the transaction. +* `secondary`: [`Uint64`](#type-uint64) - The secondary base rewards. -### Error `AlertFailedToVerifySignatures` +### Type `BlockResponse` +The wrapper represent response of `get_block` | `get_block_by_number`, return a Block with cycles. -(-1000): Some signatures in the submit alert are invalid. +### Type `BlockTemplate` +A block template for miners. -### Error `PoolRejectedTransactionByOutputsValidator` +Miners optional pick transactions and then assemble the final block. -(-1102): The transaction is rejected by the outputs validator specified by the RPC parameter. +#### Fields: +* `bytes_limit`: [`Uint64`](#type-uint64) - The block serialized size limit. -### Error `PoolRejectedTransactionByIllTransactionChecker` + Miners must keep the block size below this limit, otherwise, the CKB node will reject the block submission. -(-1103): Pool rejects some transactions which seem contain invalid VM instructions. See the issue link in the error message for details. + It is guaranteed that the block does not exceed the limit if miners do not add new transaction commitments. -### Error `PoolRejectedTransactionByMinFeeRate` +* `cellbase`: [`CellbaseTemplate`](#type-cellbasetemplate) - Provided cellbase transaction template. -(-1104): The transaction fee rate must be greater than or equal to the config option `tx_pool.min_fee_rate` + Miners must use it as the cellbase transaction without changes in the assembled block. -The fee rate is calculated as: +* `compact_target`: [`AlertId`](#type-alertid) - The compacted difficulty target for the new block. + Miners must use it unchanged in the assembled block. -``` -fee / (1000 * tx_serialization_size_in_block_in_bytes) -``` +* `current_time`: [`Uint64`](#type-uint64) - The timestamp for the new block. + CKB node guarantees that this timestamp is larger than the median of the previous 37 blocks. -### Error `PoolRejectedTransactionByMaxAncestorsCountLimit` + Miners can increase it to the current time. It is not recommended to decrease it, since it may violate the median block timestamp consensus rule. -(-1105): The in-pool ancestors count must be less than or equal to the config option `tx_pool.max_ancestors_count` +* `cycles_limit`: [`Uint64`](#type-uint64) - The cycles limit. -Pool rejects a large package of chained transactions to avoid certain kinds of DoS attacks. + Miners must keep the total cycles below this limit, otherwise, the CKB node will reject the block submission. -### Error `PoolIsFull` + It is guaranteed that the block does not exceed the limit if miners do not add new transactions to the block. -(-1106): The transaction is rejected because the pool has reached its limit. +* `dao`: [`Byte32`](#type-byte32) - Reference DAO field. -### Error `PoolRejectedDuplicatedTransaction` + This field is only valid when miners use all and only use the provided transactions in the template. Two fields must be updated when miners want to select transactions: -(-1107): The transaction is already in the pool. + * `S_i`, bytes 16 to 23 + * `U_i`, bytes 24 to 31 -### Error `PoolRejectedMalformedTransaction` + See RFC [Deposit and Withdraw in Nervos DAO](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0023-dao-deposit-withdraw/0023-dao-deposit-withdraw.md#calculation). -(-1108): The transaction is rejected because it does not make sense in the context. +* `epoch`: [`Uint64`](#type-uint64) - The epoch progress information for the new block. -For example, a cellbase transaction is not allowed in `send_transaction` RPC. + Miners must use it unchanged in the assembled block. -### Error `TransactionExpired` +* `number`: [`Uint64`](#type-uint64) - The block number for the new block. -(-1109): The transaction is expired from tx-pool after `expiry_hours`. + Miners must use it unchanged in the assembled block. -### Error `PoolRejectedTransactionBySizeLimit` +* `parent_hash`: [`H256`](#type-h256) - The parent block hash of the new block. -(-1110): The transaction exceeded maximum size limit. + Miners must use it unchanged in the assembled block. -### Error `PoolRejectedRBF` +* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - Provided proposal ids list of transactions for the new block. -(-1111): The transaction is rejected for RBF checking. +* `transactions`: `Array<` [`TransactionTemplate`](#type-transactiontemplate) `>` - Provided valid transactions which can be committed in the new block. -### Error `Indexer` + Miners must include the transactions marked as `required` in the assembled new block. -(-1200): The indexer error. +* `uncles`: `Array<` [`UncleTemplate`](#type-uncletemplate) `>` - Provided valid uncle blocks candidates for the new block. + Miners must include the uncles marked as `required` in the assembled new block. -## RPC Types +* `uncles_count_limit`: [`Uint64`](#type-uint64) - The uncle count limit. -### Type `Alert` + Miners must keep the uncles count below this limit, otherwise, the CKB node will reject the block submission. -An alert is a message about critical problems to be broadcast to all nodes via the p2p network. +* `version`: [`AlertId`](#type-alertid) - Block version. -##### Examples + Miners must use it unchanged in the assembled block. -An example in JSON +* `work_id`: [`Uint64`](#type-uint64) - Work ID. The miner must submit the new assembled and resolved block using the same work ID. +### Type `BlockView` +The JSON view of a Block including header and body. -``` -{ - "id": "0x1", - "cancel": "0x0", - "min_version": "0.1.0", - "max_version": "1.0.0", - "priority": "0x1", - "message": "An example alert message!", - "notice_until": "0x24bcca57c00", - "signatures": [ - "0xbd07059aa9a3d057da294c2c4d96fa1e67eeb089837c87b523f124239e18e9fc7d11bb95b720478f7f937d073517d0e4eb9a91d12da5c88a05f750362f4c214dd0", - "0x0242ef40bb64fe3189284de91f981b17f4d740c5e24a3fc9b70059db6aa1d198a2e76da4f84ab37549880d116860976e0cf81cd039563c452412076ebffa2e4453" - ] -} -``` +#### Fields: +* `header`: [`HeaderView`](#type-headerview) - The block header. +* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - The proposal IDs in the block body. -#### Fields +* `transactions`: `Array<` [`TransactionView`](#type-transactionview) `>` - The transactions in the block body. -`Alert` is a JSON object with the following fields. +* `uncles`: `Array<` [`UncleBlockView`](#type-uncleblockview) `>` - The uncles blocks in the block body. -* `id`: [`AlertId`](#type-alertid) - The identifier of the alert. Clients use id to filter duplicated alerts. +### Type `BlockWithCyclesResponse` +BlockResponse with cycles format wrapper -* `cancel`: [`AlertId`](#type-alertid) - Cancel a previous sent alert. +#### Fields: +* `block`: [`Either_for_BlockView_and_JsonBytes`](#type-either_for_blockview_and_jsonbytes) - The block structure -* `min_version`: `string` `|` `null` - Optionally set the minimal version of the target clients. +### Type `Buried` +Represent soft fork deployments where the activation epoch is hard-coded into the client implementation - See [Semantic Version](https://semver.org/) about how to specify a version. +#### Fields: +* `active`: `boolean` - Whether the rules are active -* `max_version`: `string` `|` `null` - Optionally set the maximal version of the target clients. +* `epoch`: [`Uint64`](#type-uint64) - The first epoch which the rules will be enforced - See [Semantic Version](https://semver.org/) about how to specify a version. +* `status`: [`SoftForkStatus`](#type-softforkstatus) - SoftFork status -* `priority`: [`AlertPriority`](#type-alertpriority) - Alerts are sorted by priority, highest first. +### Type `Byte32` -* `notice_until`: [`Timestamp`](#type-timestamp) - The alert is expired after this timestamp. -* `message`: `string` - Alert message. +### Type `CellData` +The cell data content and hash. -* `signatures`: `Array<` [`JsonBytes`](#type-jsonbytes) `>` - The list of required signatures. +###### Examples +```json + { + "content": "0x7f454c460201010000000000000000000200f3000100000078000100000000004000000000000000980000000000000005000000400038000100400003000200010000000500000000000000000000000000010000000000000001000000000082000000000000008200000000000000001000000000000001459308d00573000000002e7368737472746162002e74657874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000010000000600000000000000780001000000000078000000000000000a0000000000000000000000000000000200000000000000000000000000000001000000030000000000000000000000000000000000000082000000000000001100000000000000000000000000000001000000000000000000000000000000", + "hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5" + } +``` -### Type `AlertId` +#### Fields: +* `content`: [`JsonBytes`](#type-jsonbytes) - Cell content. -The alert identifier that is used to filter duplicated alerts. +* `hash`: [`H256`](#type-h256) - Cell content hash. -This is a 32-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint32](#type-uint32). +### Type `CellDep` +The cell dependency of a transaction. -### Type `AlertMessage` +###### Examples -An alert sent by RPC `send_alert`. +```json + { + "dep_type": "code", + "out_point": { + "index": "0x0", + "tx_hash": "0xa4037a893eb48e18ed4ef61034ce26eba9c585f15c9cee102ae58505565eccc3" + } + } +``` -#### Fields +#### Fields: +* `dep_type`: [`DepType`](#type-deptype) - Dependency type. -`AlertMessage` is a JSON object with the following fields. +* `out_point`: [`OutPoint`](#type-outpoint) - Reference to the cell. -* `id`: [`AlertId`](#type-alertid) - The unique alert ID. +### Type `CellInfo` +The JSON view of a cell combining the fields in cell output and cell data. -* `priority`: [`AlertPriority`](#type-alertpriority) - Alerts are sorted by priority, highest first. +###### Examples -* `notice_until`: [`Timestamp`](#type-timestamp) - The alert is expired after this timestamp. +```json + { + "data": { + "content": "0x7f454c460201010000000000000000000200f3000100000078000100000000004000000000000000980000000000000005000000400038000100400003000200010000000500000000000000000000000000010000000000000001000000000082000000000000008200000000000000001000000000000001459308d00573000000002e7368737472746162002e74657874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000010000000600000000000000780001000000000078000000000000000a0000000000000000000000000000000200000000000000000000000000000001000000030000000000000000000000000000000000000082000000000000001100000000000000000000000000000001000000000000000000000000000000", + "hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5" + }, + "output": { + "capacity": "0x802665800", + "lock": { + "args": "0x", + "code_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "hash_type": "data" + }, + "type": null + } + } +``` -* `message`: `string` - Alert message. +#### Fields: +* `output`: [`CellOutput`](#type-celloutput) - Cell fields appears in the transaction `outputs` array. +### Type `CellInput` +The input cell of a transaction. -### Type `AlertPriority` +###### Examples -Alerts are sorted by priority. Greater integers mean higher priorities. +```json + { + "previous_output": { + "index": "0x0", + "tx_hash": "0x365698b50ca0da75dca2c87f9e7b563811d3b5813736b8cc62cc3b106faceb17" + }, + "since": "0x0" + } +``` -This is a 32-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint32](#type-uint32). +#### Fields: +* `previous_output`: [`OutPoint`](#type-outpoint) - Reference to the input cell. -### Type `AncestorsScoreSortKey` +* `since`: [`Uint64`](#type-uint64) - Restrict when the transaction can be committed into the chain. -A struct as a sorted key for tx-pool + See the RFC [Transaction valid since](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0017-tx-valid-since/0017-tx-valid-since.md). -#### Fields +### Type `CellOutput` +The fields of an output cell except the cell data. -`AncestorsScoreSortKey` is a JSON object with the following fields. +###### Examples -* `fee`: [`Uint64`](#type-uint64) - Fee +```json + { + "capacity": "0x2540be400", + "lock": { + "code_hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5", + "hash_type": "data", + "args": "0x" + }, + "type": null + } +``` -* `weight`: [`Uint64`](#type-uint64) - Weight +#### Fields: +* `capacity`: [`Uint64`](#type-uint64) - The cell capacity. -* `ancestors_fee`: [`Uint64`](#type-uint64) - Ancestors fee + The capacity of a cell is the value of the cell in Shannons. It is also the upper limit of the cell occupied storage size where every 100,000,000 Shannons give 1-byte storage. -* `ancestors_weight`: [`Uint64`](#type-uint64) - Ancestors weight +* `lock`: [`Script`](#type-script) - The lock script. +### Type `CellWithStatus` +The JSON view of a cell with its status information. -### Type `BannedAddr` +###### Examples -A banned P2P address. +```json + { + "cell": { + "data": { + "content": "0x7f454c460201010000000000000000000200f3000100000078000100000000004000000000000000980000000000000005000000400038000100400003000200010000000500000000000000000000000000010000000000000001000000000082000000000000008200000000000000001000000000000001459308d00573000000002e7368737472746162002e74657874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000010000000600000000000000780001000000000078000000000000000a0000000000000000000000000000000200000000000000000000000000000001000000030000000000000000000000000000000000000082000000000000001100000000000000000000000000000001000000000000000000000000000000", + "hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5" + }, + "output": { + "capacity": "0x802665800", + "lock": { + "args": "0x", + "code_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "hash_type": "data" + }, + "type": null + } + }, + "status": "live" + } +``` -#### Fields +``` + { + "cell": null, + "status": "unknown" + } +``` -`BannedAddr` is a JSON object with the following fields. +#### Fields: +* `status`: `string` - Status of the cell. -* `address`: `string` - The P2P address. + Allowed values: "live", "dead", "unknown". - Example: “/ip4/192.168.0.2/tcp/8112/p2p/QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS” + * `live` - The transaction creating this cell is in the chain, and there are no transactions found in the chain that uses this cell as an input. + * `dead` - (**Deprecated**: the dead status will be removed since 0.36.0, please do not rely on the logic that differentiates dead and unknown cells.) The transaction creating this cell is in the chain, and a transaction is found in the chain which uses this cell as an input. + * `unknown` - CKB does not know the status of the cell. Either the transaction creating this cell is not in the chain yet, or it is no longer live. -* `ban_until`: [`Timestamp`](#type-timestamp) - The address is banned until this time. +### Type `CellbaseTemplate` +The cellbase transaction template of the new block for miners. -* `ban_reason`: `string` - The reason. +#### Fields: +* `data`: [`Transaction`](#type-transaction) - The cellbase transaction. -* `created_at`: [`Timestamp`](#type-timestamp) - When this address is banned. +* `hash`: [`H256`](#type-h256) - The cellbase transaction hash. +### Type `ChainInfo` +Chain information. -### Type `Block` +#### Fields: +* `alerts`: `Array<` [`AlertMessage`](#type-alertmessage) `>` - Active alerts stored in the local node. -The JSON view of a Block used as a parameter in the RPC. +* `chain`: `string` - The network name. -#### Fields + Examples: -`Block` is a JSON object with the following fields. + * "ckb" - Mirana the mainnet. + * "ckb_testnet" - Pudge the testnet. -* `header`: [`Header`](#type-header) - The block header. +* `difficulty`: `string` - Current difficulty. -* `uncles`: `Array<` [`UncleBlock`](#type-uncleblock) `>` - The uncles blocks in the block body. + Decoded from the epoch `compact_target`. -* `transactions`: `Array<` [`Transaction`](#type-transaction) `>` - The transactions in the block body. +* `epoch`: [`Uint64`](#type-uint64) - The epoch information of tip block in the chain. -* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - The proposal IDs in the block body. +* `is_initial_block_download`: `boolean` - Whether the local node is in IBD, Initial Block Download. -* `extension`: [`JsonBytes`](#type-jsonbytes) `|` `null` - The extension in the block body. + When a node starts and its chain tip timestamp is far behind the wall clock, it will enter the IBD until it catches up the synchronization. - This is a field introduced in [CKB RFC 0031](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0031-variable-length-header-field/0031-variable-length-header-field.md). Since the activation of [CKB RFC 0044](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0044-ckb-light-client/0044-ckb-light-client.md), this field is at least 32 bytes, and at most 96 bytes. The consensus rule of first 32 bytes is defined in the RFC 0044. + During IBD, the local node only synchronizes the chain with one selected remote node and stops responding the most P2P requests. +* `median_time`: [`Uint64`](#type-uint64) - The median time of the last 37 blocks, including the tip block. -### Type `BlockEconomicState` +### Type `Consensus` +Consensus defines various parameters that influence chain consensus -Block Economic State. +#### Fields: +* `block_version`: [`AlertId`](#type-alertid) - The block version number supported -It includes the rewards details and when it is finalized. +* `cellbase_maturity`: [`Uint64`](#type-uint64) - The Cellbase maturity -#### Fields +* `dao_type_hash`: [`H256`](#type-h256) - The dao type hash -`BlockEconomicState` is a JSON object with the following fields. +* `epoch_duration_target`: [`Uint64`](#type-uint64) - The expected epoch_duration -* `issuance`: [`BlockIssuance`](#type-blockissuance) - Block base rewards. +* `genesis_hash`: [`H256`](#type-h256) - The genesis block hash -* `miner_reward`: [`MinerReward`](#type-minerreward) - Block rewards for miners. +* `hardfork_features`: `Array<` [`HardForkFeature`](#type-hardforkfeature) `>` - Hardfork features -* `txs_fee`: [`Capacity`](#type-capacity) - The total fees of all transactions committed in the block. +* `id`: `string` - Names the network. -* `finalized_at`: [`H256`](#type-h256) - The block hash of the block which creates the rewards as cells in its cellbase transaction. +* `initial_primary_epoch_reward`: [`Uint64`](#type-uint64) - The initial primary_epoch_reward +* `max_block_bytes`: [`Uint64`](#type-uint64) - Maximum number of bytes to use for the entire block -### Type `BlockFilter` +* `max_block_cycles`: [`Uint64`](#type-uint64) - Maximum cycles that all the scripts in all the commit transactions can take -Block filter data and hash. +* `max_block_proposals_limit`: [`Uint64`](#type-uint64) - The Limit to the number of proposals per block -#### Fields +* `max_uncles_num`: [`Uint64`](#type-uint64) - The maximum amount of uncles allowed for a block -`BlockFilter` is a JSON object with the following fields. +* `median_time_block_count`: [`Uint64`](#type-uint64) - This parameter indicates the count of past blocks used in the median time calculation -* `data`: [`JsonBytes`](#type-jsonbytes) - The the hex-encoded filter data of the block +* `orphan_rate_target`: `string` - The expected orphan_rate -* `hash`: [`Byte32`](#type-byte32) - The filter hash, blake2b hash of the parent block filter hash and the filter data, blake2b(parent_block_filter_hash | current_block_filter_data) +* `permanent_difficulty_in_dummy`: `boolean` - Keep difficulty be permanent if the pow is dummy +* `primary_epoch_reward_halving_interval`: [`Uint64`](#type-uint64) - Primary reward is cut in half every halving_interval epoch -### Type `BlockIssuance` +* `proposer_reward_ratio`: `string` - The two-step-transaction-confirmation proposer reward ratio -Block base rewards. +* `secondary_epoch_reward`: [`Uint64`](#type-uint64) - The secondary primary_epoch_reward -#### Fields +* `softforks`: `object` - Softforks -`BlockIssuance` is a JSON object with the following fields. +* `tx_proposal_window`: [`ProposalWindow`](#type-proposalwindow) - The two-step-transaction-confirmation proposal window -* `primary`: [`Capacity`](#type-capacity) - The primary base rewards. +* `tx_version`: [`AlertId`](#type-alertid) - The tx version number supported -* `secondary`: [`Capacity`](#type-capacity) - The secondary base rewards. +* `type_id_code_hash`: [`H256`](#type-h256) - The "TYPE_ID" in hex +### Type `DaoWithdrawingCalculationKind` +An enum to represent the two kinds of dao withdrawal amount calculation option. `DaoWithdrawingCalculationKind` is equivalent to [`H256`] `|` [`OutPoint`]. -### Type `BlockNumber` +[`H256`]: struct.H256.html +[`OutPoint`]: struct.OutPoint.html -Consecutive block number starting from 0. +### Type `DepType` +The dep cell type. Allowed values: "code" and "dep_group". -This is a 64-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint64](#type-uint64). +### Type `Deployment` +RFC0043 deployment params -### Type `BlockResponse` +#### Fields: +* `bit`: `integer` - Determines which bit in the `version` field of the block is to be used to signal the softfork lock-in and activation. It is chosen from the set {0,1,2,...,28}. -The wrapper represent response of `get_block` | `get_block_by_number`, return a Block with cycles. +* `min_activation_epoch`: [`Uint64`](#type-uint64) - Specifies the epoch at which the softfork is allowed to become active. -`BlockResponse` is equivalent to `"regular" | "with_cycles"`. +* `period`: [`Uint64`](#type-uint64) - Specifies length of epochs of the signalling period. -* The block response regular format +* `start`: [`Uint64`](#type-uint64) - Specifies the first epoch in which the bit gains meaning. - [`BlockView`](#type-blockview) | [`SerializedBlock`](#type-serializedblock) - The block structure +* `threshold`: [`Ratio`](#type-ratio) - Specifies the minimum ratio of block per `period`, which indicate the locked_in of the softfork during the `period`. -* The block with cycles response format +* `timeout`: [`Uint64`](#type-uint64) - Specifies an epoch at which the miner signaling ends. Once this epoch has been reached, if the softfork has not yet locked_in (excluding this epoch block's bit state), the deployment is considered failed on all descendants of the block. - A JSON object with the following fields: +### Type `DeploymentInfo` +An object containing various state info regarding deployments of consensus changes - * `block`: [`BlockView`](#type-blockview) | [`SerializedBlock`](#type-serializedblock) - The block structure +#### Fields: +* `bit`: `integer` - determines which bit in the `version` field of the block is to be used to signal the softfork lock-in and activation. It is chosen from the set {0,1,2,...,28}. - * `cycles`: `Array<` [`Cycle`](#type-cycle) `>` `|` `null` - The block transactions consumed cycles. +* `min_activation_epoch`: [`Uint64`](#type-uint64) - specifies the epoch at which the softfork is allowed to become active. +* `period`: [`Uint64`](#type-uint64) - the length in epochs of the signalling period +* `since`: [`Uint64`](#type-uint64) - The first epoch which the current state applies -### Type `BlockTemplate` +* `start`: [`Uint64`](#type-uint64) - specifies the first epoch in which the bit gains meaning. -A block template for miners. +* `state`: [`DeploymentState`](#type-deploymentstate) - With each epoch and softfork, we associate a deployment state. The possible states are: -Miners optional pick transactions and then assemble the final block. + * `DEFINED` is the first state that each softfork starts. The blocks of 0 epoch is by definition in this state for each deployment. + * `STARTED` for all blocks reach or past the start_epoch. + * `LOCKED_IN` for one period after the first period with STARTED blocks of which at least threshold has the associated bit set in version. + * `ACTIVE` for all blocks after the LOCKED_IN period. + * `FAILED` for all blocks after the timeout_epoch, if LOCKED_IN was not reached. -#### Fields +* `threshold`: [`Ratio`](#type-ratio) - the ratio of blocks with the version bit set required to activate the feature -`BlockTemplate` is a JSON object with the following fields. +* `timeout`: [`Uint64`](#type-uint64) - specifies an epoch at which the miner signaling ends. Once this epoch has been reached, if the softfork has not yet locked_in (excluding this epoch block's bit state), the deployment is considered failed on all descendants of the block. -* `version`: [`Version`](#type-version) - Block version. +### Type `DeploymentState` +The possible softfork deployment state - Miners must use it unchanged in the assembled block. - -* `compact_target`: [`Uint32`](#type-uint32) - The compacted difficulty target for the new block. +### Type `DeploymentsInfo` +Chain information. - Miners must use it unchanged in the assembled block. +#### Fields: +* `deployments`: `object` - deployments info -* `current_time`: [`Timestamp`](#type-timestamp) - The timestamp for the new block. +* `epoch`: [`Uint64`](#type-uint64) - requested block epoch - CKB node guarantees that this timestamp is larger than the median of the previous 37 blocks. +* `hash`: [`H256`](#type-h256) - requested block hash - Miners can increase it to the current time. It is not recommended to decrease it, since it may violate the median block timestamp consensus rule. +### Type `Either_for_BlockView_and_JsonBytes` +The enum `Either` with variants `Left` and `Right` is a general purpose sum type with two cases. -* `number`: [`BlockNumber`](#type-blocknumber) - The block number for the new block. +### Type `Either_for_HeaderView_and_JsonBytes` +The enum `Either` with variants `Left` and `Right` is a general purpose sum type with two cases. - Miners must use it unchanged in the assembled block. +### Type `Either_for_TransactionView_and_JsonBytes` +The enum `Either` with variants `Left` and `Right` is a general purpose sum type with two cases. -* `epoch`: [`EpochNumberWithFraction`](#type-epochnumberwithfraction) - The epoch progress information for the new block. +### Type `EpochView` +JSON view of an epoch. - Miners must use it unchanged in the assembled block. +CKB adjusts difficulty based on epochs. -* `parent_hash`: [`H256`](#type-h256) - The parent block hash of the new block. +###### Examples - Miners must use it unchanged in the assembled block. +```json + { + "compact_target": "0x1e083126", + "length": "0x708", + "number": "0x1", + "start_number": "0x3e8" + } +``` -* `cycles_limit`: [`Cycle`](#type-cycle) - The cycles limit. +#### Fields: +* `compact_target`: [`AlertId`](#type-alertid) - The difficulty target for any block in this epoch. - Miners must keep the total cycles below this limit, otherwise, the CKB node will reject the block submission. +* `length`: [`Uint64`](#type-uint64) - The number of blocks in this epoch. - It is guaranteed that the block does not exceed the limit if miners do not add new transactions to the block. +* `number`: [`Uint64`](#type-uint64) - Consecutive epoch number starting from 0. -* `bytes_limit`: [`Uint64`](#type-uint64) - The block serialized size limit. +* `start_number`: [`Uint64`](#type-uint64) - The block number of the first block in the epoch. - Miners must keep the block size below this limit, otherwise, the CKB node will reject the block submission. + It also equals the total count of blocks in all the epochs which epoch number is less than this epoch. - It is guaranteed that the block does not exceed the limit if miners do not add new transaction commitments. +### Type `EstimateCycles` +Response result of the RPC method `estimate_cycles`. -* `uncles_count_limit`: [`Uint64`](#type-uint64) - The uncle count limit. +#### Fields: +* `cycles`: [`Uint64`](#type-uint64) - The count of cycles that the VM has consumed to verify this transaction. - Miners must keep the uncles count below this limit, otherwise, the CKB node will reject the block submission. +### Type `ExtraLoggerConfig` +Runtime logger config for extra loggers. -* `uncles`: `Array<` [`UncleTemplate`](#type-uncletemplate) `>` - Provided valid uncle blocks candidates for the new block. +#### Fields: +* `filter`: `string` - Sets log levels for different modules. - Miners must include the uncles marked as `required` in the assembled new block. + **Examples** -* `transactions`: `Array<` [`TransactionTemplate`](#type-transactiontemplate) `>` - Provided valid transactions which can be committed in the new block. + Set the log level to info for all modules - Miners must include the transactions marked as `required` in the assembled new block. + ```text + info + ``` -* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - Provided proposal ids list of transactions for the new block. + Set the log level to debug for listed modules and info for other modules. -* `cellbase`: [`CellbaseTemplate`](#type-cellbasetemplate) - Provided cellbase transaction template. + ```text + info,ckb-rpc=debug,ckb-sync=debug,ckb-relay=debug,ckb-tx-pool=debug,ckb-network=debug + ``` - Miners must use it as the cellbase transaction without changes in the assembled block. +### Type `FeeRateStatistics` +The fee_rate statistics information, includes mean and median, unit: shannons per kilo-weight -* `work_id`: [`Uint64`](#type-uint64) - Work ID. The miner must submit the new assembled and resolved block using the same work ID. +#### Fields: +* `mean`: [`Uint64`](#type-uint64) - mean -* `dao`: [`Byte32`](#type-byte32) - Reference DAO field. +* `median`: [`Uint64`](#type-uint64) - median - This field is only valid when miners use all and only use the provided transactions in the template. Two fields must be updated when miners want to select transactions: +### Type `H256` +The 32-byte fixed-length binary data. - * `S_i`, bytes 16 to 23 +The name comes from the number of bits in the data. - * `U_i`, bytes 24 to 31 +In JSONRPC, it is encoded as a 0x-prefixed hex string. - See RFC [Deposit and Withdraw in Nervos DAO](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0023-dao-deposit-withdraw/0023-dao-deposit-withdraw.md#calculation). +### Type `HardForkFeature` +The information about one hardfork feature. -* `extension`: [`JsonBytes`](#type-jsonbytes) `|` `null` - The extension for the new block. +#### Fields: +* `rfc`: `string` - The related RFC ID. - This is a field introduced in [CKB RFC 0031](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0031-variable-length-header-field/0031-variable-length-header-field.md). Since the activation of [CKB RFC 0044](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0044-ckb-light-client/0044-ckb-light-client.md), this field is at least 32 bytes, and at most 96 bytes. The consensus rule of first 32 bytes is defined in the RFC 0044. +### Type `Header` +The block header. +Refer to RFC [CKB Block Structure](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0027-block-structure/0027-block-structure.md). -### Type `BlockView` +#### Fields: +* `compact_target`: [`AlertId`](#type-alertid) - The block difficulty target. -The JSON view of a Block including header and body. + It can be converted to a 256-bit target. Miners must ensure the Eaglesong of the header is within the target. -#### Fields +* `dao`: [`Byte32`](#type-byte32) - DAO fields. -`BlockView` is a JSON object with the following fields. + See RFC [Deposit and Withdraw in Nervos DAO](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0023-dao-deposit-withdraw/0023-dao-deposit-withdraw.md#calculation). -* `header`: [`HeaderView`](#type-headerview) - The block header. +* `epoch`: [`Uint64`](#type-uint64) - The epoch information of this block. -* `uncles`: `Array<` [`UncleBlockView`](#type-uncleblockview) `>` - The uncles blocks in the block body. + See `EpochNumberWithFraction` for details. -* `transactions`: `Array<` [`TransactionView`](#type-transactionview) `>` - The transactions in the block body. +* `extra_hash`: [`H256`](#type-h256) - The hash on `uncles` and extension in the block body. -* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - The proposal IDs in the block body. + The uncles hash is all zeros when `uncles` is empty, or the hash on all the uncle header hashes concatenated together. The extension hash is the hash of the extension. The extra hash is the hash on uncles hash and extension hash concatenated together. -* `extension`: [`JsonBytes`](#type-jsonbytes) `|` `null` - The extension in the block body. + **Notice** - This is a field introduced in [CKB RFC 0031](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0031-variable-length-header-field/0031-variable-length-header-field.md). Since the activation of [CKB RFC 0044](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0044-ckb-light-client/0044-ckb-light-client.md), this field is at least 32 bytes, and at most 96 bytes. The consensus rule of first 32 bytes is defined in the RFC 0044. + This field is renamed from `uncles_hash` since 0.100.0. More details can be found in [CKB RFC 0031]. + [CKB RFC 0031]: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0031-variable-length-header-field/0031-variable-length-header-field.md -### Type `Byte32` +* `nonce`: [`Uint128`](#type-uint128) - Miner can modify this field to find a proper value such that the Eaglesong of the header is within the target encoded from `compact_target`. -The fixed-length 32 bytes binary encoded as a 0x-prefixed hex string in JSON. +* `number`: [`Uint64`](#type-uint64) - The consecutive block number starting from 0. -### Type `Capacity` +* `parent_hash`: [`H256`](#type-h256) - The header hash of the parent block. -The capacity of a cell is the value of the cell in Shannons. It is also the upper limit of the cell occupied storage size where every 100,000,000 Shannons give 1-byte storage. +* `proposals_hash`: [`H256`](#type-h256) - The hash on `proposals` in the block body. -This is a 64-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint64](#type-uint64). + It is all zeros when `proposals` is empty, or the hash on all the bytes concatenated together. -### Type `CellData` +* `timestamp`: [`Uint64`](#type-uint64) - The block timestamp. -The cell data content and hash. + It is a Unix timestamp in milliseconds (1 second = 1000 milliseconds). -##### Examples + Miners should put the time when the block is created in the header, however, the precision is not guaranteed. A block with a higher block number may even have a smaller timestamp. +* `transactions_root`: [`H256`](#type-h256) - The commitment to all the transactions in the block. -``` -{ - "content": "0x7f454c460201010000000000000000000200f3000100000078000100000000004000000000000000980000000000000005000000400038000100400003000200010000000500000000000000000000000000010000000000000001000000000082000000000000008200000000000000001000000000000001459308d00573000000002e7368737472746162002e74657874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000010000000600000000000000780001000000000078000000000000000a0000000000000000000000000000000200000000000000000000000000000001000000030000000000000000000000000000000000000082000000000000001100000000000000000000000000000001000000000000000000000000000000", - "hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5" -} -``` + It is a hash on two Merkle Tree roots: + * The root of a CKB Merkle Tree, which items are the transaction hashes of all the transactions in the block. + * The root of a CKB Merkle Tree, but the items are the transaction witness hashes of all the transactions in the block. -#### Fields +* `version`: [`AlertId`](#type-alertid) - The block version. -`CellData` is a JSON object with the following fields. + It must equal to 0 now and is reserved for future upgrades. -* `content`: [`JsonBytes`](#type-jsonbytes) - Cell content. +### Type `HeaderView` +The JSON view of a Header. -* `hash`: [`H256`](#type-h256) - Cell content hash. +This structure is serialized into a JSON object with field `hash` and all the fields in +[`Header`](struct.Header.html). +###### Examples -### Type `CellDep` +```json + { + "compact_target": "0x1e083126", + "dao": "0xb5a3e047474401001bc476b9ee573000c0c387962a38000000febffacf030000", + "epoch": "0x7080018000001", + "hash": "0xa5f5c85987a15de25661e5a214f2c1449cd803f071acc7999820f25246471f40", + "nonce": "0x0", + "number": "0x400", + "parent_hash": "0xae003585fa15309b30b31aed3dcf385e9472c3c3e93746a6c4540629a6a1ed2d", + "proposals_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "timestamp": "0x5cd2b117", + "transactions_root": "0xc47d5b78b3c4c4c853e2a32810818940d0ee403423bea9ec7b8e566d9595206c", + "extra_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "version": "0x0" + } +``` + +#### Fields: +* `compact_target`: [`AlertId`](#type-alertid) - The block difficulty target. -The cell dependency of a transaction. + It can be converted to a 256-bit target. Miners must ensure the Eaglesong of the header is within the target. -##### Examples +* `dao`: [`Byte32`](#type-byte32) - DAO fields. + See RFC [Deposit and Withdraw in Nervos DAO](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0023-dao-deposit-withdraw/0023-dao-deposit-withdraw.md#calculation). -``` -{ - "dep_type": "code", - "out_point": { - "index": "0x0", - "tx_hash": "0xa4037a893eb48e18ed4ef61034ce26eba9c585f15c9cee102ae58505565eccc3" - } -} -``` +* `epoch`: [`Uint64`](#type-uint64) - The epoch information of this block. + See `EpochNumberWithFraction` for details. -#### Fields +* `extra_hash`: [`H256`](#type-h256) - The hash on `uncles` and extension in the block body. -`CellDep` is a JSON object with the following fields. + The uncles hash is all zeros when `uncles` is empty, or the hash on all the uncle header hashes concatenated together. The extension hash is the hash of the extension. The extra hash is the hash on uncles hash and extension hash concatenated together. -* `out_point`: [`OutPoint`](#type-outpoint) - Reference to the cell. + **Notice** -* `dep_type`: [`DepType`](#type-deptype) - Dependency type. + This field is renamed from `uncles_hash` since 0.100.0. More details can be found in [CKB RFC 0031]. + [CKB RFC 0031]: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0031-variable-length-header-field/0031-variable-length-header-field.md -### Type `CellInfo` +* `hash`: [`H256`](#type-h256) - The header hash. It is also called the block hash. -The JSON view of a cell combining the fields in cell output and cell data. +* `nonce`: [`Uint128`](#type-uint128) - Miner can modify this field to find a proper value such that the Eaglesong of the header is within the target encoded from `compact_target`. -##### Examples +* `number`: [`Uint64`](#type-uint64) - The consecutive block number starting from 0. +* `parent_hash`: [`H256`](#type-h256) - The header hash of the parent block. -``` -{ - "data": { - "content": "0x7f454c460201010000000000000000000200f3000100000078000100000000004000000000000000980000000000000005000000400038000100400003000200010000000500000000000000000000000000010000000000000001000000000082000000000000008200000000000000001000000000000001459308d00573000000002e7368737472746162002e74657874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000010000000600000000000000780001000000000078000000000000000a0000000000000000000000000000000200000000000000000000000000000001000000030000000000000000000000000000000000000082000000000000001100000000000000000000000000000001000000000000000000000000000000", - "hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5" - }, - "output": { - "capacity": "0x802665800", - "lock": { - "args": "0x", - "code_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "hash_type": "data" - }, - "type": null - } -} -``` +* `proposals_hash`: [`H256`](#type-h256) - The hash on `proposals` in the block body. + It is all zeros when `proposals` is empty, or the hash on all the bytes concatenated together. -#### Fields +* `timestamp`: [`Uint64`](#type-uint64) - The block timestamp. -`CellInfo` is a JSON object with the following fields. + It is a Unix timestamp in milliseconds (1 second = 1000 milliseconds). -* `output`: [`CellOutput`](#type-celloutput) - Cell fields appears in the transaction `outputs` array. + Miners should put the time when the block is created in the header, however, the precision is not guaranteed. A block with a higher block number may even have a smaller timestamp. -* `data`: [`CellData`](#type-celldata) `|` `null` - Cell data. +* `transactions_root`: [`H256`](#type-h256) - The commitment to all the transactions in the block. - This is `null` when the data is not requested, which does not mean the cell data is empty. + It is a hash on two Merkle Tree roots: + * The root of a CKB Merkle Tree, which items are the transaction hashes of all the transactions in the block. + * The root of a CKB Merkle Tree, but the items are the transaction witness hashes of all the transactions in the block. -### Type `CellInput` +* `version`: [`AlertId`](#type-alertid) - The block version. -The input cell of a transaction. + It must equal to 0 now and is reserved for future upgrades. -##### Examples +### Type `IndexerCell` +Live cell +#### Fields: +* `block_number`: [`Uint64`](#type-uint64) - the number of the transaction committed in the block -``` -{ - "previous_output": { - "index": "0x0", - "tx_hash": "0x365698b50ca0da75dca2c87f9e7b563811d3b5813736b8cc62cc3b106faceb17" - }, - "since": "0x0" -} -``` +* `out_point`: [`OutPoint`](#type-outpoint) - reference to a cell via transaction hash and output index +* `output`: [`CellOutput`](#type-celloutput) - the fields of an output cell -#### Fields +* `tx_index`: [`AlertId`](#type-alertid) - the position index of the transaction committed in the block -`CellInput` is a JSON object with the following fields. +### Type `IndexerCellType` +Cell type -* `since`: [`Uint64`](#type-uint64) - Restrict when the transaction can be committed into the chain. +### Type `IndexerCellsCapacity` +Cells capacity - See the RFC [Transaction valid since](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0017-tx-valid-since/0017-tx-valid-since.md). +#### Fields: +* `block_hash`: [`H256`](#type-h256) - indexed tip block hash -* `previous_output`: [`OutPoint`](#type-outpoint) - Reference to the input cell. +* `block_number`: [`Uint64`](#type-uint64) - indexed tip block number +* `capacity`: [`Uint64`](#type-uint64) - total capacity -### Type `CellOutput` +### Type `IndexerOrder` +Order Desc | Asc -The fields of an output cell except the cell data. +### Type `IndexerPagination_for_IndexerCell` +IndexerPagination wraps objects array and last_cursor to provide paging -##### Examples +#### Fields: +* `last_cursor`: [`JsonBytes`](#type-jsonbytes) - pagination parameter +* `objects`: `Array<` [`IndexerCell`](#type-indexercell) `>` - objects collection -``` -{ - "capacity": "0x2540be400", - "lock": { - "code_hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5", - "hash_type": "data", - "args": "0x" - }, - "type": null -} -``` +### Type `IndexerPagination_for_IndexerTx` +IndexerPagination wraps objects array and last_cursor to provide paging +#### Fields: +* `last_cursor`: [`JsonBytes`](#type-jsonbytes) - pagination parameter -#### Fields +* `objects`: `Array<` [`IndexerTx`](#type-indexertx) `>` - objects collection -`CellOutput` is a JSON object with the following fields. +### Type `IndexerScriptType` +ScriptType `Lock` | `Type` -* `capacity`: [`Capacity`](#type-capacity) - The cell capacity. +### Type `IndexerSearchKey` +SearchKey represent indexer support params - The capacity of a cell is the value of the cell in Shannons. It is also the upper limit of the cell occupied storage size where every 100,000,000 Shannons give 1-byte storage. +#### Fields: +* `script`: [`Script`](#type-script) - Script -* `lock`: [`Script`](#type-script) - The lock script. +* `script_type`: [`IndexerScriptType`](#type-indexerscripttype) - Script Type -* `type_`: [`Script`](#type-script) `|` `null` - The optional type script. +### Type `IndexerSearchKeyFilter` +IndexerSearchKeyFilter represent indexer params `filter` - The JSON field name is “type”. +### Type `IndexerSearchMode` +IndexerSearchMode represent search mode, default is prefix search +### Type `IndexerTip` +Indexer tip information -### Type `CellWithStatus` +#### Fields: +* `block_hash`: [`H256`](#type-h256) - indexed tip block hash -The JSON view of a cell with its status information. +* `block_number`: [`Uint64`](#type-uint64) - indexed tip block number -##### Examples +### Type `IndexerTx` +Indexer Transaction Object +### Type `IndexerTxWithCell` +Ungrouped Tx inner type -``` -{ - "cell": { - "data": { - "content": "0x7f454c460201010000000000000000000200f3000100000078000100000000004000000000000000980000000000000005000000400038000100400003000200010000000500000000000000000000000000010000000000000001000000000082000000000000008200000000000000001000000000000001459308d00573000000002e7368737472746162002e74657874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000010000000600000000000000780001000000000078000000000000000a0000000000000000000000000000000200000000000000000000000000000001000000030000000000000000000000000000000000000082000000000000001100000000000000000000000000000001000000000000000000000000000000", - "hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5" - }, - "output": { - "capacity": "0x802665800", - "lock": { - "args": "0x", - "code_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "hash_type": "data" - }, - "type": null - } - }, - "status": "live" -} -``` +#### Fields: +* `block_number`: [`Uint64`](#type-uint64) - the number of the transaction committed in the block +* `io_index`: [`AlertId`](#type-alertid) - the position index of the cell in the transaction inputs or outputs +* `io_type`: [`IndexerCellType`](#type-indexercelltype) - io type -``` -{ - "cell": null, - "status": "unknown" -} -``` +* `tx_hash`: [`H256`](#type-h256) - transaction hash +* `tx_index`: [`AlertId`](#type-alertid) - the position index of the transaction committed in the block -#### Fields +### Type `IndexerTxWithCells` +Grouped Tx inner type -`CellWithStatus` is a JSON object with the following fields. +#### Fields: +* `block_number`: [`Uint64`](#type-uint64) - the number of the transaction committed in the block -* `cell`: [`CellInfo`](#type-cellinfo) `|` `null` - The cell information. +* `cells`: `Array<` ([`IndexerCellType`](#type-indexercelltype) , [`AlertId`](#type-alertid)) `>` - Array [(io_type, io_index)] - For performance issues, CKB only keeps the information for live cells. +* `tx_hash`: [`H256`](#type-h256) - transaction hash -* `status`: `string` - Status of the cell. +* `tx_index`: [`AlertId`](#type-alertid) - the position index of the transaction committed in the block - Allowed values: “live”, “dead”, “unknown”. +### Type `JsonBytes` - * `live` - The transaction creating this cell is in the chain, and there are no transactions found in the chain that uses this cell as an input. - * `dead` - (**Deprecated**: the dead status will be removed since 0.36.0, please do not rely on the logic that differentiates dead and unknown cells.) The transaction creating this cell is in the chain, and a transaction is found in the chain which uses this cell as an input. +### Type `LocalNode` +The information of the node itself. - * `unknown` - CKB does not know the status of the cell. Either the transaction creating this cell is not in the chain yet, or it is no longer live. +###### Examples +```json + { + "active": true, + "addresses": [ + { + "address": "/ip4/192.168.0.2/tcp/8112/p2p/QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS", + "score": "0xff" + }, + { + "address": "/ip4/0.0.0.0/tcp/8112/p2p/QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS", + "score": "0x1" + } + ], + "connections": "0xb", + "node_id": "QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS", + "protocols": [ + { + "id": "0x0", + "name": "/ckb/ping", + "support_versions": [ + "0.0.1" + ] + }, + { + "id": "0x1", + "name": "/ckb/discovery", + "support_versions": [ + "0.0.1" + ] + } + ], + "version": "0.34.0 (f37f598 2020-07-17)" + } +``` + +#### Fields: +* `active`: `boolean` - Whether this node is active. -### Type `CellbaseTemplate` + An inactive node ignores incoming p2p messages and drops outgoing messages. -The cellbase transaction template of the new block for miners. +* `addresses`: `Array<` [`NodeAddress`](#type-nodeaddress) `>` - P2P addresses of this node. -#### Fields + A node can have multiple addresses. -`CellbaseTemplate` is a JSON object with the following fields. +* `connections`: [`Uint64`](#type-uint64) - Count of currently connected peers. -* `hash`: [`H256`](#type-h256) - The cellbase transaction hash. +* `node_id`: `string` - The unique node ID derived from the p2p private key. -* `cycles`: [`Cycle`](#type-cycle) `|` `null` - The hint of how many cycles this transaction consumes. + The private key is generated randomly on the first boot. - Miners can utilize this field to ensure that the total cycles do not exceed the limit while selecting transactions. +* `protocols`: `Array<` [`LocalNodeProtocol`](#type-localnodeprotocol) `>` - Supported protocols. -* `data`: [`Transaction`](#type-transaction) - The cellbase transaction. +* `version`: `string` - CKB node version. + Example: "version": "0.34.0 (f37f598 2020-07-17)" -### Type `ChainInfo` +### Type `LocalNodeProtocol` +The information of a P2P protocol that is supported by the local node. -Chain information. +#### Fields: +* `id`: [`Uint64`](#type-uint64) - Unique protocol ID. -#### Fields +* `name`: `string` - Readable protocol name. -`ChainInfo` is a JSON object with the following fields. +* `support_versions`: `Array<` `string` `>` - Supported versions. -* `chain`: `string` - The network name. + See [Semantic Version](https://semver.org/) about how to specify a version. - Examples: +### Type `MainLoggerConfig` +Runtime logger config. - * “ckb” - Mirana the mainnet. +### Type `MerkleProof` +Proof of CKB Merkle Tree. - * “ckb_testnet” - Pudge the testnet. +CKB Merkle Tree is a [CBMT](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0006-merkle-tree/0006-merkle-tree.md) using CKB blake2b hash as the merge function. -* `median_time`: [`Timestamp`](#type-timestamp) - The median time of the last 37 blocks, including the tip block. +#### Fields: +* `indices`: `Array<` [`AlertId`](#type-alertid) `>` - Leaves indices in the CBMT that are proved present in the block. -* `epoch`: [`EpochNumberWithFraction`](#type-epochnumberwithfraction) - The epoch information of tip block in the chain. + These are indices in the CBMT tree not the transaction indices in the block. -* `difficulty`: [`U256`](#type-u256) - Current difficulty. +* `lemmas`: `Array<` [`H256`](#type-h256) `>` - Hashes of all siblings along the paths to root. - Decoded from the epoch `compact_target`. +### Type `MinerReward` +Block rewards for miners. -* `is_initial_block_download`: `boolean` - Whether the local node is in IBD, Initial Block Download. +#### Fields: +* `committed`: [`Uint64`](#type-uint64) - The transaction fees that are rewarded to miners because the transaction is committed in the block. - When a node starts and its chain tip timestamp is far behind the wall clock, it will enter the IBD until it catches up the synchronization. + Miners get 60% of the transaction fee for each transaction committed in the block. - During IBD, the local node only synchronizes the chain with one selected remote node and stops responding the most P2P requests. +* `primary`: [`Uint64`](#type-uint64) - The primary base block reward allocated to miners. -* `alerts`: `Array<` [`AlertMessage`](#type-alertmessage) `>` - Active alerts stored in the local node. +* `proposal`: [`Uint64`](#type-uint64) - The transaction fees that are rewarded to miners because the transaction is proposed in the block or its uncles. + Miners get 40% of the transaction fee for each transaction proposed in the block and committed later in its active commit window. -### Type `Consensus` +* `secondary`: [`Uint64`](#type-uint64) - The secondary base block reward allocated to miners. -Consensus defines various parameters that influence chain consensus +### Type `NodeAddress` +Node P2P address and score. -#### Fields +#### Fields: +* `address`: `string` - P2P address. -`Consensus` is a JSON object with the following fields. + This is the same address used in the whitelist in ckb.toml. -* `id`: `string` - Names the network. + Example: "/ip4/192.168.0.2/tcp/8112/p2p/QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS" -* `genesis_hash`: [`H256`](#type-h256) - The genesis block hash +* `score`: [`Uint64`](#type-uint64) - Address score. -* `dao_type_hash`: [`H256`](#type-h256) - The dao type hash + A higher score means a higher probability of a successful connection. -* `secp256k1_blake160_sighash_all_type_hash`: [`H256`](#type-h256) `|` `null` - The secp256k1_blake160_sighash_all_type_hash +### Type `OutPoint` +Reference to a cell via transaction hash and output index. -* `secp256k1_blake160_multisig_all_type_hash`: [`H256`](#type-h256) `|` `null` - The secp256k1_blake160_multisig_all_type_hash +###### Examples -* `initial_primary_epoch_reward`: [`Capacity`](#type-capacity) - The initial primary_epoch_reward +```json + { + "index": "0x0", + "tx_hash": "0x365698b50ca0da75dca2c87f9e7b563811d3b5813736b8cc62cc3b106faceb17" + } +``` -* `secondary_epoch_reward`: [`Capacity`](#type-capacity) - The secondary primary_epoch_reward +#### Fields: +* `index`: [`AlertId`](#type-alertid) - The output index of the cell in the transaction specified by `tx_hash`. -* `max_uncles_num`: [`Uint64`](#type-uint64) - The maximum amount of uncles allowed for a block +* `tx_hash`: [`H256`](#type-h256) - Transaction hash in which the cell is an output. -* `orphan_rate_target`: [`RationalU256`](#type-rationalu256) - The expected orphan_rate +### Type `OutputsValidator` +Transaction output validators that prevent common mistakes. -* `epoch_duration_target`: [`Uint64`](#type-uint64) - The expected epoch_duration +### Type `PeerSyncState` +The chain synchronization state between the local node and a remote node. -* `tx_proposal_window`: [`ProposalWindow`](#type-proposalwindow) - The two-step-transaction-confirmation proposal window +#### Fields: +* `can_fetch_count`: [`Uint64`](#type-uint64) - The count of blocks are available for concurrency download. -* `proposer_reward_ratio`: [`RationalU256`](#type-rationalu256) - The two-step-transaction-confirmation proposer reward ratio +* `inflight_count`: [`Uint64`](#type-uint64) - The count of concurrency downloading blocks. -* `cellbase_maturity`: [`EpochNumberWithFraction`](#type-epochnumberwithfraction) - The Cellbase maturity +* `unknown_header_list_size`: [`Uint64`](#type-uint64) - The total size of unknown header list. -* `median_time_block_count`: [`Uint64`](#type-uint64) - This parameter indicates the count of past blocks used in the median time calculation + **Deprecated**: this is an internal state and will be removed in a future release. -* `max_block_cycles`: [`Cycle`](#type-cycle) - Maximum cycles that all the scripts in all the commit transactions can take +### Type `PoolTxDetailInfo` +A Tx details info in tx-pool. -* `max_block_bytes`: [`Uint64`](#type-uint64) - Maximum number of bytes to use for the entire block +#### Fields: +* `ancestors_count`: [`Uint64`](#type-uint64) - The ancestors count of tx -* `block_version`: [`Version`](#type-version) - The block version number supported +* `descendants_count`: [`Uint64`](#type-uint64) - The descendants count of tx -* `tx_version`: [`Version`](#type-version) - The tx version number supported +* `entry_status`: `string` - The detailed status in tx-pool, `pending`, `gap`, `proposed` -* `type_id_code_hash`: [`H256`](#type-h256) - The “TYPE_ID” in hex +* `pending_count`: [`Uint64`](#type-uint64) - The pending(`pending` and `gap`) count -* `max_block_proposals_limit`: [`Uint64`](#type-uint64) - The Limit to the number of proposals per block +* `proposed_count`: [`Uint64`](#type-uint64) - The proposed count -* `primary_epoch_reward_halving_interval`: [`Uint64`](#type-uint64) - Primary reward is cut in half every halving_interval epoch +* `rank_in_pending`: [`Uint64`](#type-uint64) - The rank in pending, starting from 0 -* `permanent_difficulty_in_dummy`: `boolean` - Keep difficulty be permanent if the pow is dummy +* `score_sortkey`: [`AncestorsScoreSortKey`](#type-ancestorsscoresortkey) - The score key details, useful to debug -* `hardfork_features`: [`HardForks`](#type-hardforks) - Hardfork features +* `timestamp`: [`Uint64`](#type-uint64) - The time added into tx-pool -* `softforks`: `{ [ key:` [`DeploymentPos`](#type-deploymentpos) `]: ` [`SoftFork`](#type-softfork) `}` - Softforks +### Type `ProposalShortId` +The 10-byte fixed-length binary encoded as a 0x-prefixed hex string in JSON. +###### Example -### Type `Cycle` +```text + 0xa0ef4eb5f4ceeb08a4c8 +``` -Count of cycles consumed by CKB VM to run scripts. +### Type `ProposalWindow` +Two protocol parameters `closest` and `farthest` define the closest and farthest on-chain distance between a transaction's proposal and commitment. -This is a 64-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint64](#type-uint64). +A non-cellbase transaction is committed at height h_c if all of the following conditions are met: +1) it is proposed at height h_p of the same chain, where w_close <= h_c − h_p <= w_far ; +2) it is in the commitment zone of the main chain block with height h_c ; -### Type `DaoWithdrawingCalculationKind` +```text + ProposalWindow { closest: 2, farthest: 10 } + propose + \ + \ + 13 14 [15 16 17 18 19 20 21 22 23] + \_______________________/ + \ + commit +``` -An enum to represent the two kinds of dao withdrawal amount calculation option. `DaoWithdrawingCalculationKind` is equivalent to [`H256`](#type-h256) `|` [`OutPoint`](#type-outpoint). +#### Fields: +* `closest`: [`Uint64`](#type-uint64) - The closest distance between the proposal and the commitment. -`DaoWithdrawingCalculationKind` is equivalent to `"withdrawing_header_hash" | "withdrawing_out_point"`. +* `farthest`: [`Uint64`](#type-uint64) - The farthest distance between the proposal and the commitment. -* the assumed reference block hash for withdrawing phase 1 transaction -* the out point of the withdrawing phase 1 transaction +### Type `Ratio` +Represents the ratio `numerator / denominator`, where `numerator` and `denominator` are both unsigned 64-bit integers. +#### Fields: +* `denom`: [`Uint64`](#type-uint64) - Denominator. -### Type `DepType` +* `numer`: [`Uint64`](#type-uint64) - Numerator. -The dep cell type. Allowed values: “code” and “dep_group”. +### Type `RawTxPool` +All transactions in tx-pool. -`DepType` is equivalent to `"code" | "dep_group"`. +`RawTxPool` is equivalent to [`TxPoolIds`][] `|` [`TxPoolEntries`][]. -* Type “code”. +[`TxPoolIds`]: struct.TxPoolIds.html +[`TxPoolEntries`]: struct.TxPoolEntries.html - Use the cell itself as the dep cell. +### Type `RemoteNode` +Information of a remote node. -* Type “dep_group”. +A remote node connects to the local node via the P2P network. It is often called a peer. - The cell is a dep group which members are cells. These members are used as dep cells instead of the group itself. +###### Examples - The dep group stores the array of `OutPoint`s serialized via molecule in the cell data. Each `OutPoint` points to one cell member. +```json + { + "addresses": [ + { + "address": "/ip6/::ffff:18.185.102.19/tcp/8115/p2p/QmXwUgF48ULy6hkgfqrEwEfuHW7WyWyWauueRDAYQHNDfN", + "score": "0x64" + }, + { + "address": "/ip4/18.185.102.19/tcp/8115/p2p/QmXwUgF48ULy6hkgfqrEwEfuHW7WyWyWauueRDAYQHNDfN", + "score": "0x64" + } + ], + "connected_duration": "0x2f", + "is_outbound": true, + "last_ping_duration": "0x1a", + "node_id": "QmXwUgF48ULy6hkgfqrEwEfuHW7WyWyWauueRDAYQHNDfN", + "protocols": [ + { + "id": "0x4", + "version": "0.0.1" + }, + { + "id": "0x2", + "version": "0.0.1" + }, + { + "id": "0x1", + "version": "0.0.1" + }, + { + "id": "0x64", + "version": "1" + }, + { + "id": "0x6e", + "version": "1" + }, + { + "id": "0x66", + "version": "1" + }, + { + "id": "0x65", + "version": "1" + }, + { + "id": "0x0", + "version": "0.0.1" + } + ], + "sync_state": { + "best_known_header_hash": null, + "best_known_header_number": null, + "can_fetch_count": "0x80", + "inflight_count": "0xa", + "last_common_header_hash": null, + "last_common_header_number": null, + "unknown_header_list_size": "0x20" + }, + "version": "0.34.0 (f37f598 2020-07-17)" + } +``` +#### Fields: +* `addresses`: `Array<` [`NodeAddress`](#type-nodeaddress) `>` - The remote node addresses. +* `connected_duration`: [`Uint64`](#type-uint64) - Elapsed time in milliseconds since the remote node is connected. -### Type `DeploymentInfo` +* `is_outbound`: `boolean` - Whether this is an outbound remote node. -An object containing various state info regarding deployments of consensus changes + If the connection is established by the local node, `is_outbound` is true. -#### Fields +* `node_id`: `string` - The remote node ID which is derived from its P2P private key. -`DeploymentInfo` is a JSON object with the following fields. +* `protocols`: `Array<` [`RemoteNodeProtocol`](#type-remotenodeprotocol) `>` - Active protocols. -* `bit`: https://doc.rust-lang.org/1.71.1/std/primitive.u8.html - determines which bit in the `version` field of the block is to be used to signal the softfork lock-in and activation. It is chosen from the set {0,1,2,…,28}. + CKB uses Tentacle multiplexed network framework. Multiple protocols are running simultaneously in the connection. -* `start`: [`EpochNumber`](#type-epochnumber) - specifies the first epoch in which the bit gains meaning. +* `version`: `string` - The remote node version. -* `timeout`: [`EpochNumber`](#type-epochnumber) - specifies an epoch at which the miner signaling ends. Once this epoch has been reached, if the softfork has not yet locked_in (excluding this epoch block’s bit state), the deployment is considered failed on all descendants of the block. +### Type `RemoteNodeProtocol` +The information about an active running protocol. -* `min_activation_epoch`: [`EpochNumber`](#type-epochnumber) - specifies the epoch at which the softfork is allowed to become active. +#### Fields: +* `id`: [`Uint64`](#type-uint64) - Unique protocol ID. -* `period`: [`EpochNumber`](#type-epochnumber) - the length in epochs of the signalling period +* `version`: `string` - Active protocol version. -* `threshold`: [`Ratio`](#type-ratio) - the ratio of blocks with the version bit set required to activate the feature +### Type `Rfc0043` +Represent soft fork deployments where activation is controlled by rfc0043 signaling -* `since`: [`EpochNumber`](#type-epochnumber) - The first epoch which the current state applies +#### Fields: +* `rfc0043`: [`Deployment`](#type-deployment) - RFC0043 deployment params -* `state`: [`DeploymentState`](#type-deploymentstate) - With each epoch and softfork, we associate a deployment state. The possible states are: +* `status`: [`SoftForkStatus`](#type-softforkstatus) - SoftFork status - * `DEFINED` is the first state that each softfork starts. The blocks of 0 epoch is by definition in this state for each deployment. +### Type `Script` +Describes the lock script and type script for a cell. - * `STARTED` for all blocks reach or past the start_epoch. +###### Examples - * `LOCKED_IN` for one period after the first period with STARTED blocks of which at least threshold has the associated bit set in version. +```json + { + "code_hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5", + "hash_type": "data", + "args": "0x" + } +``` - * `ACTIVE` for all blocks after the LOCKED_IN period. +#### Fields: +* `args`: [`JsonBytes`](#type-jsonbytes) - Arguments for script. - * `FAILED` for all blocks after the timeout_epoch, if LOCKED_IN was not reached. +* `code_hash`: [`H256`](#type-h256) - The hash used to match the script code. +* `hash_type`: [`ScriptHashType`](#type-scripthashtype) - Specifies how to use the `code_hash` to match the script code. -### Type `DeploymentPos` +### Type `ScriptHashType` +Specifies how the script `code_hash` is used to match the script code and how to run the code. -Deployment name +Allowed kinds: "data", "type", "data1" and "data2" -`DeploymentPos` is equivalent to `"testdummy" | "light_client"`. +Refer to the section [Code Locating](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md#code-locating) and [Upgradable Script](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md#upgradable-script) in the RFC *CKB Transaction Structure*. -* Dummy -* light client protocol +The hash type is split into the high 7 bits and the low 1 bit, when the low 1 bit is 1, it indicates the type, when the low 1 bit is 0, it indicates the data, and then it relies on the high 7 bits to indicate that the data actually corresponds to the version. +### Type `SoftFork` +SoftFork information -### Type `DeploymentState` +### Type `SoftForkStatus` +SoftForkStatus which is either `buried` (for soft fork deployments where the activation epoch is hard-coded into the client implementation), or `rfc0043` (for soft fork deployments where activation is controlled by rfc0043 signaling). -The possible softfork deployment state +### Type `Status` +Status for transaction -`DeploymentState` is equivalent to `"defined" | "started" | "locked_in" | "active" | "failed"`. +### Type `SyncState` +The overall chain synchronization state of this local node. -* First state that each softfork starts. The 0 epoch is by definition in this state for each deployment. -* For epochs past the `start` epoch. -* For one epoch after the first epoch period with STARTED epochs of which at least `threshold` has the associated bit set in `version`. -* For all epochs after the LOCKED_IN epoch. -* For one epoch period past the `timeout_epoch`, if LOCKED_IN was not reached. +#### Fields: +* `best_known_block_number`: [`Uint64`](#type-uint64) - This is the best known block number observed by the local node from the P2P network. + The best here means that the block leads a chain which has the best known accumulated difficulty. -### Type `DeploymentsInfo` + This can be used to estimate the synchronization progress. If this RPC returns B, and the RPC `get_tip_block_number` returns T, the node has already synchronized T/B blocks. -Chain information. +* `best_known_block_timestamp`: [`Uint64`](#type-uint64) - This is timestamp of the same block described in `best_known_block_number`. -#### Fields +* `fast_time`: [`Uint64`](#type-uint64) - The download scheduler's time analysis data, the fast is the 1/3 of the cut-off point, unit ms -`DeploymentsInfo` is a JSON object with the following fields. +* `ibd`: `boolean` - Whether the local node is in IBD, Initial Block Download. -* `hash`: [`H256`](#type-h256) - requested block hash + When a node starts and its chain tip timestamp is far behind the wall clock, it will enter the IBD until it catches up the synchronization. -* `epoch`: [`EpochNumber`](#type-epochnumber) - requested block epoch + During IBD, the local node only synchronizes the chain with one selected remote node and stops responding to most P2P requests. -* `deployments`: `{ [ key:` [`DeploymentPos`](#type-deploymentpos) `]: ` [`DeploymentInfo`](#type-deploymentinfo) `}` - deployments info +* `inflight_blocks_count`: [`Uint64`](#type-uint64) - Count of downloading blocks. +* `low_time`: [`Uint64`](#type-uint64) - The download scheduler's time analysis data, the low is the 9/10 of the cut-off point, unit ms -### Type `Either` +* `normal_time`: [`Uint64`](#type-uint64) - The download scheduler's time analysis data, the normal is the 4/5 of the cut-off point, unit ms -The enum `Either` with variants `Left` and `Right` is a general purpose sum type with two cases. +* `orphan_blocks_count`: [`Uint64`](#type-uint64) - Count of orphan blocks the local node has downloaded. -`Either` is equivalent to `"left" | "right"`. + The local node downloads multiple blocks simultaneously but blocks must be connected consecutively. If a descendant is downloaded before its ancestors, it becomes an orphan block. -* A value of type `L`. -* A value of type `R`. + If this number is too high, it indicates that block download has stuck at some block. +### Type `Transaction` +The transaction. -### Type `EpochNumber` +Refer to RFC [CKB Transaction Structure](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md). -Consecutive epoch number starting from 0. +#### Fields: +* `cell_deps`: `Array<` [`CellDep`](#type-celldep) `>` - An array of cell deps. -This is a 64-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint64](#type-uint64). + CKB locates lock script and type script code via cell deps. The script also can use syscalls to read the cells here. -### Type `EpochNumberWithFraction` + Unlike inputs, the live cells can be used as cell deps in multiple transactions. -The epoch indicator of a block. It shows which epoch the block is in, and the elapsed epoch fraction after adding this block. +* `header_deps`: `Array<` [`H256`](#type-h256) `>` - An array of header deps. -This is a 64-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint64](#type-uint64). + The block must already be in the canonical chain. -The lower 56 bits of the epoch field are split into 3 parts (listed in the order from higher bits to lower bits): + Lock script and type script can read the header information of blocks listed here. -* The highest 16 bits represent the epoch length +* `inputs`: `Array<` [`CellInput`](#type-cellinput) `>` - An array of input cells. -* The next 16 bits represent the current block index in the epoch, starting from 0. + In the canonical chain, any cell can only appear as an input once. -* The lowest 24 bits represent the current epoch number. +* `outputs`: `Array<` [`CellOutput`](#type-celloutput) `>` - An array of output cells. -Assume there’s a block, which number is 11555 and in epoch 50. The epoch 50 starts from block 11000 and have 1000 blocks. The epoch field for this particular block will then be 1,099,520,939,130,930, which is calculated in the following way: +* `outputs_data`: `Array<` [`JsonBytes`](#type-jsonbytes) `>` - Output cells data. + This is a parallel array of outputs. The cell capacity, lock, and type of the output i is `outputs[i]` and its data is `outputs_data[i]`. -``` -50 | ((11555 - 11000) << 24) | (1000 << 40) -``` +* `version`: [`AlertId`](#type-alertid) - Reserved for future usage. It must equal 0 in current version. +* `witnesses`: `Array<` [`JsonBytes`](#type-jsonbytes) `>` - An array of variable-length binaries. -### Type `EpochView` + Lock script and type script can read data here to verify the transaction. -JSON view of an epoch. + For example, the bundled secp256k1 lock script requires storing the signature in `witnesses`. -CKB adjusts difficulty based on epochs. +### Type `TransactionAndWitnessProof` +Merkle proof for transactions' witnesses in a block. -##### Examples +#### Fields: +* `block_hash`: [`H256`](#type-h256) - Block hash +* `transactions_proof`: [`MerkleProof`](#type-merkleproof) - Merkle proof of all transactions' hash -``` -{ - "compact_target": "0x1e083126", - "length": "0x708", - "number": "0x1", - "start_number": "0x3e8" -} -``` +* `witnesses_proof`: [`MerkleProof`](#type-merkleproof) - Merkle proof of transactions' witnesses +### Type `TransactionProof` +Merkle proof for transactions in a block. -#### Fields +#### Fields: +* `block_hash`: [`H256`](#type-h256) - Block hash -`EpochView` is a JSON object with the following fields. +* `proof`: [`MerkleProof`](#type-merkleproof) - Merkle proof of all transactions' hash -* `number`: [`EpochNumber`](#type-epochnumber) - Consecutive epoch number starting from 0. +* `witnesses_root`: [`H256`](#type-h256) - Merkle root of all transactions' witness hash -* `start_number`: [`BlockNumber`](#type-blocknumber) - The block number of the first block in the epoch. +### Type `TransactionTemplate` +Transaction template which is ready to be committed in the new block. - It also equals the total count of blocks in all the epochs which epoch number is less than this epoch. +#### Fields: +* `data`: [`Transaction`](#type-transaction) - The transaction. -* `length`: [`BlockNumber`](#type-blocknumber) - The number of blocks in this epoch. + Miners must keep it unchanged when including it in the new block. -* `compact_target`: [`Uint32`](#type-uint32) - The difficulty target for any block in this epoch. +* `hash`: [`H256`](#type-h256) - Transaction hash. +* `required`: `boolean` - Whether miner must include this transaction in the new block. -### Type `EstimateCycles` +### Type `TransactionView` +The JSON view of a Transaction. -Response result of the RPC method `estimate_cycles`. +This structure is serialized into a JSON object with field `hash` and all the fields in +[`Transaction`](struct.Transaction.html). -#### Fields +###### Examples -`EstimateCycles` is a JSON object with the following fields. - -* `cycles`: [`Cycle`](#type-cycle) - The count of cycles that the VM has consumed to verify this transaction. - - -### Type `FeeRateStatistics` - -The fee_rate statistics information, includes mean and median, unit: shannons per kilo-weight - -#### Fields - -`FeeRateStatistics` is a JSON object with the following fields. - -* `mean`: [`Uint64`](#type-uint64) - mean - -* `median`: [`Uint64`](#type-uint64) - median - - -### Type `H256` - -The 256-bit binary data encoded as a 0x-prefixed hex string in JSON. - -### Type `HardForks` - -Hardfork information - - - -### Type `Header` - -The block header. - -Refer to RFC [CKB Block Structure](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0027-block-structure/0027-block-structure.md). - -#### Fields - -`Header` is a JSON object with the following fields. - -* `version`: [`Version`](#type-version) - The block version. - - It must equal to 0 now and is reserved for future upgrades. - -* `compact_target`: [`Uint32`](#type-uint32) - The block difficulty target. - - It can be converted to a 256-bit target. Miners must ensure the Eaglesong of the header is within the target. - -* `timestamp`: [`Timestamp`](#type-timestamp) - The block timestamp. - - It is a Unix timestamp in milliseconds (1 second = 1000 milliseconds). - - Miners should put the time when the block is created in the header, however, the precision is not guaranteed. A block with a higher block number may even have a smaller timestamp. - -* `number`: [`BlockNumber`](#type-blocknumber) - The consecutive block number starting from 0. - -* `epoch`: [`EpochNumberWithFraction`](#type-epochnumberwithfraction) - The epoch information of this block. - - See `EpochNumberWithFraction` for details. - -* `parent_hash`: [`H256`](#type-h256) - The header hash of the parent block. - -* `transactions_root`: [`H256`](#type-h256) - The commitment to all the transactions in the block. - - It is a hash on two Merkle Tree roots: - - * The root of a CKB Merkle Tree, which items are the transaction hashes of all the transactions in the block. - - * The root of a CKB Merkle Tree, but the items are the transaction witness hashes of all the transactions in the block. - -* `proposals_hash`: [`H256`](#type-h256) - The hash on `proposals` in the block body. - - It is all zeros when `proposals` is empty, or the hash on all the bytes concatenated together. - -* `extra_hash`: [`H256`](#type-h256) - The hash on `uncles` and extension in the block body. - - The uncles hash is all zeros when `uncles` is empty, or the hash on all the uncle header hashes concatenated together. The extension hash is the hash of the extension. The extra hash is the hash on uncles hash and extension hash concatenated together. - - ##### Notice - - This field is renamed from `uncles_hash` since 0.100.0. More details can be found in [CKB RFC 0031](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0031-variable-length-header-field/0031-variable-length-header-field.md). - -* `dao`: [`Byte32`](#type-byte32) - DAO fields. - - See RFC [Deposit and Withdraw in Nervos DAO](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0023-dao-deposit-withdraw/0023-dao-deposit-withdraw.md#calculation). - -* `nonce`: [`Uint128`](#type-uint128) - Miner can modify this field to find a proper value such that the Eaglesong of the header is within the target encoded from `compact_target`. - - -### Type `HeaderView` - -The JSON view of a Header. - -This structure is serialized into a JSON object with field `hash` and all the fields in [`Header`](#type-header). - -##### Examples - - -``` -{ - "compact_target": "0x1e083126", - "dao": "0xb5a3e047474401001bc476b9ee573000c0c387962a38000000febffacf030000", - "epoch": "0x7080018000001", - "hash": "0xa5f5c85987a15de25661e5a214f2c1449cd803f071acc7999820f25246471f40", - "nonce": "0x0", - "number": "0x400", - "parent_hash": "0xae003585fa15309b30b31aed3dcf385e9472c3c3e93746a6c4540629a6a1ed2d", - "proposals_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "timestamp": "0x5cd2b117", - "transactions_root": "0xc47d5b78b3c4c4c853e2a32810818940d0ee403423bea9ec7b8e566d9595206c", - "extra_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "version": "0x0" -} -``` - - -#### Fields - -`HeaderView` is a JSON object with the following fields. - -* `inner`: [`Header`](#type-header) - All the fields in `Header` are included in `HeaderView` in JSON. - -* `hash`: [`H256`](#type-h256) - The header hash. It is also called the block hash. - - -### Type `IndexerCell` - -Live cell - -#### Fields - -`IndexerCell` is a JSON object with the following fields. - -* `output`: [`CellOutput`](#type-celloutput) - the fields of an output cell - -* `output_data`: [`JsonBytes`](#type-jsonbytes) `|` `null` - the cell data - -* `out_point`: [`OutPoint`](#type-outpoint) - reference to a cell via transaction hash and output index - -* `block_number`: [`BlockNumber`](#type-blocknumber) - the number of the transaction committed in the block - -* `tx_index`: [`Uint32`](#type-uint32) - the position index of the transaction committed in the block - - -### Type `IndexerCellsCapacity` - -Cells capacity - -#### Fields - -`IndexerCellsCapacity` is a JSON object with the following fields. - -* `capacity`: [`Capacity`](#type-capacity) - total capacity - -* `block_hash`: [`H256`](#type-h256) - indexed tip block hash - -* `block_number`: [`BlockNumber`](#type-blocknumber) - indexed tip block number - - -### Type `IndexerOrder` - -Order Desc | Asc - -`IndexerOrder` is equivalent to `"desc" | "asc"`. - -* Descending order -* Ascending order - - -### Type `IndexerRange` - -A array represent (half-open) range bounded inclusively below and exclusively above [start, end). - -##### Examples - - -| JSON | range | -| --- |--- | -| [“0x0”, “0x2”] | [0, 2) | -| [“0x0”, “0x174876e801”] | [0, 100000000001) | - - - - -### Type `IndexerScriptType` - -ScriptType `Lock` | `Type` - -`IndexerScriptType` is equivalent to `"lock" | "type"`. - -* Lock -* Type - - -### Type `IndexerSearchKey` - -SearchKey represent indexer support params - -#### Fields - -`IndexerSearchKey` is a JSON object with the following fields. - -* `script`: [`Script`](#type-script) - Script - -* `script_type`: [`IndexerScriptType`](#type-indexerscripttype) - Script Type - -* `script_search_mode`: [`IndexerSearchMode`](#type-indexersearchmode) `|` `null` - Script search mode, optional default is `prefix`, means search script with prefix - -* `filter`: [`IndexerSearchKeyFilter`](#type-indexersearchkeyfilter) `|` `null` - filter cells by following conditions, all conditions are optional - -* `with_data`: `boolean` `|` `null` - bool, optional default is `true`, if with_data is set to false, the field of returning cell.output_data is null in the result - -* `group_by_transaction`: `boolean` `|` `null` - bool, optional default is `false`, if group_by_transaction is set to true, the returning objects will be grouped by the tx hash - - -### Type `IndexerSearchKeyFilter` - -IndexerSearchKeyFilter represent indexer params `filter` - -#### Fields - -`IndexerSearchKeyFilter` is a JSON object with the following fields. - -* `script`: [`Script`](#type-script) `|` `null` - if search script type is lock, filter cells by type script prefix, and vice versa - -* `script_len_range`: [`IndexerRange`](#type-indexerrange) `|` `null` - filter cells by script len range - -* `output_data`: [`JsonBytes`](#type-jsonbytes) `|` `null` - filter cells by output data - -* `output_data_filter_mode`: [`IndexerSearchMode`](#type-indexersearchmode) `|` `null` - output data filter mode, optional default is `prefix` - -* `output_data_len_range`: [`IndexerRange`](#type-indexerrange) `|` `null` - filter cells by output data len range - -* `output_capacity_range`: [`IndexerRange`](#type-indexerrange) `|` `null` - filter cells by output capacity range - -* `block_range`: [`IndexerRange`](#type-indexerrange) `|` `null` - filter cells by block number range - - -### Type `IndexerSearchMode` - -IndexerSearchMode represent search mode, default is prefix search - -`IndexerSearchMode` is equivalent to `"prefix" | "exact" | "partial"`. - -* Mode `prefix` search with prefix -* Mode `exact` search with exact match -* Mode `partial` search with partial match - - -### Type `IndexerTip` - -Indexer tip information - -#### Fields - -`IndexerTip` is a JSON object with the following fields. - -* `block_hash`: [`H256`](#type-h256) - indexed tip block hash - -* `block_number`: [`BlockNumber`](#type-blocknumber) - indexed tip block number - - -### Type `IndexerTx` - -Indexer Transaction Object - -`IndexerTx` is equivalent to `"ungrouped" | "grouped"`. - -* ###### Ungrouped format represent as `IndexerTxWithCell` - - ####### Fields - - `IndexerCellType` is equivalent to `"input" | "output"`. - - `IndexerTxWithCell` is a JSON object with the following fields. - - * `tx_hash`: [`H256`](#type-h256) - transaction hash - - * `block_number`: [`BlockNumber`](#type-blocknumber) - the number of the transaction committed in the block - - * `tx_index`: [`Uint32`](#type-uint32) - the position index of the transaction committed in the block - - * `io_index`: [`Uint32`](#type-uint32) - the position index of the cell in the transaction inputs or outputs - - * `io_type`: [`IndexerCellType`](#type-indexercelltype) - io type - -* ###### Grouped format represent as `IndexerTxWithCells` - - ####### Fields - - `IndexerCellType` is equivalent to `"input" | "output"`. - - `IndexerTxWithCells` is a JSON object with the following fields. - - * `tx_hash`: [`H256`](#type-h256) - transaction hash - - * `block_number`: [`BlockNumber`](#type-blocknumber) - the number of the transaction committed in the block - - * `tx_index`: [`Uint32`](#type-uint32)- the position index of the transaction committed in the block - - * `cells`: Array <(IndexerCellType, Uint32)> - - - -### Type `JsonBytes` - -Variable-length binary encoded as a 0x-prefixed hex string in JSON. - -##### Example - - -| JSON | Binary | -| --- |--- | -| “0x” | Empty binary | -| “0x00” | Single byte 0 | -| “0x636b62” | 3 bytes, UTF-8 encoding of ckb | -| “00” | Invalid, 0x is required | -| “0x0” | Invalid, each byte requires 2 digits | - - - - -### Type `LocalNode` - -The information of the node itself. - -##### Examples - - -``` -{ - "active": true, - "addresses": [ - { - "address": "/ip4/192.168.0.2/tcp/8112/p2p/QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS", - "score": "0xff" - }, - { - "address": "/ip4/0.0.0.0/tcp/8112/p2p/QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS", - "score": "0x1" - } - ], - "connections": "0xb", - "node_id": "QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS", - "protocols": [ - { - "id": "0x0", - "name": "/ckb/ping", - "support_versions": [ - "0.0.1" - ] - }, - { - "id": "0x1", - "name": "/ckb/discovery", - "support_versions": [ - "0.0.1" - ] - } - ], - "version": "0.34.0 (f37f598 2020-07-17)" -} -``` - - -#### Fields - -`LocalNode` is a JSON object with the following fields. - -* `version`: `string` - CKB node version. - - Example: “version”: “0.34.0 (f37f598 2020-07-17)” - -* `node_id`: `string` - The unique node ID derived from the p2p private key. - - The private key is generated randomly on the first boot. - -* `active`: `boolean` - Whether this node is active. - - An inactive node ignores incoming p2p messages and drops outgoing messages. - -* `addresses`: `Array<` [`NodeAddress`](#type-nodeaddress) `>` - P2P addresses of this node. - - A node can have multiple addresses. - -* `protocols`: `Array<` [`LocalNodeProtocol`](#type-localnodeprotocol) `>` - Supported protocols. - -* `connections`: [`Uint64`](#type-uint64) - Count of currently connected peers. - - -### Type `LocalNodeProtocol` - -The information of a P2P protocol that is supported by the local node. - -#### Fields - -`LocalNodeProtocol` is a JSON object with the following fields. - -* `id`: [`Uint64`](#type-uint64) - Unique protocol ID. - -* `name`: `string` - Readable protocol name. - -* `support_versions`: `Array<` `string` `>` - Supported versions. - - See [Semantic Version](https://semver.org/) about how to specify a version. - - -### Type `MerkleProof` - -Proof of CKB Merkle Tree. - -CKB Merkle Tree is a [CBMT](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0006-merkle-tree/0006-merkle-tree.md) using CKB blake2b hash as the merge function. - -#### Fields - -`MerkleProof` is a JSON object with the following fields. - -* `indices`: `Array<` [`Uint32`](#type-uint32) `>` - Leaves indices in the CBMT that are proved present in the block. - - These are indices in the CBMT tree not the transaction indices in the block. - -* `lemmas`: `Array<` [`H256`](#type-h256) `>` - Hashes of all siblings along the paths to root. - - -### Type `MinerReward` - -Block rewards for miners. - -#### Fields - -`MinerReward` is a JSON object with the following fields. - -* `primary`: [`Capacity`](#type-capacity) - The primary base block reward allocated to miners. - -* `secondary`: [`Capacity`](#type-capacity) - The secondary base block reward allocated to miners. - -* `committed`: [`Capacity`](#type-capacity) - The transaction fees that are rewarded to miners because the transaction is committed in the block. - - Miners get 60% of the transaction fee for each transaction committed in the block. - -* `proposal`: [`Capacity`](#type-capacity) - The transaction fees that are rewarded to miners because the transaction is proposed in the block or its uncles. - - Miners get 40% of the transaction fee for each transaction proposed in the block and committed later in its active commit window. - - -### Type `NodeAddress` - -Node P2P address and score. - -#### Fields - -`NodeAddress` is a JSON object with the following fields. - -* `address`: `string` - P2P address. - - This is the same address used in the whitelist in ckb.toml. - - Example: “/ip4/192.168.0.2/tcp/8112/p2p/QmTRHCdrRtgUzYLNCin69zEvPvLYdxUZLLfLYyHVY3DZAS” - -* `score`: [`Uint64`](#type-uint64) - Address score. - - A higher score means a higher probability of a successful connection. - - -### Type `OutPoint` - -Reference to a cell via transaction hash and output index. - -##### Examples - - -``` -{ - "index": "0x0", - "tx_hash": "0x365698b50ca0da75dca2c87f9e7b563811d3b5813736b8cc62cc3b106faceb17" -} -``` - - -#### Fields - -`OutPoint` is a JSON object with the following fields. - -* `tx_hash`: [`H256`](#type-h256) - Transaction hash in which the cell is an output. - -* `index`: [`Uint32`](#type-uint32) - The output index of the cell in the transaction specified by `tx_hash`. - - -### Type `OutputsValidator` - -Transaction output validators that prevent common mistakes. - -`OutputsValidator` is equivalent to `"passthrough" | "well_known_scripts_only"`. - -* “passthrough”: the default validator, bypass output checking, thus allow any kind of transaction outputs. -* “well_known_scripts_only”: restricts the lock script and type script usage, see more information on [https://github.com/nervosnetwork/ckb/wiki/Transaction-%C2%BB-Default-Outputs-Validator](https://github.com/nervosnetwork/ckb/wiki/Transaction-%C2%BB-Default-Outputs-Validator) - - -### Type `PeerSyncState` - -The chain synchronization state between the local node and a remote node. - -#### Fields - -`PeerSyncState` is a JSON object with the following fields. - -* `best_known_header_hash`: [`Byte32`](#type-byte32) `|` `null` - Best known header hash of remote peer. - - This is the observed tip of the remote node’s canonical chain. - -* `best_known_header_number`: [`Uint64`](#type-uint64) `|` `null` - Best known header number of remote peer - - This is the block number of the block with the hash `best_known_header_hash`. - -* `last_common_header_hash`: [`Byte32`](#type-byte32) `|` `null` - Last common header hash of remote peer. - - This is the common ancestor of the local node canonical chain tip and the block `best_known_header_hash`. - -* `last_common_header_number`: [`Uint64`](#type-uint64) `|` `null` - Last common header number of remote peer. - - This is the block number of the block with the hash `last_common_header_hash`. - -* `unknown_header_list_size`: [`Uint64`](#type-uint64) - The total size of unknown header list. - - **Deprecated**: this is an internal state and will be removed in a future release. - -* `inflight_count`: [`Uint64`](#type-uint64) - The count of concurrency downloading blocks. - -* `can_fetch_count`: [`Uint64`](#type-uint64) - The count of blocks are available for concurrency download. - - -### Type `PoolTransactionEntry` - -The transaction entry in the pool. - -#### Fields - -`PoolTransactionEntry` is a JSON object with the following fields. - -* `transaction`: [`TransactionView`](#type-transactionview) - The transaction. - -* `cycles`: [`Cycle`](#type-cycle) - Consumed cycles. - -* `size`: [`Uint64`](#type-uint64) - The transaction serialized size in block. - -* `fee`: [`Capacity`](#type-capacity) - The transaction fee. - -* `timestamp`: [`Uint64`](#type-uint64) - The unix timestamp when entering the Txpool, unit: Millisecond - - -### Type `PoolTransactionReject` - -TX reject message - -`PoolTransactionReject` is a JSON object with following fields. - -* `type`: `"LowFeeRate" | "ExceededMaximumAncestorsCount" | "ExceededTransactionSizeLimit" | "Full" | "Duplicated" | "Malformed" | "DeclaredWrongCycles" | "Resolve" | "Verification" | "Expiry" | "RBFRejected"` - Reject type. -* `description`: `string` - Detailed description about why the transaction is rejected. - -Different reject types: - -* `LowFeeRate`: Transaction fee lower than config -* `ExceededMaximumAncestorsCount`: Transaction exceeded maximum ancestors count limit -* `ExceededTransactionSizeLimit`: Transaction exceeded maximum size limit -* `Full`: Transaction are replaced because the pool is full -* `Duplicated`: Transaction already exists in transaction_pool -* `Malformed`: Malformed transaction -* `DeclaredWrongCycles`: Declared wrong cycles -* `Resolve`: Resolve failed -* `Verification`: Verification failed -* `Expiry`: Transaction expired -* `RBFRejected`: RBF rejected - - -### Type `PoolTxDetailInfo` - -A Tx details info in tx-pool. - -#### Fields - -`PoolTxDetailInfo` is a JSON object with the following fields. - -* `timestamp`: [`Uint64`](#type-uint64) - The time added into tx-pool - -* `entry_status`: `string` - The detailed status in tx-pool, `pending`, `gap`, `proposed` - -* `rank_in_pending`: [`Uint64`](#type-uint64) - The rank in pending, starting from 0 - -* `pending_count`: [`Uint64`](#type-uint64) - The pending(`pending` and `gap`) count - -* `proposed_count`: [`Uint64`](#type-uint64) - The proposed count - -* `descendants_count`: [`Uint64`](#type-uint64) - The descendants count of tx - -* `ancestors_count`: [`Uint64`](#type-uint64) - The ancestors count of tx - -* `score_sortkey`: [`AncestorsScoreSortKey`](#type-ancestorsscoresortkey) - The score key details, useful to debug - - -### Type `ProposalShortId` - -The 10-byte fixed-length binary encoded as a 0x-prefixed hex string in JSON. - -##### Example - - -``` -0xa0ef4eb5f4ceeb08a4c8 -``` - - -### Type `ProposalWindow` - -Two protocol parameters `closest` and `farthest` define the closest and farthest on-chain distance between a transaction’s proposal and commitment. - -A non-cellbase transaction is committed at height h_c if all of the following conditions are met: - -* it is proposed at height h_p of the same chain, where w_close <= h_c − h_p <= w_far ; - -* it is in the commitment zone of the main chain block with height h_c ; - - -``` - ProposalWindow { closest: 2, farthest: 10 } - propose - \ - \ - 13 14 [15 16 17 18 19 20 21 22 23] - \_______________________/ - \ - commit -``` - - -#### Fields - -`ProposalWindow` is a JSON object with the following fields. - -* `closest`: [`BlockNumber`](#type-blocknumber) - The closest distance between the proposal and the commitment. - -* `farthest`: [`BlockNumber`](#type-blocknumber) - The farthest distance between the proposal and the commitment. - - -### Type `Ratio` - -Represents the ratio `numerator / denominator`, where `numerator` and `denominator` are both unsigned 64-bit integers. - -#### Fields - -`Ratio` is a JSON object with the following fields. - -* `numer`: [`Uint64`](#type-uint64) - Numerator. - -* `denom`: [`Uint64`](#type-uint64) - Denominator. - - -### Type `RationalU256` - -The ratio which numerator and denominator are both 256-bit unsigned integers. - -#### Example - -``` -{ - "denom": "0x28", - "numer": "0x1" -} -``` - - -### Type `RawTxPool` - -All transactions in tx-pool. - -`RawTxPool` is equivalent to [`TxPoolIds`](#type-txpoolids) `|` [`TxPoolEntries`](#type-txpoolentries). - -### Type `RemoteNode` - -Information of a remote node. - -A remote node connects to the local node via the P2P network. It is often called a peer. - -##### Examples - - -``` -{ - "addresses": [ - { - "address": "/ip6/::ffff:18.185.102.19/tcp/8115/p2p/QmXwUgF48ULy6hkgfqrEwEfuHW7WyWyWauueRDAYQHNDfN", - "score": "0x64" - }, - { - "address": "/ip4/18.185.102.19/tcp/8115/p2p/QmXwUgF48ULy6hkgfqrEwEfuHW7WyWyWauueRDAYQHNDfN", - "score": "0x64" - } - ], - "connected_duration": "0x2f", - "is_outbound": true, - "last_ping_duration": "0x1a", - "node_id": "QmXwUgF48ULy6hkgfqrEwEfuHW7WyWyWauueRDAYQHNDfN", - "protocols": [ - { - "id": "0x4", - "version": "0.0.1" - }, - { - "id": "0x2", - "version": "0.0.1" - }, - { - "id": "0x1", - "version": "0.0.1" - }, - { - "id": "0x64", - "version": "1" - }, - { - "id": "0x6e", - "version": "1" - }, - { - "id": "0x66", - "version": "1" - }, - { - "id": "0x65", - "version": "1" - }, - { - "id": "0x0", - "version": "0.0.1" - } - ], - "sync_state": { - "best_known_header_hash": null, - "best_known_header_number": null, - "can_fetch_count": "0x80", - "inflight_count": "0xa", - "last_common_header_hash": null, - "last_common_header_number": null, - "unknown_header_list_size": "0x20" - }, - "version": "0.34.0 (f37f598 2020-07-17)" -} -``` - - -#### Fields - -`RemoteNode` is a JSON object with the following fields. - -* `version`: `string` - The remote node version. - -* `node_id`: `string` - The remote node ID which is derived from its P2P private key. - -* `addresses`: `Array<` [`NodeAddress`](#type-nodeaddress) `>` - The remote node addresses. - -* `is_outbound`: `boolean` - Whether this is an outbound remote node. - - If the connection is established by the local node, `is_outbound` is true. - -* `connected_duration`: [`Uint64`](#type-uint64) - Elapsed time in milliseconds since the remote node is connected. - -* `last_ping_duration`: [`Uint64`](#type-uint64) `|` `null` - Elapsed time in milliseconds since receiving the ping response from this remote node. - - Null means no ping responses have been received yet. - -* `sync_state`: [`PeerSyncState`](#type-peersyncstate) `|` `null` - Chain synchronization state. - - Null means chain sync has not started with this remote node yet. - -* `protocols`: `Array<` [`RemoteNodeProtocol`](#type-remotenodeprotocol) `>` - Active protocols. - - CKB uses Tentacle multiplexed network framework. Multiple protocols are running simultaneously in the connection. - - -### Type `RemoteNodeProtocol` - -The information about an active running protocol. - -#### Fields - -`RemoteNodeProtocol` is a JSON object with the following fields. - -* `id`: [`Uint64`](#type-uint64) - Unique protocol ID. - -* `version`: `string` - Active protocol version. - - -### Type `ResponseFormat` - -This is a wrapper for JSON serialization to select the format between Json and Hex. - -##### Examples - -`ResponseFormat` returns the block in its Json format or molecule serialized Hex format. - -#### Fields - -`ResponseFormat` is a JSON object with the following fields. - -* `inner`: [`Either`](#type-either) - The inner value. - - -### Type `Script` - -Describes the lock script and type script for a cell. - -##### Examples - - -``` -{ - "code_hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5", - "hash_type": "data", - "args": "0x" -} -``` - - -#### Fields - -`Script` is a JSON object with the following fields. - -* `code_hash`: [`H256`](#type-h256) - The hash used to match the script code. - -* `hash_type`: [`ScriptHashType`](#type-scripthashtype) - Specifies how to use the `code_hash` to match the script code. - -* `args`: [`JsonBytes`](#type-jsonbytes) - Arguments for script. - - -### Type `ScriptHashType` - -Specifies how the script `code_hash` is used to match the script code and how to run the code. - -Allowed kinds: “data”, “type”, “data1” and “data2” - -Refer to the section [Code Locating](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md#code-locating) and [Upgradable Script](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md#upgradable-script) in the RFC *CKB Transaction Structure*. - -The hash type is split into the high 7 bits and the low 1 bit, when the low 1 bit is 1, it indicates the type, when the low 1 bit is 0, it indicates the data, and then it relies on the high 7 bits to indicate that the data actually corresponds to the version. - -`ScriptHashType` is equivalent to `"data" | "type" | "data1" | "data2"`. - -* Type “data” matches script code via cell data hash, and run the script code in v0 CKB VM. -* Type “type” matches script code via cell type script hash. -* Type “data1” matches script code via cell data hash, and run the script code in v1 CKB VM. -* Type “data2” matches script code via cell data hash, and run the script code in v2 CKB VM. - - -### Type `SerializedBlock` - -This is a 0x-prefix hex string. It is the block serialized by molecule using the schema `table Block`. - -### Type `SerializedHeader` - -This is a 0x-prefix hex string. It is the block header serialized by molecule using the schema `table Header`. - -### Type `SoftFork` - -SoftFork information - -`SoftFork` is equivalent to `"buried" | "rfc0043"`. - -* buried - the activation epoch is hard-coded into the client implementation -* rfc0043 - the activation is controlled by rfc0043 signaling - - -### Type `Status` - -Status for transaction - -`Status` is equivalent to `"pending" | "proposed" | "committed" | "unknown" | "rejected"`. - -* Status “pending”. The transaction is in the pool, and not proposed yet. -* Status “proposed”. The transaction is in the pool and has been proposed. -* Status “committed”. The transaction has been committed to the canonical chain. -* Status “unknown”. The node has not seen the transaction, or it should be rejected but was cleared due to storage limitations. -* Status “rejected”. The transaction has been recently removed from the pool. Due to storage limitations, the node can only hold the most recently removed transactions. - - -### Type `SyncState` - -The overall chain synchronization state of this local node. - -#### Fields - -`SyncState` is a JSON object with the following fields. - -* `ibd`: `boolean` - Whether the local node is in IBD, Initial Block Download. - - When a node starts and its chain tip timestamp is far behind the wall clock, it will enter the IBD until it catches up the synchronization. - - During IBD, the local node only synchronizes the chain with one selected remote node and stops responding to most P2P requests. - -* `best_known_block_number`: [`BlockNumber`](#type-blocknumber) - This is the best known block number observed by the local node from the P2P network. - - The best here means that the block leads a chain which has the best known accumulated difficulty. - - This can be used to estimate the synchronization progress. If this RPC returns B, and the RPC `get_tip_block_number` returns T, the node has already synchronized T/B blocks. - -* `best_known_block_timestamp`: [`Timestamp`](#type-timestamp) - This is timestamp of the same block described in `best_known_block_number`. - -* `orphan_blocks_count`: [`Uint64`](#type-uint64) - Count of orphan blocks the local node has downloaded. - - The local node downloads multiple blocks simultaneously but blocks must be connected consecutively. If a descendant is downloaded before its ancestors, it becomes an orphan block. - - If this number is too high, it indicates that block download has stuck at some block. - -* `inflight_blocks_count`: [`Uint64`](#type-uint64) - Count of downloading blocks. - -* `fast_time`: [`Uint64`](#type-uint64) - The download scheduler’s time analysis data, the fast is the 1/3 of the cut-off point, unit ms - -* `normal_time`: [`Uint64`](#type-uint64) - The download scheduler’s time analysis data, the normal is the 4/5 of the cut-off point, unit ms - -* `low_time`: [`Uint64`](#type-uint64) - The download scheduler’s time analysis data, the low is the 9/10 of the cut-off point, unit ms - - -### Type `Timestamp` - -The Unix timestamp in milliseconds (1 second is 1000 milliseconds). - -For example, 1588233578000 is Thu, 30 Apr 2020 07:59:38 +0000 - -This is a 64-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint64](#type-uint64). - -### Type `Transaction` - -The transaction. - -Refer to RFC [CKB Transaction Structure](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md). - -#### Fields - -`Transaction` is a JSON object with the following fields. - -* `version`: [`Version`](#type-version) - Reserved for future usage. It must equal 0 in current version. +```json + { + "cell_deps": [ + { + "dep_type": "code", + "out_point": { + "index": "0x0", + "tx_hash": "0xa4037a893eb48e18ed4ef61034ce26eba9c585f15c9cee102ae58505565eccc3" + } + } + ], + "hash": "0xa0ef4eb5f4ceeb08a4c8524d84c5da95dce2f608e0ca2ec8091191b0f330c6e3", + "header_deps": [ + "0x7978ec7ce5b507cfb52e149e36b1a23f6062ed150503c85bbf825da3599095ed" + ], + "inputs": [ + { + "previous_output": { + "index": "0x0", + "tx_hash": "0x365698b50ca0da75dca2c87f9e7b563811d3b5813736b8cc62cc3b106faceb17" + }, + "since": "0x0" + } + ], + "outputs": [ + { + "capacity": "0x2540be400", + "lock": { + "code_hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5", + "hash_type": "data", + "args": "0x" + }, + "type": null + } + ], + "outputs_data": [ + "0x" + ], + "version": "0x0", + "witnesses": [] + } +``` -* `cell_deps`: `Array<` [`CellDep`](#type-celldep) `>` - An array of cell deps. +#### Fields: +* `cell_deps`: `Array<` [`CellDep`](#type-celldep) `>` - An array of cell deps. CKB locates lock script and type script code via cell deps. The script also can use syscalls to read the cells here. Unlike inputs, the live cells can be used as cell deps in multiple transactions. -* `header_deps`: `Array<` [`H256`](#type-h256) `>` - An array of header deps. +* `hash`: [`H256`](#type-h256) - The transaction hash. + +* `header_deps`: `Array<` [`H256`](#type-h256) `>` - An array of header deps. The block must already be in the canonical chain. Lock script and type script can read the header information of blocks listed here. -* `inputs`: `Array<` [`CellInput`](#type-cellinput) `>` - An array of input cells. +* `inputs`: `Array<` [`CellInput`](#type-cellinput) `>` - An array of input cells. In the canonical chain, any cell can only appear as an input once. -* `outputs`: `Array<` [`CellOutput`](#type-celloutput) `>` - An array of output cells. +* `outputs`: `Array<` [`CellOutput`](#type-celloutput) `>` - An array of output cells. -* `outputs_data`: `Array<` [`JsonBytes`](#type-jsonbytes) `>` - Output cells data. +* `outputs_data`: `Array<` [`JsonBytes`](#type-jsonbytes) `>` - Output cells data. This is a parallel array of outputs. The cell capacity, lock, and type of the output i is `outputs[i]` and its data is `outputs_data[i]`. -* `witnesses`: `Array<` [`JsonBytes`](#type-jsonbytes) `>` - An array of variable-length binaries. +* `version`: [`AlertId`](#type-alertid) - Reserved for future usage. It must equal 0 in current version. + +* `witnesses`: `Array<` [`JsonBytes`](#type-jsonbytes) `>` - An array of variable-length binaries. Lock script and type script can read data here to verify the transaction. For example, the bundled secp256k1 lock script requires storing the signature in `witnesses`. - -### Type `TransactionAndWitnessProof` - -Merkle proof for transactions’ witnesses in a block. - -#### Fields - -`TransactionAndWitnessProof` is a JSON object with the following fields. - -* `block_hash`: [`H256`](#type-h256) - Block hash - -* `transactions_proof`: [`MerkleProof`](#type-merkleproof) - Merkle proof of all transactions’ hash - -* `witnesses_proof`: [`MerkleProof`](#type-merkleproof) - Merkle proof of transactions’ witnesses - - -### Type `TransactionProof` - -Merkle proof for transactions in a block. - -#### Fields - -`TransactionProof` is a JSON object with the following fields. - -* `block_hash`: [`H256`](#type-h256) - Block hash - -* `witnesses_root`: [`H256`](#type-h256) - Merkle root of all transactions’ witness hash - -* `proof`: [`MerkleProof`](#type-merkleproof) - Merkle proof of all transactions’ hash - - -### Type `TransactionTemplate` - -Transaction template which is ready to be committed in the new block. - -#### Fields - -`TransactionTemplate` is a JSON object with the following fields. - -* `hash`: [`H256`](#type-h256) - Transaction hash. - -* `required`: `boolean` - Whether miner must include this transaction in the new block. - -* `cycles`: [`Cycle`](#type-cycle) `|` `null` - The hint of how many cycles this transaction consumes. - - Miners can utilize this field to ensure that the total cycles do not exceed the limit while selecting transactions. - -* `depends`: `Array<` [`Uint64`](#type-uint64) `>` `|` `null` - Transaction dependencies. - - This is a hint to help miners selecting transactions. - - This transaction can only be committed if its dependencies are also committed in the new block. - - This field is a list of indices into the array `transactions` in the block template. - - For example, `depends = [1, 2]` means this transaction depends on `block_template.transactions[1]` and `block_template.transactions[2]`. - -* `data`: [`Transaction`](#type-transaction) - The transaction. - - Miners must keep it unchanged when including it in the new block. - - -### Type `TransactionView` - -The JSON view of a Transaction. - -This structure is serialized into a JSON object with field `hash` and all the fields in [`Transaction`](#type-transaction). - -##### Examples - - -``` -{ - "cell_deps": [ - { - "dep_type": "code", - "out_point": { - "index": "0x0", - "tx_hash": "0xa4037a893eb48e18ed4ef61034ce26eba9c585f15c9cee102ae58505565eccc3" - } - } - ], - "hash": "0xa0ef4eb5f4ceeb08a4c8524d84c5da95dce2f608e0ca2ec8091191b0f330c6e3", - "header_deps": [ - "0x7978ec7ce5b507cfb52e149e36b1a23f6062ed150503c85bbf825da3599095ed" - ], - "inputs": [ - { - "previous_output": { - "index": "0x0", - "tx_hash": "0x365698b50ca0da75dca2c87f9e7b563811d3b5813736b8cc62cc3b106faceb17" - }, - "since": "0x0" - } - ], - "outputs": [ - { - "capacity": "0x2540be400", - "lock": { - "code_hash": "0x28e83a1277d48add8e72fadaa9248559e1b632bab2bd60b27955ebc4c03800a5", - "hash_type": "data", - "args": "0x" - }, - "type": null - } - ], - "outputs_data": [ - "0x" - ], - "version": "0x0", - "witnesses": [] -} -``` - - -#### Fields - -`TransactionView` is a JSON object with the following fields. - -* `inner`: [`Transaction`](#type-transaction) - All the fields in `Transaction` are included in `TransactionView` in JSON. - -* `hash`: [`H256`](#type-h256) - The transaction hash. - - ### Type `TransactionWithStatusResponse` - The JSON view of a transaction as well as its status. -#### Fields - -`TransactionWithStatusResponse` is a JSON object with the following fields. - -* `transaction`: [`ResponseFormat`](#type-responseformat) `|` `null` - The transaction. - -* `cycles`: [`Cycle`](#type-cycle) `|` `null` - The transaction consumed cycles. - -* `time_added_to_pool`: [`Uint64`](#type-uint64) `|` `null` - If the transaction is in tx-pool, `time_added_to_pool` represent when it enters the tx-pool. unit: Millisecond - -* `tx_status`: [`TxStatus`](#type-txstatus) - The Transaction status. - -* `fee`: [`Capacity`](#type-capacity) `|` `null` - The transaction fee of the transaction - -* `min_replace_fee`: [`Capacity`](#type-capacity) `|` `null` - The minimal fee required to replace this transaction - +#### Fields: +* `tx_status`: [`TxStatus`](#type-txstatus) - The Transaction status. ### Type `TxPoolEntries` - Tx-pool entries object -#### Fields - -`TxPoolEntries` is a JSON object with the following fields. - -* `pending`: `{ [ key:` [`H256`](#type-h256) `]: ` [`TxPoolEntry`](#type-txpoolentry) `}` - Pending tx verbose info - -* `proposed`: `{ [ key:` [`H256`](#type-h256) `]: ` [`TxPoolEntry`](#type-txpoolentry) `}` - Proposed tx verbose info +#### Fields: +* `pending`: `object` - Pending tx verbose info +* `proposed`: `object` - Proposed tx verbose info ### Type `TxPoolEntry` - Transaction entry info -#### Fields +#### Fields: +* `ancestors_count`: [`Uint64`](#type-uint64) - Number of in-tx-pool ancestor transactions -`TxPoolEntry` is a JSON object with the following fields. +* `ancestors_cycles`: [`Uint64`](#type-uint64) - Cycles of in-tx-pool ancestor transactions -* `cycles`: [`Uint64`](#type-uint64) - Consumed cycles. +* `ancestors_size`: [`Uint64`](#type-uint64) - Size of in-tx-pool ancestor transactions -* `size`: [`Uint64`](#type-uint64) - The transaction serialized size in block. +* `cycles`: [`Uint64`](#type-uint64) - Consumed cycles. -* `fee`: [`Capacity`](#type-capacity) - The transaction fee. +* `fee`: [`Uint64`](#type-uint64) - The transaction fee. -* `ancestors_size`: [`Uint64`](#type-uint64) - Size of in-tx-pool ancestor transactions - -* `ancestors_cycles`: [`Uint64`](#type-uint64) - Cycles of in-tx-pool ancestor transactions - -* `ancestors_count`: [`Uint64`](#type-uint64) - Number of in-tx-pool ancestor transactions - -* `timestamp`: [`Uint64`](#type-uint64) - The unix timestamp when entering the Txpool, unit: Millisecond +* `size`: [`Uint64`](#type-uint64) - The transaction serialized size in block. +* `timestamp`: [`Uint64`](#type-uint64) - The unix timestamp when entering the Txpool, unit: Millisecond ### Type `TxPoolIds` - Array of transaction ids -#### Fields - -`TxPoolIds` is a JSON object with the following fields. - -* `pending`: `Array<` [`H256`](#type-h256) `>` - Pending transaction ids - -* `proposed`: `Array<` [`H256`](#type-h256) `>` - Proposed transaction ids +#### Fields: +* `pending`: `Array<` [`H256`](#type-h256) `>` - Pending transaction ids +* `proposed`: `Array<` [`H256`](#type-h256) `>` - Proposed transaction ids ### Type `TxPoolInfo` - Transaction pool information. -#### Fields +#### Fields: +* `last_txs_updated_at`: [`Uint64`](#type-uint64) - Last updated time. This is the Unix timestamp in milliseconds. -`TxPoolInfo` is a JSON object with the following fields. +* `max_tx_pool_size`: [`Uint64`](#type-uint64) - Total limit on the size of transactions in the tx-pool -* `tip_hash`: [`H256`](#type-h256) - The associated chain tip block hash. +* `min_fee_rate`: [`Uint64`](#type-uint64) - Fee rate threshold. The pool rejects transactions which fee rate is below this threshold. - The transaction pool is stateful. It manages the transactions which are valid to be committed after this block. - -* `tip_number`: [`BlockNumber`](#type-blocknumber) - The block number of the block `tip_hash`. - -* `pending`: [`Uint64`](#type-uint64) - Count of transactions in the pending state. + The unit is Shannons per 1000 bytes transaction serialization size in the block. - The pending transactions must be proposed in a new block first. +* `min_rbf_rate`: [`Uint64`](#type-uint64) - RBF rate threshold. -* `proposed`: [`Uint64`](#type-uint64) - Count of transactions in the proposed state. + The pool reject to replace for transactions which fee rate is below this threshold. if min_rbf_rate > min_fee_rate then RBF is enabled on the node. - The proposed transactions are ready to be committed in the new block after the block `tip_hash`. + The unit is Shannons per 1000 bytes transaction serialization size in the block. -* `orphan`: [`Uint64`](#type-uint64) - Count of orphan transactions. +* `orphan`: [`Uint64`](#type-uint64) - Count of orphan transactions. An orphan transaction has an input cell from the transaction which is neither in the chain nor in the transaction pool. -* `total_tx_size`: [`Uint64`](#type-uint64) - Total count of transactions in the pool of all the different kinds of states (excluding orphan transactions). +* `pending`: [`Uint64`](#type-uint64) - Count of transactions in the pending state. -* `total_tx_cycles`: [`Uint64`](#type-uint64) - Total consumed VM cycles of all the transactions in the pool (excluding orphan transactions). + The pending transactions must be proposed in a new block first. -* `min_fee_rate`: [`Uint64`](#type-uint64) - Fee rate threshold. The pool rejects transactions which fee rate is below this threshold. +* `proposed`: [`Uint64`](#type-uint64) - Count of transactions in the proposed state. - The unit is Shannons per 1000 bytes transaction serialization size in the block. + The proposed transactions are ready to be committed in the new block after the block `tip_hash`. -* `min_rbf_rate`: [`Uint64`](#type-uint64) - RBF rate threshold. The pool reject to replace for transactions which fee rate is below this threshold. if min_rbf_rate > min_fee_rate then RBF is enabled on the node. +* `tip_hash`: [`H256`](#type-h256) - The associated chain tip block hash. - The unit is Shannons per 1000 bytes transaction serialization size in the block. + The transaction pool is stateful. It manages the transactions which are valid to be committed after this block. -* `last_txs_updated_at`: [`Timestamp`](#type-timestamp) - Last updated time. This is the Unix timestamp in milliseconds. +* `tip_number`: [`Uint64`](#type-uint64) - The block number of the block `tip_hash`. -* `tx_size_limit`: [`Uint64`](#type-uint64) - Limiting transactions to tx_size_limit +* `total_tx_cycles`: [`Uint64`](#type-uint64) - Total consumed VM cycles of all the transactions in the pool (excluding orphan transactions). - Transactions with a large size close to the block size limit may not be packaged, because the block header and cellbase are occupied, so the tx-pool is limited to accepting transaction up to tx_size_limit. +* `total_tx_size`: [`Uint64`](#type-uint64) - Total count of transactions in the pool of all the different kinds of states (excluding orphan transactions). -* `max_tx_pool_size`: [`Uint64`](#type-uint64) - Total limit on the size of transactions in the tx-pool +* `tx_size_limit`: [`Uint64`](#type-uint64) - Limiting transactions to tx_size_limit + Transactions with a large size close to the block size limit may not be packaged, because the block header and cellbase are occupied, so the tx-pool is limited to accepting transaction up to tx_size_limit. ### Type `TxStatus` - Transaction status and the block hash if it is committed. -#### Fields - -`TxStatus` is a JSON object with the following fields. - -* `status`: [`Status`](#type-status) - The transaction status, allowed values: “pending”, “proposed” “committed” “unknown” and “rejected”. - -* `block_number`: [`BlockNumber`](#type-blocknumber) `|` `null` - The block number of the block which has committed this transaction in the canonical chain. - -* `block_hash`: [`H256`](#type-h256) `|` `null` - The block hash of the block which has committed this transaction in the canonical chain. - -* `reason`: `string` `|` `null` - The reason why the transaction is rejected - - -### Type `U256` - -The 256-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. +#### Fields: +* `status`: [`Status`](#type-status) - The transaction status, allowed values: "pending", "proposed" "committed" "unknown" and "rejected". ### Type `Uint128` - -The 128-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. - -##### Examples - - -| JSON | Decimal Value | -| --- |--- | -| “0x0” | 0 | -| “0x10” | 16 | -| “10” | Invalid, 0x is required | -| “0x01” | Invalid, redundant leading 0 | - - -### Type `Uint32` - -The 32-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. - -##### Examples - - -| JSON | Decimal Value | -| --- |--- | -| “0x0” | 0 | -| “0x10” | 16 | -| “10” | Invalid, 0x is required | -| “0x01” | Invalid, redundant leading 0 | - +`Uint128` is `uint128` ### Type `Uint64` - -The 64-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. - -##### Examples - - -| JSON | Decimal Value | -| --- |--- | -| “0x0” | 0 | -| “0x10” | 16 | -| “10” | Invalid, 0x is required | -| “0x01” | Invalid, redundant leading 0 | - +`Uint64` is `uint64` ### Type `UncleBlock` - The uncle block used as a parameter in the RPC. The chain stores only the uncle block header and proposal IDs. The header ensures the block is covered by PoW and can pass the consensus rules on uncle blocks. Proposal IDs are there because a block can commit transactions proposed in an uncle. A block B1 is considered to be the uncle of another block B2 if all the following conditions are met: -* They are in the same epoch, sharing the same difficulty; +1. They are in the same epoch, sharing the same difficulty; +2. B2 block number is larger than B1; +3. B1's parent is either B2's ancestor or an uncle embedded in B2 or any of B2's ancestors. +4. B2 is the first block in its chain to refer to B1. -* B2 block number is larger than B1; +#### Fields: +* `header`: [`Header`](#type-header) - The uncle block header. -* B1’s parent is either B2’s ancestor or an uncle embedded in B2 or any of B2’s ancestors. +* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - Proposal IDs in the uncle block body. -* B2 is the first block in its chain to refer to B1. +### Type `UncleBlockView` +The uncle block. + +The chain stores only the uncle block header and proposal IDs. The header ensures the block is covered by PoW and can pass the consensus rules on uncle blocks. Proposal IDs are there because a block can commit transactions proposed in an uncle. -#### Fields +A block B1 is considered to be the uncle of another block B2 if all the following conditions are met: -`UncleBlock` is a JSON object with the following fields. +1. They are in the same epoch, sharing the same difficulty; +2. B2 block number is larger than B1; +3. B1's parent is either B2's ancestor or an uncle embedded in B2 or any of B2's ancestors. +4. B2 is the first block in its chain to refer to B1. -* `header`: [`Header`](#type-header) - The uncle block header. +#### Fields: +* `header`: [`HeaderView`](#type-headerview) - The uncle block header. -* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - Proposal IDs in the uncle block body. +* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - Proposal IDs in the uncle block body. +### Type `UncleTemplate` +The uncle block template of the new block for miners. -### Type `UncleBlockView` +#### Fields: +* `hash`: [`H256`](#type-h256) - The uncle block hash. -The uncle block. +* `header`: [`Header`](#type-header) - The header of the uncle block. -The chain stores only the uncle block header and proposal IDs. The header ensures the block is covered by PoW and can pass the consensus rules on uncle blocks. Proposal IDs are there because a block can commit transactions proposed in an uncle. + Miners must keep this unchanged when including this uncle in the new block. -A block B1 is considered to be the uncle of another block B2 if all the following conditions are met: +* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - The proposals of the uncle block. -* They are in the same epoch, sharing the same difficulty; + Miners must keep this unchanged when including this uncle in the new block. -* B2 block number is larger than B1; +* `required`: `boolean` - Whether miners must include this uncle in the submit block. -* B1’s parent is either B2’s ancestor or an uncle embedded in B2 or any of B2’s ancestors. -* B2 is the first block in its chain to refer to B1. +## RPC Errors +CKB RPC error codes. -#### Fields +CKB RPC follows the JSON RPC specification about the [error object](https://www.jsonrpc.org/specification#error_object). -`UncleBlockView` is a JSON object with the following fields. +Besides the pre-defined errors, all CKB defined errors are listed here. -* `header`: [`HeaderView`](#type-headerview) - The uncle block header. +Here is a reference to the pre-defined errors: -* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - Proposal IDs in the uncle block body. +| code | message | meaning | +| ---------------- | ---------------- | -------------------------------------------------- | +| -32700 | Parse error | Invalid JSON was received by the server. | +| -32600 | Invalid Request | The JSON sent is not a valid Request object. | +| -32601 | Method not found | The method does not exist / is not available. | +| -32602 | Invalid params | Invalid method parameter(s). | +| -32603 | Internal error | Internal JSON-RPC error. | +| -32000 to -32099 | Server error | Reserved for implementation-defined server-errors. | +CKB application-defined errors follow some patterns to assign the codes: -### Type `UncleTemplate` +* -1 ~ -999 are general errors +* -1000 ~ -2999 are module-specific errors. Each module generally gets 100 reserved error codes. -The uncle block template of the new block for miners. +Unless otherwise noted, all the errors return optional detailed information as `string` in the error object `data` field. + +### ERROR `CKBInternalError` +(-1): CKB internal errors are considered to never happen or only happen when the system resources are exhausted. +### ERROR `Deprecated` +(-2): The CKB method has been deprecated and disabled. -#### Fields +Set `rpc.enable_deprecated_rpc` to `true` in the config file to enable all deprecated methods. +### ERROR `Invalid` +(-3): Error code -3 is no longer used. -`UncleTemplate` is a JSON object with the following fields. +Before v0.35.0, CKB returns all RPC errors using the error code -3. CKB no longer uses +-3 since v0.35.0. +### ERROR `RPCModuleIsDisabled` +(-4): The RPC method is not enabled. -* `hash`: [`H256`](#type-h256) - The uncle block hash. +CKB groups RPC methods into modules, and a method is enabled only when the module is explicitly enabled in the config file. +### ERROR `DaoError` +(-5): DAO related errors. +### ERROR `IntegerOverflow` +(-6): Integer operation overflow. +### ERROR `ConfigError` +(-7): The error is caused by a config file option. -* `required`: `boolean` - Whether miners must include this uncle in the submit block. +Users have to edit the config file to fix the error. +### ERROR `P2PFailedToBroadcast` +(-101): The CKB local node failed to broadcast a message to its peers. +### ERROR `DatabaseError` +(-200): Internal database error. -* `proposals`: `Array<` [`ProposalShortId`](#type-proposalshortid) `>` - The proposals of the uncle block. +The CKB node persists data to the database. This is the error from the underlying database module. +### ERROR `ChainIndexIsInconsistent` +(-201): The chain index is inconsistent. - Miners must keep this unchanged when including this uncle in the new block. +An example of an inconsistent index is that the chain index says a block hash is in the chain but the block cannot be read from the database. -* `header`: [`Header`](#type-header) - The header of the uncle block. +This is a fatal error usually due to a serious bug. Please back up the data directory and re-sync the chain from scratch. +### ERROR `DatabaseIsCorrupt` +(-202): The underlying database is corrupt. - Miners must keep this unchanged when including this uncle in the new block. +This is a fatal error usually caused by the underlying database used by CKB. Please back up the data directory and re-sync the chain from scratch. +### ERROR `TransactionFailedToResolve` +(-301): Failed to resolve the referenced cells and headers used in the transaction, as inputs or dependencies. +### ERROR `TransactionFailedToVerify` +(-302): Failed to verify the transaction. +### ERROR `AlertFailedToVerifySignatures` +(-1000): Some signatures in the submit alert are invalid. +### ERROR `PoolRejectedTransactionByOutputsValidator` +(-1102): The transaction is rejected by the outputs validator specified by the RPC parameter. +### ERROR `PoolRejectedTransactionByIllTransactionChecker` +(-1103): Pool rejects some transactions which seem contain invalid VM instructions. See the issue link in the error message for details. +### ERROR `PoolRejectedTransactionByMinFeeRate` +(-1104): The transaction fee rate must be greater than or equal to the config option `tx_pool.min_fee_rate` +The fee rate is calculated as: -### Type `Version` +```text + fee / (1000 * tx_serialization_size_in_block_in_bytes) +``` +### ERROR `PoolRejectedTransactionByMaxAncestorsCountLimit` +(-1105): The in-pool ancestors count must be less than or equal to the config option `tx_pool.max_ancestors_count` -The simple increasing integer version. +Pool rejects a large package of chained transactions to avoid certain kinds of DoS attacks. +### ERROR `PoolIsFull` +(-1106): The transaction is rejected because the pool has reached its limit. +### ERROR `PoolRejectedDuplicatedTransaction` +(-1107): The transaction is already in the pool. +### ERROR `PoolRejectedMalformedTransaction` +(-1108): The transaction is rejected because it does not make sense in the context. -This is a 32-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint32](#type-uint32). +For example, a cellbase transaction is not allowed in `send_transaction` RPC. +### ERROR `TransactionExpired` +(-1109): The transaction is expired from tx-pool after `expiry_hours`. +### ERROR `PoolRejectedTransactionBySizeLimit` +(-1110): The transaction exceeded maximum size limit. +### ERROR `PoolRejectedRBF` +(-1111): The transaction is rejected for RBF checking. +### ERROR `Indexer` +(-1200): The indexer error. \ No newline at end of file diff --git a/rpc/src/error.rs b/rpc/src/error.rs index 184e181c94..c030d83155 100644 --- a/rpc/src/error.rs +++ b/rpc/src/error.rs @@ -1,6 +1,7 @@ use ckb_error::{AnyError, Error as CKBError, ErrorKind, InternalError, InternalErrorKind}; use ckb_tx_pool::error::Reject; use jsonrpc_core::{Error, ErrorCode, Value}; +use schemars::JsonSchema; use std::fmt::{Debug, Display}; /// CKB RPC error codes. @@ -28,7 +29,7 @@ use std::fmt::{Debug, Display}; /// /// Unless otherwise noted, all the errors return optional detailed information as `string` in the error /// object `data` field. -#[derive(Debug, PartialEq, Clone, Copy, Eq)] +#[derive(Debug, PartialEq, Clone, Copy, Eq, JsonSchema)] pub enum RPCError { /// (-1): CKB internal errors are considered to never happen or only happen when the system /// resources are exhausted. diff --git a/rpc/src/module/alert.rs b/rpc/src/module/alert.rs index f75bc6014c..959ea2e3ee 100644 --- a/rpc/src/module/alert.rs +++ b/rpc/src/module/alert.rs @@ -17,7 +17,7 @@ use std::sync::Arc; /// /// The alerts must be signed by 2-of-4 signatures, where the public keys are hard-coded in the source code /// and belong to early CKB developers. -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait AlertRpc { /// Sends an alert. diff --git a/rpc/src/module/chain.rs b/rpc/src/module/chain.rs index f4ebec4fb4..da56b00c66 100644 --- a/rpc/src/module/chain.rs +++ b/rpc/src/module/chain.rs @@ -43,7 +43,7 @@ use std::sync::Arc; /// ## Chain Reorganization /// /// Chain Reorganization happens when CKB found a chain that has accumulated more work than the -/// canonical chain. The reorganization reverts the blocks in the current canonical chain if needed, +/// canonical chain. The reorganization revert the blocks in the current canonical chain if needed, /// and switch the canonical chain to that better chain. /// /// ## Live Cell @@ -53,7 +53,7 @@ use std::sync::Arc; /// * it is found as an output in any transaction in the [canonical chain](#canonical-chain), /// and /// * it is not found as an input in any transaction in the canonical chain. -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait ChainRpc { /// Returns the information about a block by hash. diff --git a/rpc/src/module/debug.rs b/rpc/src/module/debug.rs index 350cbdd1c5..3b5be3d20a 100644 --- a/rpc/src/module/debug.rs +++ b/rpc/src/module/debug.rs @@ -8,8 +8,7 @@ use std::time; /// /// **This module is for CKB developers and will not guarantee compatibility.** The methods here /// will be changed or removed without advanced notification. -#[doc(hidden)] -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait DebugRpc { /// Dumps jemalloc memory profiling information into a file. diff --git a/rpc/src/module/experiment.rs b/rpc/src/module/experiment.rs index 55edc5dd5a..1788654ddd 100644 --- a/rpc/src/module/experiment.rs +++ b/rpc/src/module/experiment.rs @@ -16,7 +16,7 @@ use jsonrpc_utils::rpc; /// **EXPERIMENTAL warning** /// /// The methods here may be removed or changed in future releases without prior notifications. -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait ExperimentRpc { /// Dry run a transaction and return the execution cycles. diff --git a/rpc/src/module/indexer.rs b/rpc/src/module/indexer.rs index 1fd8dca836..8b9932c02f 100644 --- a/rpc/src/module/indexer.rs +++ b/rpc/src/module/indexer.rs @@ -9,7 +9,7 @@ use jsonrpc_core::Result; use jsonrpc_utils::rpc; /// RPC Module Indexer. -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait IndexerRpc { /// Returns the indexed tip diff --git a/rpc/src/module/miner.rs b/rpc/src/module/miner.rs index 9a043804dd..6376c68970 100644 --- a/rpc/src/module/miner.rs +++ b/rpc/src/module/miner.rs @@ -19,7 +19,7 @@ use std::sync::Arc; /// /// A miner gets a template from CKB, optionally selects transactions, resolves the PoW puzzle, and /// submits the found new block. -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait MinerRpc { /// Returns block template for miners. diff --git a/rpc/src/module/mod.rs b/rpc/src/module/mod.rs index ad554dc63e..03d23ef3ad 100644 --- a/rpc/src/module/mod.rs +++ b/rpc/src/module/mod.rs @@ -134,14 +134,16 @@ pub(crate) use self::stats::StatsRpcImpl; pub(crate) use self::subscription::SubscriptionRpcImpl; pub(crate) use self::test::IntegrationTestRpcImpl; -pub use self::alert::{add_alert_rpc_methods, AlertRpc}; -pub use self::chain::{add_chain_rpc_methods, ChainRpc}; -pub use self::debug::{add_debug_rpc_methods, DebugRpc}; -pub use self::experiment::{add_experiment_rpc_methods, ExperimentRpc}; -pub use self::indexer::{add_indexer_rpc_methods, IndexerRpc}; -pub use self::miner::{add_miner_rpc_methods, MinerRpc}; -pub use self::net::{add_net_rpc_methods, NetRpc}; -pub use self::pool::{add_pool_rpc_methods, PoolRpc}; -pub use self::stats::{add_stats_rpc_methods, StatsRpc}; -pub use self::subscription::{add_subscription_rpc_methods, SubscriptionRpc}; -pub use self::test::{add_integration_test_rpc_methods, IntegrationTestRpc}; +pub use self::alert::{add_alert_rpc_methods, alert_rpc_doc, AlertRpc}; +pub use self::chain::{add_chain_rpc_methods, chain_rpc_doc, ChainRpc}; +pub use self::debug::{add_debug_rpc_methods, debug_rpc_doc, DebugRpc}; +pub use self::experiment::{add_experiment_rpc_methods, experiment_rpc_doc, ExperimentRpc}; +pub use self::indexer::{add_indexer_rpc_methods, indexer_rpc_doc, IndexerRpc}; +pub use self::miner::{add_miner_rpc_methods, miner_rpc_doc, MinerRpc}; +pub use self::net::{add_net_rpc_methods, net_rpc_doc, NetRpc}; +pub use self::pool::{add_pool_rpc_methods, pool_rpc_doc, PoolRpc}; +pub use self::stats::{add_stats_rpc_methods, stats_rpc_doc, StatsRpc}; +pub use self::subscription::{add_subscription_rpc_methods, subscription_rpc_doc, SubscriptionRpc}; +pub use self::test::{ + add_integration_test_rpc_methods, integration_test_rpc_doc, IntegrationTestRpc, +}; diff --git a/rpc/src/module/net.rs b/rpc/src/module/net.rs index 289ffb1710..05c82f8db7 100644 --- a/rpc/src/module/net.rs +++ b/rpc/src/module/net.rs @@ -15,7 +15,7 @@ const MAX_ADDRS: usize = 50; const DEFAULT_BAN_DURATION: u64 = 24 * 60 * 60 * 1000; // 1 day /// RPC Module Net for P2P network. -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait NetRpc { /// Returns the local node information. diff --git a/rpc/src/module/pool.rs b/rpc/src/module/pool.rs index cf9e67100c..5b1e3568ae 100644 --- a/rpc/src/module/pool.rs +++ b/rpc/src/module/pool.rs @@ -14,7 +14,7 @@ use jsonrpc_utils::rpc; use std::sync::Arc; /// RPC Module Pool for transaction memory pool. -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait PoolRpc { /// Submits a new transaction into the transaction pool. If the transaction is already in the diff --git a/rpc/src/module/stats.rs b/rpc/src/module/stats.rs index b9adec9f4b..0dececa47f 100644 --- a/rpc/src/module/stats.rs +++ b/rpc/src/module/stats.rs @@ -11,7 +11,7 @@ use std::collections::BTreeMap; use std::sync::Arc; /// RPC Module Stats for getting various statistic data. -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait StatsRpc { /// Returns statistics about the chain. diff --git a/rpc/src/module/subscription.rs b/rpc/src/module/subscription.rs index 25bfe5845f..1c6e846dce 100644 --- a/rpc/src/module/subscription.rs +++ b/rpc/src/module/subscription.rs @@ -8,17 +8,17 @@ use jsonrpc_core::Result; use jsonrpc_utils::{pub_sub::PublishMsg, rpc}; use tokio::sync::broadcast; -/// RPC Module Subscription that CKB node will push new messages to subscribers. +/// RPC Module Subscription that CKB node will push new messages to subscribers, support with WebSocket or TCP. /// /// RPC subscriptions require a full duplex connection. CKB offers such connections in the form of -/// TCP (enable with rpc.tcp_listen_address configuration option) and WebSocket (enable with -/// rpc.ws_listen_address). +/// TCP (enable with `rpc.tcp_listen_address` configuration option) and WebSocket (enable with +/// `rpc.ws_listen_address`). /// -/// ## Examples +/// ###### Examples /// /// TCP RPC subscription: /// -/// ```text +/// ```bash /// telnet localhost 18114 /// > {"id": 2, "jsonrpc": "2.0", "method": "subscribe", "params": ["new_tip_header"]} /// < {"jsonrpc":"2.0","result":"0x0","id":2} @@ -45,20 +45,21 @@ use tokio::sync::broadcast; /// socket.send(`{"id": 2, "jsonrpc": "2.0", "method": "unsubscribe", "params": ["0x0"]}`) /// ``` #[allow(clippy::needless_return)] -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait SubscriptionRpc { /// Context to implement the subscription RPC. /// The stream of subscription messages. type S: Stream> + Send + 'static; + /// #### Method `subscribe` /// Subscribes to a topic. /// - /// ## Params + /// ###### Params /// /// * `topic` - Subscription topic (enum: new_tip_header | new_tip_block | new_transaction | proposed_transaction | rejected_transaction) /// - /// ## Returns + /// ###### Returns /// /// This RPC returns the subscription ID as the result. CKB node will push messages in the subscribed /// topics to the current RPC connection. The subscript ID is also attached as @@ -77,35 +78,35 @@ pub trait SubscriptionRpc { /// } /// ``` /// - /// ## Topics + /// ##### Topics /// - /// ### `new_tip_header` + /// ###### `new_tip_header` /// /// Whenever there's a block that is appended to the canonical chain, the CKB node will publish the /// block header to subscribers. /// /// The type of the `params.result` in the push message is [`HeaderView`](../../ckb_jsonrpc_types/struct.HeaderView.html). /// - /// ### `new_tip_block` + /// ###### `new_tip_block` /// /// Whenever there's a block that is appended to the canonical chain, the CKB node will publish the /// whole block to subscribers. /// /// The type of the `params.result` in the push message is [`BlockView`](../../ckb_jsonrpc_types/struct.BlockView.html). /// - /// ### `new_transaction` + /// ###### `new_transaction` /// /// Subscribers will get notified when a new transaction is submitted to the pool. /// /// The type of the `params.result` in the push message is [`PoolTransactionEntry`](../../ckb_jsonrpc_types/struct.PoolTransactionEntry.html). /// - /// ### `proposed_transaction` + /// ###### `proposed_transaction` /// /// Subscribers will get notified when an in-pool transaction is proposed by chain. /// /// The type of the `params.result` in the push message is [`PoolTransactionEntry`](../../ckb_jsonrpc_types/struct.PoolTransactionEntry.html). /// - /// ### `rejected_transaction` + /// ###### `rejected_transaction` /// /// Subscribers will get notified when a pending transaction is rejected by tx-pool. /// @@ -116,7 +117,7 @@ pub trait SubscriptionRpc { /// - the first item type is [`PoolTransactionEntry`](../../ckb_jsonrpc_types/struct.PoolTransactionEntry.html), and /// - the second item type is [`PoolTransactionReject`](../../ckb_jsonrpc_types/struct.PoolTransactionReject.html). /// - /// ## Examples + /// ###### Examples /// /// Subscribe Request /// @@ -141,6 +142,18 @@ pub trait SubscriptionRpc { /// } /// ``` /// + /// #### Method `unsubscribe` + /// * `unsubscribe(id)` + /// * `id`: `string` + /// * result: `boolean` + /// + /// Unsubscribes from a subscribed topic. + /// + /// ###### Params + /// * `id` - Subscription ID + /// + /// ###### Examples + /// /// Unsubscribe Request /// /// ```json @@ -158,9 +171,9 @@ pub trait SubscriptionRpc { /// /// ```json /// { - /// "id": 42, - /// "jsonrpc": "2.0", - /// "result": true + /// "id": 42, + /// "jsonrpc": "2.0", + /// "result": true /// } /// ``` /// diff --git a/rpc/src/module/test.rs b/rpc/src/module/test.rs index 1452a1af31..1490e1101f 100644 --- a/rpc/src/module/test.rs +++ b/rpc/src/module/test.rs @@ -26,7 +26,7 @@ use std::collections::HashSet; use std::sync::Arc; /// RPC for Integration Test. -#[rpc] +#[rpc(openrpc)] #[async_trait] pub trait IntegrationTestRpc { /// process block without any block verification. diff --git a/rpc/src/service_builder.rs b/rpc/src/service_builder.rs index ceecf2316c..210accd72c 100644 --- a/rpc/src/service_builder.rs +++ b/rpc/src/service_builder.rs @@ -49,7 +49,7 @@ impl<'a> ServiceBuilder<'a> { pub fn new(config: &'a RpcConfig) -> Self { Self { config, - io_handler: IoHandler::default(), + io_handler: IoHandler::with_compatibility(jsonrpc_core::Compatibility::V2), } } diff --git a/util/fixed-hash/core/Cargo.toml b/util/fixed-hash/core/Cargo.toml index de1f9e1cfa..9d94a821f7 100644 --- a/util/fixed-hash/core/Cargo.toml +++ b/util/fixed-hash/core/Cargo.toml @@ -12,6 +12,9 @@ repository = "https://github.com/nervosnetwork/ckb" thiserror = "1.0.22" serde = { version = "1.0", features = ["derive"] } faster-hex = "0.6" +schemars = { version = "0.8.16", package = "ckb_schemars" } + + [dev-dependencies] serde_json = "1.0" diff --git a/util/fixed-hash/core/src/lib.rs b/util/fixed-hash/core/src/lib.rs index 6e387b822f..ac76b08f70 100644 --- a/util/fixed-hash/core/src/lib.rs +++ b/util/fixed-hash/core/src/lib.rs @@ -10,6 +10,8 @@ //! //! [`ckb_fixed_hash`]: ../ckb_fixed_hash/index.html +use schemars::JsonSchema; + pub mod error; mod impls; @@ -37,7 +39,7 @@ pub struct H160(pub [u8; 20]); /// The name comes from the number of bits in the data. /// /// In JSONRPC, it is encoded as a 0x-prefixed hex string. -#[derive(Clone)] +#[derive(Clone, JsonSchema)] pub struct H256(pub [u8; 32]); /// The 64-byte fixed-length binary data. diff --git a/util/jsonrpc-types/Cargo.toml b/util/jsonrpc-types/Cargo.toml index 6501ab1048..b1c816e029 100644 --- a/util/jsonrpc-types/Cargo.toml +++ b/util/jsonrpc-types/Cargo.toml @@ -13,6 +13,8 @@ ckb-types = { path = "../types", version = "= 0.114.0-pre" } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" faster-hex = "0.6" +schemars = { version = "0.8.16", package = "ckb_schemars" } + [dev-dependencies] proptest = "1.0" diff --git a/util/jsonrpc-types/src/alert.rs b/util/jsonrpc-types/src/alert.rs index 830ff57cdf..bbb459830c 100644 --- a/util/jsonrpc-types/src/alert.rs +++ b/util/jsonrpc-types/src/alert.rs @@ -1,11 +1,13 @@ use crate::{bytes::JsonBytes, Timestamp, Uint32}; use ckb_types::{packed, prelude::*}; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; /// The alert identifier that is used to filter duplicated alerts. /// /// This is a 32-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint32](type.Uint32.html#examples). pub type AlertId = Uint32; + /// Alerts are sorted by priority. Greater integers mean higher priorities. /// /// This is a 32-bit unsigned integer type encoded as the 0x-prefixed hex string in JSON. See examples of [Uint32](type.Uint32.html#examples). @@ -34,7 +36,7 @@ pub type AlertPriority = Uint32; /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct Alert { /// The identifier of the alert. Clients use id to filter duplicated alerts. pub id: AlertId, @@ -59,7 +61,7 @@ pub struct Alert { } /// An alert sent by RPC `send_alert`. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct AlertMessage { /// The unique alert ID. pub id: AlertId, diff --git a/util/jsonrpc-types/src/block_template.rs b/util/jsonrpc-types/src/block_template.rs index 77bbf1f406..8e49f9bf72 100644 --- a/util/jsonrpc-types/src/block_template.rs +++ b/util/jsonrpc-types/src/block_template.rs @@ -3,13 +3,14 @@ use crate::{ Timestamp, Transaction, Uint32, Uint64, Version, }; use ckb_types::{packed, prelude::*, H256}; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::convert::From; /// A block template for miners. /// /// Miners optional pick transactions and then assemble the final block. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct BlockTemplate { /// Block version. /// @@ -174,7 +175,7 @@ impl From for packed::Block { } /// The uncle block template of the new block for miners. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct UncleTemplate { /// The uncle block hash. pub hash: H256, @@ -203,7 +204,7 @@ impl From for packed::UncleBlock { } /// The cellbase transaction template of the new block for miners. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct CellbaseTemplate { /// The cellbase transaction hash. pub hash: H256, @@ -224,7 +225,7 @@ impl From for packed::Transaction { } /// Transaction template which is ready to be committed in the new block. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct TransactionTemplate { /// Transaction hash. pub hash: H256, diff --git a/util/jsonrpc-types/src/blockchain.rs b/util/jsonrpc-types/src/blockchain.rs index d346d7a0f0..bfb92522f0 100644 --- a/util/jsonrpc-types/src/blockchain.rs +++ b/util/jsonrpc-types/src/blockchain.rs @@ -7,6 +7,7 @@ use crate::{ use ckb_types::core::tx_pool; use ckb_types::utilities::MerkleProof as RawMerkleProof; use ckb_types::{core, packed, prelude::*, H256}; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt; @@ -24,7 +25,7 @@ use std::fmt; /// when the low 1 bit is 0, it indicates the data, /// and then it relies on the high 7 bits to indicate /// that the data actually corresponds to the version. -#[derive(Default, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Default, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ScriptHashType { /// Type "data" matches script code via cell data hash, and run the script code in v0 CKB VM. @@ -84,7 +85,7 @@ impl fmt::Display for ScriptHashType { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Script { /// The hash used to match the script code. @@ -140,7 +141,7 @@ impl From for Script { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(deny_unknown_fields)] pub struct CellOutput { /// The cell capacity. @@ -200,7 +201,7 @@ impl From for packed::CellOutput { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(deny_unknown_fields)] pub struct OutPoint { /// Transaction hash in which the cell is an output. @@ -245,7 +246,7 @@ impl From for packed::OutPoint { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(deny_unknown_fields)] pub struct CellInput { /// Restrict when the transaction can be committed into the chain. @@ -279,7 +280,7 @@ impl From for packed::CellInput { } /// The dep cell type. Allowed values: "code" and "dep_group". -#[derive(Default, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Default, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum DepType { /// Type "code". @@ -330,7 +331,7 @@ impl From for DepType { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(deny_unknown_fields)] pub struct CellDep { /// Reference to the cell. @@ -367,7 +368,7 @@ impl From for packed::CellDep { /// The transaction. /// /// Refer to RFC [CKB Transaction Structure](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md). -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Transaction { /// Reserved for future usage. It must equal 0 in current version. @@ -456,7 +457,7 @@ pub struct Transaction { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct TransactionView { /// All the fields in `Transaction` are included in `TransactionView` in JSON. #[serde(flatten)] @@ -520,7 +521,7 @@ impl From for packed::Transaction { } /// The JSON view of a transaction as well as its status. -#[derive(Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct TransactionWithStatusResponse { /// The transaction. pub transaction: Option>, @@ -566,7 +567,7 @@ impl TransactionWithStatusResponse { } /// Status for transaction -#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(rename_all = "lowercase")] pub enum Status { /// Status "pending". The transaction is in the pool, and not proposed yet. @@ -584,7 +585,7 @@ pub enum Status { } /// Transaction status and the block hash if it is committed. -#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct TxStatus { /// The transaction status, allowed values: "pending", "proposed" "committed" "unknown" and "rejected". pub status: Status, @@ -676,7 +677,7 @@ impl TxStatus { /// The block header. /// /// Refer to RFC [CKB Block Structure](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0027-block-structure/0027-block-structure.md). -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Header { /// The block version. @@ -720,7 +721,7 @@ pub struct Header { /// The extension hash is the hash of the extension. /// The extra hash is the hash on uncles hash and extension hash concatenated together. /// - /// # Notice + /// **Notice** /// /// This field is renamed from `uncles_hash` since 0.100.0. /// More details can be found in [CKB RFC 0031]. @@ -761,7 +762,7 @@ pub struct Header { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct HeaderView { /// All the fields in `Header` are included in `HeaderView` in JSON. #[serde(flatten)] @@ -851,7 +852,7 @@ impl From
for packed::Header { /// 2. B2 block number is larger than B1; /// 3. B1's parent is either B2's ancestor or an uncle embedded in B2 or any of B2's ancestors. /// 4. B2 is the first block in its chain to refer to B1. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(deny_unknown_fields)] pub struct UncleBlock { /// The uncle block header. @@ -872,7 +873,7 @@ pub struct UncleBlock { /// 2. B2 block number is larger than B1; /// 3. B1's parent is either B2's ancestor or an uncle embedded in B2 or any of B2's ancestors. /// 4. B2 is the first block in its chain to refer to B1. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct UncleBlockView { /// The uncle block header. pub header: HeaderView, @@ -918,7 +919,7 @@ impl From for packed::UncleBlock { } /// The JSON view of a Block used as a parameter in the RPC. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Block { /// The block header. @@ -942,7 +943,7 @@ pub struct Block { } /// The wrapper represent response of `get_block` | `get_block_by_number`, return a Block with cycles. -#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] #[serde(untagged)] pub enum BlockResponse { /// The block response regular format @@ -970,7 +971,7 @@ impl BlockResponse { } /// BlockResponse with cycles format wrapper -#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct BlockWithCyclesResponse { /// The block structure pub block: ResponseFormat, @@ -980,7 +981,7 @@ pub struct BlockWithCyclesResponse { } /// The JSON view of a Block including header and body. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct BlockView { /// The block header. pub header: HeaderView, @@ -1131,7 +1132,7 @@ impl From for core::BlockView { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct EpochView { /// Consecutive epoch number starting from 0. pub number: EpochNumber, @@ -1159,7 +1160,7 @@ impl EpochView { } /// Block base rewards. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct BlockIssuance { /// The primary base rewards. pub primary: Capacity, @@ -1186,7 +1187,7 @@ impl From for core::BlockIssuance { } /// Block rewards for miners. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct MinerReward { /// The primary base block reward allocated to miners. pub primary: Capacity, @@ -1229,7 +1230,7 @@ impl From for core::MinerReward { /// Block Economic State. /// /// It includes the rewards details and when it is finalized. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct BlockEconomicState { /// Block base rewards. pub issuance: BlockIssuance, @@ -1264,7 +1265,7 @@ impl From for core::BlockEconomicState { } /// Merkle proof for transactions in a block. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct TransactionProof { /// Block hash pub block_hash: H256, @@ -1275,7 +1276,7 @@ pub struct TransactionProof { } /// Merkle proof for transactions' witnesses in a block. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct TransactionAndWitnessProof { /// Block hash pub block_hash: H256, @@ -1288,7 +1289,7 @@ pub struct TransactionAndWitnessProof { /// Proof of CKB Merkle Tree. /// /// CKB Merkle Tree is a [CBMT](https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0006-merkle-tree/0006-merkle-tree.md) using CKB blake2b hash as the merge function. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct MerkleProof { /// Leaves indices in the CBMT that are proved present in the block. /// @@ -1312,7 +1313,7 @@ impl From for MerkleProof { } /// Block filter data and hash. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct BlockFilter { /// The the hex-encoded filter data of the block pub data: JsonBytes, @@ -1338,7 +1339,7 @@ pub struct BlockFilter { /// \ /// commit /// ``` -#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)] +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug, JsonSchema)] pub struct ProposalWindow { /// The closest distance between the proposal and the commitment. pub closest: BlockNumber, @@ -1347,7 +1348,7 @@ pub struct ProposalWindow { } /// Consensus defines various parameters that influence chain consensus -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)] pub struct Consensus { /// Names the network. pub id: String, @@ -1366,12 +1367,14 @@ pub struct Consensus { /// The maximum amount of uncles allowed for a block pub max_uncles_num: Uint64, /// The expected orphan_rate + #[schemars(schema_with = "crate::json_schema::rational_u256")] pub orphan_rate_target: core::RationalU256, /// The expected epoch_duration pub epoch_duration_target: Uint64, /// The two-step-transaction-confirmation proposal window pub tx_proposal_window: ProposalWindow, /// The two-step-transaction-confirmation proposer reward ratio + #[schemars(schema_with = "crate::json_schema::rational_u256")] pub proposer_reward_ratio: core::RationalU256, /// The Cellbase maturity pub cellbase_maturity: EpochNumberWithFraction, @@ -1400,7 +1403,7 @@ pub struct Consensus { } /// Hardfork information -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)] #[serde(transparent)] pub struct HardForks { inner: Vec, @@ -1426,7 +1429,7 @@ impl HardForks { } /// The information about one hardfork feature. -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)] pub struct HardForkFeature { /// The related RFC ID. pub rfc: String, @@ -1437,7 +1440,7 @@ pub struct HardForkFeature { /// SoftForkStatus which is either `buried` (for soft fork deployments where the activation epoch is /// hard-coded into the client implementation), or `rfc0043` (for soft fork deployments /// where activation is controlled by rfc0043 signaling). -#[derive(Clone, Copy, Serialize, Deserialize, Debug)] +#[derive(Clone, Copy, Serialize, Deserialize, Debug, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum SoftForkStatus { /// the activation epoch is hard-coded into the client implementation @@ -1447,7 +1450,7 @@ pub enum SoftForkStatus { } /// SoftFork information -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)] #[serde(untagged)] pub enum SoftFork { /// buried - the activation epoch is hard-coded into the client implementation @@ -1468,7 +1471,7 @@ impl SoftFork { /// Represent soft fork deployments where the activation epoch is /// hard-coded into the client implementation -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)] pub struct Buried { /// SoftFork status pub status: SoftForkStatus, @@ -1480,7 +1483,7 @@ pub struct Buried { /// Represent soft fork deployments /// where activation is controlled by rfc0043 signaling -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)] pub struct Rfc0043 { /// SoftFork status pub status: SoftForkStatus, @@ -1490,7 +1493,7 @@ pub struct Rfc0043 { /// Represents the ratio `numerator / denominator`, where `numerator` and `denominator` are both /// unsigned 64-bit integers. -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)] pub struct Ratio { /// Numerator. pub numer: Uint64, @@ -1508,7 +1511,7 @@ impl From for Ratio { } /// RFC0043 deployment params -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)] pub struct Deployment { /// Determines which bit in the `version` field of the block is to be used to signal the softfork lock-in and activation. /// It is chosen from the set {0,1,2,...,28}. @@ -1547,7 +1550,7 @@ impl HardForkFeature { } /// The fee_rate statistics information, includes mean and median, unit: shannons per kilo-weight -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, JsonSchema)] pub struct FeeRateStatistics { /// mean pub mean: Uint64, diff --git a/util/jsonrpc-types/src/bytes.rs b/util/jsonrpc-types/src/bytes.rs index b146ea54e8..1e270f8d54 100644 --- a/util/jsonrpc-types/src/bytes.rs +++ b/util/jsonrpc-types/src/bytes.rs @@ -1,5 +1,6 @@ use ckb_types::{bytes::Bytes, packed, prelude::*}; use faster_hex::{hex_decode, hex_encode}; +use schemars::JsonSchema; use std::fmt; /// Variable-length binary encoded as a 0x-prefixed hex string in JSON. @@ -15,6 +16,14 @@ use std::fmt; /// | "0x0" | Invalid, each byte requires 2 digits | #[derive(Clone, PartialEq, Eq, Hash, Debug, Default)] pub struct JsonBytes(Bytes); +impl JsonSchema for JsonBytes { + fn schema_name() -> String { + String::from("JsonBytes") + } + fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + gen.subschema_for::().into_object().into() + } +} impl JsonBytes { /// Creates the `JsonBytes` from `Bytes`. diff --git a/util/jsonrpc-types/src/cell.rs b/util/jsonrpc-types/src/cell.rs index cee472fd5d..887dbc2ab8 100644 --- a/util/jsonrpc-types/src/cell.rs +++ b/util/jsonrpc-types/src/cell.rs @@ -4,6 +4,7 @@ use ckb_types::{ prelude::Unpack, H256, }; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; /// The JSON view of a cell with its status information. @@ -41,7 +42,7 @@ use serde::{Deserialize, Serialize}; /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct CellWithStatus { /// The cell information. /// @@ -85,7 +86,7 @@ pub struct CellWithStatus { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct CellInfo { /// Cell fields appears in the transaction `outputs` array. pub output: CellOutput, @@ -107,7 +108,7 @@ pub struct CellInfo { /// } /// # "#).unwrap(); /// ``` -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct CellData { /// Cell content. pub content: JsonBytes, diff --git a/util/jsonrpc-types/src/debug.rs b/util/jsonrpc-types/src/debug.rs index 29dd6d542e..54958775de 100644 --- a/util/jsonrpc-types/src/debug.rs +++ b/util/jsonrpc-types/src/debug.rs @@ -1,7 +1,8 @@ +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; /// Runtime logger config for extra loggers. -#[derive(Clone, Default, Serialize, Deserialize, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, Debug, JsonSchema)] pub struct ExtraLoggerConfig { /// Sets log levels for different modules. /// @@ -22,7 +23,7 @@ pub struct ExtraLoggerConfig { } /// Runtime logger config. -#[derive(Clone, Default, Serialize, Deserialize, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, Debug, JsonSchema)] pub struct MainLoggerConfig { /// Sets log levels for different modules. /// diff --git a/util/jsonrpc-types/src/experiment.rs b/util/jsonrpc-types/src/experiment.rs index 23e3dc5d25..8c7e9bac01 100644 --- a/util/jsonrpc-types/src/experiment.rs +++ b/util/jsonrpc-types/src/experiment.rs @@ -1,9 +1,10 @@ use crate::{Cycle, OutPoint}; use ckb_types::H256; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; /// Response result of the RPC method `estimate_cycles`. -#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, JsonSchema)] pub struct EstimateCycles { /// The count of cycles that the VM has consumed to verify this transaction. pub cycles: Cycle, @@ -14,7 +15,7 @@ pub struct EstimateCycles { /// /// [`H256`]: struct.H256.html /// [`OutPoint`]: struct.OutPoint.html -#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)] +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug, JsonSchema)] #[serde(untagged)] pub enum DaoWithdrawingCalculationKind { /// the assumed reference block hash for withdrawing phase 1 transaction diff --git a/util/jsonrpc-types/src/indexer.rs b/util/jsonrpc-types/src/indexer.rs index 4d38d847d8..b18b31fe37 100644 --- a/util/jsonrpc-types/src/indexer.rs +++ b/util/jsonrpc-types/src/indexer.rs @@ -1,9 +1,10 @@ use crate::{BlockNumber, Capacity, CellOutput, JsonBytes, OutPoint, Script, Uint32, Uint64}; use ckb_types::H256; +use schemars::JsonSchema; use serde::{Deserialize, Serialize}; /// Indexer tip information -#[derive(Serialize)] +#[derive(Serialize, JsonSchema)] pub struct IndexerTip { /// indexed tip block hash pub block_hash: H256, @@ -12,7 +13,7 @@ pub struct IndexerTip { } /// Live cell -#[derive(Serialize)] +#[derive(Serialize, JsonSchema)] pub struct IndexerCell { /// the fields of an output cell pub output: CellOutput, @@ -27,7 +28,7 @@ pub struct IndexerCell { } /// IndexerPagination wraps objects array and last_cursor to provide paging -#[derive(Serialize)] +#[derive(Serialize, JsonSchema)] pub struct IndexerPagination { /// objects collection pub objects: Vec, @@ -46,7 +47,7 @@ impl IndexerPagination { } /// SearchKey represent indexer support params -#[derive(Deserialize)] +#[derive(Deserialize, JsonSchema)] pub struct IndexerSearchKey { /// Script pub script: Script, @@ -76,7 +77,7 @@ impl Default for IndexerSearchKey { } /// IndexerSearchMode represent search mode, default is prefix search -#[derive(Deserialize, PartialEq, Eq)] +#[derive(Deserialize, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum IndexerSearchMode { /// Mode `prefix` search with prefix @@ -102,7 +103,7 @@ impl Default for IndexerSearchMode { /// | ["0x0", "0x2"] | [0, 2) | /// | ["0x0", "0x174876e801"] | [0, 100000000001) | /// -#[derive(Deserialize, Default)] +#[derive(Deserialize, Default, JsonSchema)] #[serde(transparent)] pub struct IndexerRange { inner: [Uint64; 2], @@ -131,7 +132,7 @@ impl IndexerRange { } /// IndexerSearchKeyFilter represent indexer params `filter` -#[derive(Deserialize, Default)] +#[derive(Deserialize, Default, JsonSchema)] pub struct IndexerSearchKeyFilter { /// if search script type is lock, filter cells by type script prefix, and vice versa pub script: Option