Skip to content
Snippets Groups Projects
Commit d63807b6 authored by Éloïs's avatar Éloïs
Browse files

wip: #76

parent 23233c41
Branches
Tags
1 merge request!63Resolve "Migrate SQLite to rustbreak"
Showing with 2420 additions and 1265 deletions
...@@ -32,6 +32,27 @@ dependencies = [ ...@@ -32,6 +32,27 @@ dependencies = [
"winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]]
name = "backtrace"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"backtrace-sys 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)",
"cfg-if 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.40 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-demangle 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "backtrace-sys"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cc 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.40 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "base58" name = "base58"
version = "0.1.0" version = "0.1.0"
...@@ -72,6 +93,15 @@ dependencies = [ ...@@ -72,6 +93,15 @@ dependencies = [
"serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]]
name = "bincode"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"byteorder 1.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "0.9.1" version = "0.9.1"
...@@ -227,12 +257,15 @@ dependencies = [ ...@@ -227,12 +257,15 @@ dependencies = [
"duniter-network 0.1.0", "duniter-network 0.1.0",
"duniter-wotb 0.8.0-a0.6", "duniter-wotb 0.8.0-a0.6",
"log 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
"num_cpus 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
"pbr 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "pbr 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
"rustbreak 2.0.0-rc2 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)",
"sqlite 0.23.9 (registry+https://github.com/rust-lang/crates.io-index)", "sqlite 0.23.9 (registry+https://github.com/rust-lang/crates.io-index)",
"threadpool 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]] [[package]]
...@@ -278,6 +311,7 @@ dependencies = [ ...@@ -278,6 +311,7 @@ dependencies = [
"base64 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)", "base64 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]] [[package]]
...@@ -294,10 +328,10 @@ dependencies = [ ...@@ -294,10 +328,10 @@ dependencies = [
"rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "regex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)",
"rustbreak 2.0.0-rc2 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)",
"sqlite 0.23.9 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]] [[package]]
...@@ -312,6 +346,7 @@ dependencies = [ ...@@ -312,6 +346,7 @@ dependencies = [
"regex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "regex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]] [[package]]
...@@ -419,6 +454,25 @@ name = "either" ...@@ -419,6 +454,25 @@ name = "either"
version = "1.5.0" version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "failure"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"backtrace 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
"failure_derive 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "failure_derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)",
"synstructure 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "foreign-types" name = "foreign-types"
version = "0.3.2" version = "0.3.2"
...@@ -716,6 +770,11 @@ dependencies = [ ...@@ -716,6 +770,11 @@ dependencies = [
"unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]]
name = "quote"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]] [[package]]
name = "quote" name = "quote"
version = "0.5.2" version = "0.5.2"
...@@ -838,6 +897,22 @@ dependencies = [ ...@@ -838,6 +897,22 @@ dependencies = [
"time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]]
name = "rustbreak"
version = "2.0.0-rc2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"base64 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)",
"bincode 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"failure 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.57 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rustc-demangle"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]] [[package]]
name = "rustc-serialize" name = "rustc-serialize"
version = "0.3.24" version = "0.3.24"
...@@ -964,6 +1039,16 @@ name = "strsim" ...@@ -964,6 +1039,16 @@ name = "strsim"
version = "0.7.0" version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "syn"
version = "0.11.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)",
"synom 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "syn" name = "syn"
version = "0.13.10" version = "0.13.10"
...@@ -974,6 +1059,23 @@ dependencies = [ ...@@ -974,6 +1059,23 @@ dependencies = [
"unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]]
name = "synom"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "synstructure"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "tempdir" name = "tempdir"
version = "0.3.7" version = "0.3.7"
...@@ -1213,6 +1315,11 @@ name = "unicode-width" ...@@ -1213,6 +1315,11 @@ name = "unicode-width"
version = "0.1.4" version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "unicode-xid"
version = "0.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.1.0" version = "0.1.0"
...@@ -1330,11 +1437,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" ...@@ -1330,11 +1437,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" "checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
"checksum arrayvec 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)" = "a1e964f9e24d588183fcb43503abda40d288c8657dfc27311516ce2f05675aef" "checksum arrayvec 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)" = "a1e964f9e24d588183fcb43503abda40d288c8657dfc27311516ce2f05675aef"
"checksum atty 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "2fc4a1aa4c24c0718a250f0681885c1af91419d242f29eb8f2ab28502d80dbd1" "checksum atty 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "2fc4a1aa4c24c0718a250f0681885c1af91419d242f29eb8f2ab28502d80dbd1"
"checksum backtrace 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "dbdd17cd962b570302f5297aea8648d5923e22e555c2ed2d8b2e34eca646bf6d"
"checksum backtrace-sys 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)" = "bff67d0c06556c0b8e6b5f090f0eac52d950d9dfd1d35ba04e4ca3543eaf6a7e"
"checksum base58 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5024ee8015f02155eee35c711107ddd9a9bf3cb689cf2a9089c97e79b6e1ae83" "checksum base58 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5024ee8015f02155eee35c711107ddd9a9bf3cb689cf2a9089c97e79b6e1ae83"
"checksum base64 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "30e93c03064e7590d0466209155251b90c22e37fab1daf2771582598b5827557" "checksum base64 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "30e93c03064e7590d0466209155251b90c22e37fab1daf2771582598b5827557"
"checksum base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "96434f987501f0ed4eb336a411e0631ecd1afa11574fe148587adc4ff96143c9" "checksum base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "96434f987501f0ed4eb336a411e0631ecd1afa11574fe148587adc4ff96143c9"
"checksum base64 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9263aa6a38da271eec5c91a83ce1e800f093c8535788d403d626d8d5c3f8f007" "checksum base64 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9263aa6a38da271eec5c91a83ce1e800f093c8535788d403d626d8d5c3f8f007"
"checksum bincode 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9a6301db0b49fb63551bc15b5ae348147101cdf323242b93ec7546d5002ff1af" "checksum bincode 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9a6301db0b49fb63551bc15b5ae348147101cdf323242b93ec7546d5002ff1af"
"checksum bincode 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bda13183df33055cbb84b847becce220d392df502ebe7a4a78d7021771ed94d0"
"checksum bitflags 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4efd02e230a02e18f92fc2735f44597385ed02ad8f831e7c1c1156ee5e1ab3a5" "checksum bitflags 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4efd02e230a02e18f92fc2735f44597385ed02ad8f831e7c1c1156ee5e1ab3a5"
"checksum bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d0c54bb8f454c567f21197eefcdbf5679d0bd99f2ddbe52e84c77061952e6789" "checksum bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d0c54bb8f454c567f21197eefcdbf5679d0bd99f2ddbe52e84c77061952e6789"
"checksum byteorder 1.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "74c0b906e9446b0a2e4f760cdb3fa4b2c48cdc6db8766a845c54b6ff063fd2e9" "checksum byteorder 1.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "74c0b906e9446b0a2e4f760cdb3fa4b2c48cdc6db8766a845c54b6ff063fd2e9"
...@@ -1353,6 +1463,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" ...@@ -1353,6 +1463,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum crossbeam-utils 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d636a8b3bcc1b409d7ffd3facef8f21dcb4009626adbd0c5e6c4305c07253c7b" "checksum crossbeam-utils 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d636a8b3bcc1b409d7ffd3facef8f21dcb4009626adbd0c5e6c4305c07253c7b"
"checksum dtoa 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "09c3753c3db574d215cba4ea76018483895d7bff25a31b49ba45db21c48e50ab" "checksum dtoa 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "09c3753c3db574d215cba4ea76018483895d7bff25a31b49ba45db21c48e50ab"
"checksum either 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3be565ca5c557d7f59e7cfcf1844f9e3033650c929c6566f511e8005f205c1d0" "checksum either 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3be565ca5c557d7f59e7cfcf1844f9e3033650c929c6566f511e8005f205c1d0"
"checksum failure 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "934799b6c1de475a012a02dab0ace1ace43789ee4b99bcfbf1a2e3e8ced5de82"
"checksum failure_derive 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c7cdda555bb90c9bb67a3b670a0f42de8e73f5981524123ad8578aafec8ddb8b"
"checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" "checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
"checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" "checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
"checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" "checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82"
...@@ -1391,6 +1503,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" ...@@ -1391,6 +1503,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" "checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831"
"checksum pkg-config 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)" = "110d5ee3593dbb73f56294327fe5668bcc997897097cbc76b51e7aed3f52452f" "checksum pkg-config 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)" = "110d5ee3593dbb73f56294327fe5668bcc997897097cbc76b51e7aed3f52452f"
"checksum proc-macro2 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "1b06e2f335f48d24442b35a19df506a835fb3547bc3c06ef27340da9acf5cae7" "checksum proc-macro2 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "1b06e2f335f48d24442b35a19df506a835fb3547bc3c06ef27340da9acf5cae7"
"checksum quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6e920b65c65f10b2ae65c831a81a073a89edd28c7cce89475bff467ab4167a"
"checksum quote 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9949cfe66888ffe1d53e6ec9d9f3b70714083854be20fd5e271b232a017401e8" "checksum quote 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9949cfe66888ffe1d53e6ec9d9f3b70714083854be20fd5e271b232a017401e8"
"checksum rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)" = "15a732abf9d20f0ad8eeb6f909bf6868722d9a06e1e50802b6a70351f40b4eb1" "checksum rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)" = "15a732abf9d20f0ad8eeb6f909bf6868722d9a06e1e50802b6a70351f40b4eb1"
"checksum rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "eba5f8cb59cc50ed56be8880a5c7b496bfd9bd26394e176bc67884094145c2c5" "checksum rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "eba5f8cb59cc50ed56be8880a5c7b496bfd9bd26394e176bc67884094145c2c5"
...@@ -1404,6 +1517,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" ...@@ -1404,6 +1517,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum regex-syntax 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8f1ac0f60d675cc6cf13a20ec076568254472551051ad5dd050364d70671bf6b" "checksum regex-syntax 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8f1ac0f60d675cc6cf13a20ec076568254472551051ad5dd050364d70671bf6b"
"checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5" "checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5"
"checksum rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)" = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a" "checksum rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)" = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a"
"checksum rustbreak 2.0.0-rc2 (registry+https://github.com/rust-lang/crates.io-index)" = "676cb04876f4391d5d2f2c9029d10cfe5fe28ad625ad8460531bed1191477083"
"checksum rustc-demangle 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "76d7ba1feafada44f2d38eed812bd2489a03c0f5abb975799251518b68848649"
"checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" "checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda"
"checksum safemem 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e27a8b19b835f7aea908818e871f5cc3a5a186550c30773be987e155e8163d8f" "checksum safemem 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e27a8b19b835f7aea908818e871f5cc3a5a186550c30773be987e155e8163d8f"
"checksum schannel 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "85fd9df495640643ad2d00443b3d78aae69802ad488debab4f1dd52fc1806ade" "checksum schannel 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "85fd9df495640643ad2d00443b3d78aae69802ad488debab4f1dd52fc1806ade"
...@@ -1421,7 +1536,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" ...@@ -1421,7 +1536,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum sqlite3-src 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "46e0bc115b563b1ee6c665ef895b56bf488522f57d1c6571887547c57c8f5a88" "checksum sqlite3-src 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "46e0bc115b563b1ee6c665ef895b56bf488522f57d1c6571887547c57c8f5a88"
"checksum sqlite3-sys 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "71fec807a1534bd13eeaaec396175d67c79bdc68df55e18a452726ec62a8fb08" "checksum sqlite3-sys 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "71fec807a1534bd13eeaaec396175d67c79bdc68df55e18a452726ec62a8fb08"
"checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550" "checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550"
"checksum syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d3b891b9015c88c576343b9b3e41c2c11a51c219ef067b264bd9c8aa9b441dad"
"checksum syn 0.13.10 (registry+https://github.com/rust-lang/crates.io-index)" = "77961dcdac942fa8bc033c16f3a790b311c8a27d00811b878ebd8cf9b7ba39d5" "checksum syn 0.13.10 (registry+https://github.com/rust-lang/crates.io-index)" = "77961dcdac942fa8bc033c16f3a790b311c8a27d00811b878ebd8cf9b7ba39d5"
"checksum synom 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a393066ed9010ebaed60b9eafa373d4b1baac186dd7e008555b0f702b51945b6"
"checksum synstructure 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3a761d12e6d8dcb4dcf952a7a89b475e3a9d69e4a69307e01a470977642914bd"
"checksum tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8" "checksum tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8"
"checksum term 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5e6b677dd1e8214ea1ef4297f85dbcbed8e8cdddb561040cc998ca2551c37561" "checksum term 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5e6b677dd1e8214ea1ef4297f85dbcbed8e8cdddb561040cc998ca2551c37561"
"checksum termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096" "checksum termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096"
...@@ -1447,6 +1565,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" ...@@ -1447,6 +1565,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" "checksum unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5"
"checksum unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "6a0180bc61fc5a987082bfa111f4cc95c4caff7f9799f3e46df09163a937aa25" "checksum unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "6a0180bc61fc5a987082bfa111f4cc95c4caff7f9799f3e46df09163a937aa25"
"checksum unicode-width 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "bf3a113775714a22dcb774d8ea3655c53a32debae63a063acc00a91cc586245f" "checksum unicode-width 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "bf3a113775714a22dcb774d8ea3655c53a32debae63a063acc00a91cc586245f"
"checksum unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f860d7d29cf02cb2f3f359fd35991af3d30bac52c57d265a3c461074cb4dc"
"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
"checksum unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" "checksum unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56"
"checksum url 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f808aadd8cfec6ef90e4a14eb46f24511824d1ac596b9682703c87056c8678b7" "checksum url 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f808aadd8cfec6ef90e4a14eb46f24511824d1ac596b9682703c87056c8678b7"
......
...@@ -18,9 +18,12 @@ duniter-module = { path = "../module" } ...@@ -18,9 +18,12 @@ duniter-module = { path = "../module" }
duniter-network = { path = "../network" } duniter-network = { path = "../network" }
duniter-wotb = { path = "../wotb" } duniter-wotb = { path = "../wotb" }
log = "0.4.1" log = "0.4.1"
num_cpus = "1.8.0"
pbr = "1.0.1" pbr = "1.0.1"
rand = "0.4.2" rand = "0.4.2"
rustbreak = {version = "2.0.0-rc2", features = ["bin_enc"]}
serde = "1.0.57" serde = "1.0.57"
serde_derive = "1.0.57" serde_derive = "1.0.57"
serde_json = "1.0.17" serde_json = "1.0.17"
sqlite = "0.23.9" sqlite = "0.23.9"
threadpool = "1.7.1"
\ No newline at end of file
...@@ -13,33 +13,47 @@ ...@@ -13,33 +13,47 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
extern crate duniter_crypto;
extern crate duniter_dal;
extern crate duniter_documents;
extern crate duniter_wotb;
use duniter_crypto::keys::*; use duniter_crypto::keys::*;
use duniter_dal::block::{DALBlock, WotEvent}; use duniter_dal::block::DALBlock;
use duniter_dal::writers::requests::DBWriteRequest; use duniter_dal::sources::SourceAmount;
use duniter_dal::writers::requests::*;
use duniter_dal::ForkId;
use duniter_documents::blockchain::v10::documents::transaction::{TxAmount, TxBase};
use duniter_documents::blockchain::v10::documents::BlockDocument; use duniter_documents::blockchain::v10::documents::BlockDocument;
use duniter_documents::blockchain::Document; use duniter_documents::blockchain::Document;
use duniter_documents::BlockId;
use duniter_wotb::data::NewLinkResult;
use duniter_wotb::{NodeId, WebOfTrust}; use duniter_wotb::{NodeId, WebOfTrust};
use std::collections::HashMap; use std::collections::HashMap;
pub fn try_stack_up_completed_block<W: WebOfTrust + Sync>( #[derive(Debug)]
/// Stores all queries to apply in database to "apply" the block
pub struct ValidBlockApplyReqs(
pub BlocksDBsWriteQuery,
pub Vec<WotsDBsWriteQuery>,
pub Vec<CurrencyDBsWriteQuery>,
);
#[derive(Debug, Copy, Clone)]
/// ApplyValidBlockError
pub enum ApplyValidBlockError {
ExcludeUnknowNodeId(),
RevokeUnknowNodeId(),
}
pub fn apply_valid_block<W: WebOfTrust + Sync>(
block: &BlockDocument, block: &BlockDocument,
wotb_index: &HashMap<PubKey, NodeId>, wot_index: &mut HashMap<PubKey, NodeId>,
wot: &W, wot: &mut W,
) -> (bool, Vec<DBWriteRequest>, Vec<WotEvent>) { expire_certs: &HashMap<(NodeId, NodeId), BlockId>,
old_fork_id: Option<ForkId>,
) -> Result<ValidBlockApplyReqs, ApplyValidBlockError> {
debug!( debug!(
"BlockchainModule : try stack up complete block {}", "BlockchainModule : apply_valid_block({})",
block.blockstamp() block.blockstamp()
); );
let mut db_requests = Vec::new(); let mut wot_dbs_requests = Vec::new();
let mut wot_events = Vec::new(); let mut currency_dbs_requests = Vec::new();
let mut wot_copy: W = wot.clone();
let mut wotb_index_copy: HashMap<PubKey, NodeId> = wotb_index.clone();
let current_blockstamp = block.blockstamp(); let current_blockstamp = block.blockstamp();
let mut identities = HashMap::with_capacity(block.identities.len()); let mut identities = HashMap::with_capacity(block.identities.len());
for identity in block.identities.clone() { for identity in block.identities.clone() {
...@@ -49,104 +63,143 @@ pub fn try_stack_up_completed_block<W: WebOfTrust + Sync>( ...@@ -49,104 +63,143 @@ pub fn try_stack_up_completed_block<W: WebOfTrust + Sync>(
let pubkey = joiner.clone().issuers()[0]; let pubkey = joiner.clone().issuers()[0];
if let Some(idty_doc) = identities.get(&pubkey) { if let Some(idty_doc) = identities.get(&pubkey) {
// Newcomer // Newcomer
let wotb_id = NodeId(wot_copy.size()); let wotb_id = NodeId(wot.size());
wot_events.push(WotEvent::AddNode(pubkey, wotb_id)); wot.add_node();
wot_copy.add_node(); wot_index.insert(pubkey, wotb_id);
wotb_index_copy.insert(pubkey, wotb_id); wot_dbs_requests.push(WotsDBsWriteQuery::CreateIdentity(
db_requests.push(DBWriteRequest::CreateIdentity(
wotb_id, wotb_id,
current_blockstamp, current_blockstamp,
block.median_time, block.median_time,
Box::new(idty_doc.clone()), Box::new(idty_doc.clone()),
joiner.blockstamp().id,
)); ));
} else { } else {
// Renewer // Renewer
let wotb_id = wotb_index_copy[&joiner.issuers()[0]]; let wotb_id = wot_index[&joiner.issuers()[0]];
wot_events.push(WotEvent::EnableNode(wotb_id)); wot.set_enabled(wotb_id, true);
wot_copy.set_enabled(wotb_id, true); wot_dbs_requests.push(WotsDBsWriteQuery::RenewalIdentity(
db_requests.push(DBWriteRequest::RenewalIdentity(
joiner.issuers()[0], joiner.issuers()[0],
block.blockstamp(), wotb_id,
block.median_time, block.median_time,
joiner.blockstamp().id,
)); ));
} }
} }
for active in block.actives.clone() { for active in block.actives.clone() {
let pubkey = active.issuers()[0]; let pubkey = active.issuers()[0];
if !identities.contains_key(&pubkey) { if !identities.contains_key(&pubkey) {
let wotb_id = wotb_index_copy[&pubkey]; let wotb_id = wot_index[&pubkey];
wot_events.push(WotEvent::EnableNode(wotb_id)); wot.set_enabled(wotb_id, true);
wot_copy.set_enabled(wotb_id, true); wot_dbs_requests.push(WotsDBsWriteQuery::RenewalIdentity(
db_requests.push(DBWriteRequest::RenewalIdentity(
pubkey, pubkey,
block.blockstamp(), wotb_id,
block.median_time, block.median_time,
active.blockstamp().id,
)); ));
} }
} }
for exclusion in block.excluded.clone() { for exclusion in block.excluded.clone() {
let wotb_id = wotb_index_copy[&exclusion]; let wot_id = if let Some(wot_id) = wot_index.get(&exclusion) {
wot_events.push(WotEvent::DisableNode(wotb_id)); wot_id
wot_copy.set_enabled(wotb_id, false); } else {
db_requests.push(DBWriteRequest::ExcludeIdentity( return Err(ApplyValidBlockError::ExcludeUnknowNodeId());
wotb_id, };
wot.set_enabled(*wot_id, false);
wot_dbs_requests.push(WotsDBsWriteQuery::ExcludeIdentity(
exclusion,
block.blockstamp(), block.blockstamp(),
block.median_time,
)); ));
} }
for revocation in block.revoked.clone() { for revocation in block.revoked.clone() {
let compact_revoc = revocation.to_compact_document(); let compact_revoc = revocation.to_compact_document();
let wotb_id = wotb_index_copy[&compact_revoc.issuer]; let wot_id = if let Some(wot_id) = wot_index.get(&compact_revoc.issuer) {
wot_events.push(WotEvent::DisableNode(wotb_id)); wot_id
wot_copy.set_enabled(wotb_id, false); } else {
db_requests.push(DBWriteRequest::RevokeIdentity( return Err(ApplyValidBlockError::RevokeUnknowNodeId());
wotb_id, };
wot.set_enabled(*wot_id, false);
wot_dbs_requests.push(WotsDBsWriteQuery::RevokeIdentity(
compact_revoc.issuer,
block.blockstamp(), block.blockstamp(),
block.median_time,
)); ));
} }
for certification in block.certifications.clone() { for certification in block.certifications.clone() {
trace!("try_stack_up_completed_block: apply cert..."); trace!("stack_up_valid_block: apply cert...");
let compact_cert = certification.to_compact_document(); let compact_cert = certification.to_compact_document();
let wotb_node_from = wotb_index_copy[&compact_cert.issuer]; let wotb_node_from = wot_index[&compact_cert.issuer];
let wotb_node_to = wotb_index_copy[&compact_cert.target]; let wotb_node_to = wot_index[&compact_cert.target];
wot_events.push(WotEvent::AddLink(wotb_node_from, wotb_node_to)); let result = wot.add_link(wotb_node_from, wotb_node_to);
wot_copy.add_link(wotb_node_from, wotb_node_to); match result {
db_requests.push(DBWriteRequest::CreateCert( NewLinkResult::Ok(_) => {}
block.blockstamp(), _ => panic!(
"Fail to add_link {}->{} : {:?}",
wotb_node_from.0, wotb_node_to.0, result
),
}
wot_dbs_requests.push(WotsDBsWriteQuery::CreateCert(
compact_cert.issuer,
wotb_node_from,
wotb_node_to,
compact_cert.block_number,
block.median_time, block.median_time,
compact_cert,
)); ));
trace!("try_stack_up_completed_block: apply cert...success."); trace!("stack_up_valid_block: apply cert...success.");
}
for ((source, target), created_block_id) in expire_certs {
wot_dbs_requests.push(WotsDBsWriteQuery::ExpireCert(
*source,
*target,
*created_block_id,
));
}
if let Some(du_amount) = block.dividend {
if du_amount > 0 {
let members_wot_ids = wot.get_enabled();
let mut members_pubkeys = Vec::new();
for (pubkey, wotb_id) in wot_index {
if members_wot_ids.contains(wotb_id) {
members_pubkeys.push(*pubkey);
}
}
currency_dbs_requests.push(CurrencyDBsWriteQuery::CreateDU(
SourceAmount(TxAmount(du_amount as isize), TxBase(block.unit_base)),
block.number,
members_pubkeys,
));
}
}
for tx in block.transactions.clone() {
currency_dbs_requests.push(CurrencyDBsWriteQuery::WriteTx(Box::new(tx.unwrap_doc())));
} }
/*// Calculate the state of the wot /*// Calculate the state of the wot
if !wot_events.is_empty() && verif_level != SyncVerificationLevel::FastSync() { if !wot_events.is_empty() && verif_level != SyncVerificationLevel::FastSync() {
// Calculate sentries_count // Calculate sentries_count
let sentries_count = wot_copy.get_sentries(3).len(); let sentries_count = wot.get_sentries(3).len();
// Calculate average_density // Calculate average_density
let average_density = calculate_average_density::<W>(&wot_copy); let average_density = calculate_average_density::<W>(&wot);
let sentry_requirement = let sentry_requirement =
get_sentry_requirement(block.members_count, G1_PARAMS.step_max); get_sentry_requirement(block.members_count, G1_PARAMS.step_max);
// Calculate distances and connectivities // Calculate distances and connectivities
let (average_distance, distances, average_connectivity, connectivities) = let (average_distance, distances, average_connectivity, connectivities) =
compute_distances::<W>( compute_distances::<W>(
&wot_copy, &wot,
sentry_requirement, sentry_requirement,
G1_PARAMS.step_max, G1_PARAMS.step_max,
G1_PARAMS.x_percent, G1_PARAMS.x_percent,
); );
// Calculate centralities and average_centrality // Calculate centralities and average_centrality
let centralities = let centralities =
calculate_distance_stress_centralities::<W>(&wot_copy, G1_PARAMS.step_max); calculate_distance_stress_centralities::<W>(&wot, G1_PARAMS.step_max);
let average_centrality = let average_centrality =
(centralities.iter().sum::<u64>() as f64 / centralities.len() as f64) as usize; (centralities.iter().sum::<u64>() as f64 / centralities.len() as f64) as usize;
// Register the state of the wot // Register the state of the wot
let max_connectivity = currency_params.max_connectivity();
duniter_dal::register_wot_state( duniter_dal::register_wot_state(
db, db,
&WotState { &WotState {
block_number: block.number.0, block_number: block.number.0,
block_hash: block.hash.unwrap().to_string(), block_hash: block.hash.expect("Fail to get block hash").to_string(),
sentries_count, sentries_count,
average_density, average_density,
average_distance, average_distance,
...@@ -155,8 +208,8 @@ pub fn try_stack_up_completed_block<W: WebOfTrust + Sync>( ...@@ -155,8 +208,8 @@ pub fn try_stack_up_completed_block<W: WebOfTrust + Sync>(
connectivities: connectivities connectivities: connectivities
.iter() .iter()
.map(|c| { .map(|c| {
if *c > *G1_CONNECTIVITY_MAX { if *c > max_connectivity {
*G1_CONNECTIVITY_MAX max_connectivity
} else { } else {
*c *c
} }
...@@ -167,12 +220,28 @@ pub fn try_stack_up_completed_block<W: WebOfTrust + Sync>( ...@@ -167,12 +220,28 @@ pub fn try_stack_up_completed_block<W: WebOfTrust + Sync>(
}, },
); );
}*/ }*/
// Write block in bdd // Create DALBlock
db_requests.push(DBWriteRequest::WriteBlock(Box::new(DALBlock { let mut block = block.clone();
block: block.clone(), let previous_blockcstamp = block.previous_blockstamp();
fork: 0, let block_hash = block
.hash
.expect("Try to get hash of an uncompleted or reduce block !");
block.reduce();
let dal_block = DALBlock {
block,
fork_id: ForkId(0),
isolate: false, isolate: false,
}))); expire_certs: Some(expire_certs.clone()),
};
(true, db_requests, wot_events) // Return DBs requests
Ok(ValidBlockApplyReqs(
BlocksDBsWriteQuery::WriteBlock(
Box::new(dal_block),
old_fork_id,
previous_blockcstamp,
block_hash,
),
wot_dbs_requests,
currency_dbs_requests,
))
} }
// Copyright (C) 2018 The Duniter Project Developers.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::collections::HashMap;
use apply_valid_block::*;
use duniter_crypto::keys::*;
use duniter_dal::block::DALBlock;
use duniter_dal::*;
use duniter_documents::blockchain::Document;
use duniter_documents::{BlockHash, BlockId, Blockstamp, PreviousBlockstamp};
use duniter_network::NetworkBlock;
use *;
#[derive(Debug, Copy, Clone)]
pub enum BlockError {
BlockVersionNotSupported(),
CompletedBlockError(CompletedBlockError),
DALError(DALError),
//CheckBlockError(),
ApplyValidBlockError(ApplyValidBlockError),
NoForkAvailable(),
UnknowError(),
}
impl From<CompletedBlockError> for BlockError {
fn from(err: CompletedBlockError) -> Self {
BlockError::CompletedBlockError(err)
}
}
impl From<DALError> for BlockError {
fn from(err: DALError) -> Self {
BlockError::DALError(err)
}
}
impl From<ApplyValidBlockError> for BlockError {
fn from(err: ApplyValidBlockError) -> Self {
BlockError::ApplyValidBlockError(err)
}
}
pub fn check_and_apply_block<W: WebOfTrust + Sync>(
blocks_databases: &BlocksV10DBs,
certs_db: &BinFileDB<CertsExpirV10Datas>,
block: &Block,
current_blockstamp: &Blockstamp,
wotb_index: &mut HashMap<PubKey, NodeId>,
wot: &mut W,
forks_states: &[ForkStatus],
) -> Result<ValidBlockApplyReqs, BlockError> {
let (block_doc, already_have_block) = match *block {
Block::NetworkBlock(network_block) => match *network_block {
NetworkBlock::V10(ref network_block_v10) => {
let already_have_block = DALBlock::already_have_block(
&blocks_databases.blockchain_db,
&blocks_databases.forks_blocks_db,
network_block_v10.uncompleted_block_doc.blockstamp(),
)?;
(&network_block_v10.uncompleted_block_doc, already_have_block)
}
_ => return Err(BlockError::BlockVersionNotSupported()),
},
Block::LocalBlock(block_doc) => (block_doc, true),
};
if (block_doc.number.0 == current_blockstamp.id.0 + 1
&& block_doc.previous_hash.to_string() == current_blockstamp.hash.0.to_string())
|| (block_doc.number.0 == 0 && *current_blockstamp == Blockstamp::default())
{
debug!(
"stackable_block : block {} chainable !",
block_doc.blockstamp()
);
// Detect expire_certs
let blocks_expiring = Vec::with_capacity(0);
let expire_certs = duniter_dal::certs::find_expire_certs(certs_db, blocks_expiring)?;
// Try stack up block
let mut old_fork_id = None;
let block_doc = match *block {
Block::NetworkBlock(network_block) => complete_network_block(network_block)?,
Block::LocalBlock(block_doc) => {
old_fork_id = duniter_dal::block::get_fork_id_of_blockstamp(
&blocks_databases.forks_blocks_db,
&block_doc.blockstamp(),
)?;
block_doc.clone()
}
};
return Ok(apply_valid_block(
&block_doc,
wotb_index,
wot,
&expire_certs,
old_fork_id,
)?);
} else if !already_have_block
&& (block_doc.number.0 >= current_blockstamp.id.0
|| (current_blockstamp.id.0 - block_doc.number.0) < 100)
{
debug!(
"stackable_block : block {} not chainable, store this for future !",
block_doc.blockstamp()
);
let (fork_id, new_fork) = DALBlock::assign_fork_to_new_block(
&blocks_databases.forks_db,
&PreviousBlockstamp {
id: BlockId(block_doc.number.0 - 1),
hash: BlockHash(block_doc.previous_hash),
},
&block_doc
.hash
.expect("Try to get hash of an uncompleted or reduce block"),
)?;
if let Some(fork_id) = fork_id {
let mut isolate = true;
let fork_state = if new_fork {
ForkStatus::Isolate()
} else {
forks_states[fork_id.0]
};
match fork_state {
ForkStatus::Stackable(_) | ForkStatus::RollBack(_, _) | ForkStatus::TooOld(_) => {
isolate = false
}
_ => {}
}
match *block {
Block::NetworkBlock(network_block) => {
// Completed network block
let block_doc = complete_network_block(network_block)?;
let dal_block = DALBlock {
fork_id,
isolate,
block: block_doc,
expire_certs: None,
};
duniter_dal::writers::block::write(
&blocks_databases.blockchain_db,
&blocks_databases.forks_db,
&blocks_databases.forks_blocks_db,
&dal_block,
None,
false,
).expect("duniter_dal::writers::block::write() : DALError")
}
Block::LocalBlock(block_doc) => {
let old_fork_id = None;
let dal_block = DALBlock {
fork_id,
isolate,
block: block_doc.clone(),
expire_certs: None,
};
duniter_dal::writers::block::write(
&blocks_databases.blockchain_db,
&blocks_databases.forks_db,
&blocks_databases.forks_blocks_db,
&dal_block,
old_fork_id,
false,
).expect("duniter_dal::writers::block::write() : DALError")
}
};
} else {
return Err(BlockError::NoForkAvailable());
}
} else {
debug!(
"stackable_block : block {} not chainable and already stored !",
block_doc.blockstamp()
);
}
Err(BlockError::UnknowError())
}
cyclomatic-complexity-threshold = 36 cyclomatic-complexity-threshold = 37
\ No newline at end of file \ No newline at end of file
// Copyright (C) 2018 The Duniter Project Developers.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use duniter_crypto::keys::*;
use duniter_dal::identity::DALIdentity;
use duniter_documents::blockchain::v10::documents::transaction::*;
use duniter_documents::Blockstamp;
use duniter_module::DuniterConf;
use duniter_wotb::data::rusty::RustyWebOfTrust;
use std::time::*;
use *;
#[derive(Debug, Clone)]
/// Query for wot databases explorer
pub enum DBExWotQuery {
/// Ask member datas
MemberDatas(String),
}
#[derive(Debug, Clone)]
/// Query for tx databases explorer
pub enum DBExTxQuery {
/// Ask balance of an address (pubkey or uid)
Balance(String),
}
#[derive(Debug, Clone)]
/// Query for databases explorer
pub enum DBExQuery {
/// Wot query
WotQuery(DBExWotQuery),
/// Tx query
TxQuery(DBExTxQuery),
}
pub fn dbex(conf: &DuniterConf, query: &DBExQuery) {
match *query {
DBExQuery::WotQuery(ref wot_query) => dbex_wot(conf, wot_query),
DBExQuery::TxQuery(ref tx_query) => dbex_tx(conf, tx_query),
}
}
pub fn dbex_tx(conf: &DuniterConf, query: &DBExTxQuery) {
// Get db path
let db_path = duniter_conf::get_blockchain_db_path(conf.profile().as_str(), &conf.currency());
// Open databases
let load_dbs_begin = SystemTime::now();
//let blocks_databases = BlocksV10DBs::open(&db_path, false);
let currency_databases = CurrencyV10DBs::open(&db_path, false);
let wot_databases = WotsV10DBs::open(&db_path, false);
let load_dbs_duration = SystemTime::now()
.duration_since(load_dbs_begin)
.expect("duration_since error !");
println!(
"Databases loaded in {}.{:03} seconds.",
load_dbs_duration.as_secs(),
load_dbs_duration.subsec_nanos() / 1_000_000
);
let req_process_begin = SystemTime::now();
match *query {
DBExTxQuery::Balance(ref address_str) => {
let pubkey = if let Ok(ed25519_pubkey) = ed25519::PublicKey::from_base58(address_str) {
PubKey::Ed25519(ed25519_pubkey)
} else if let Some(pubkey) = duniter_dal::identity::get_pubkey_from_uid(
&wot_databases.identities_db,
address_str,
).expect("get_uid : DALError")
{
pubkey
} else {
println!("This address doesn't exist !");
return;
};
let address =
TransactionOutputConditionGroup::Single(TransactionOutputCondition::Sig(pubkey));
let address_balance = duniter_dal::balance::get_address_balance(
&currency_databases.balances_db,
&address,
).expect("get_address_balance : DALError")
.expect("Address not found in balances DB.");
println!(
"Balance={},{} Ğ1",
(address_balance.0).0 / 100,
(address_balance.0).0 % 100
);
}
}
let req_process_duration = SystemTime::now()
.duration_since(req_process_begin)
.expect("duration_since error");
println!(
"Request processed in {}.{:06} seconds.",
req_process_duration.as_secs(),
req_process_duration.subsec_nanos() / 1_000
);
}
pub fn dbex_wot(conf: &DuniterConf, query: &DBExWotQuery) {
// Get db path
let db_path = duniter_conf::get_blockchain_db_path(conf.profile().as_str(), &conf.currency());
// Open databases
let load_dbs_begin = SystemTime::now();
//let blocks_databases = BlocksV10DBs::open(&db_path, false);
let wot_databases = WotsV10DBs::open(&db_path, false);
let load_dbs_duration = SystemTime::now()
.duration_since(load_dbs_begin)
.expect("duration_since error");
println!(
"Databases loaded in {}.{:03} seconds.",
load_dbs_duration.as_secs(),
load_dbs_duration.subsec_nanos() / 1_000_000
);
let req_process_begin = SystemTime::now();
// get wot_index
let wot_index = DALIdentity::get_wotb_index(&wot_databases.identities_db).expect("DALError");
// get wot_reverse_index
let wot_reverse_index: HashMap<NodeId, &PubKey> =
wot_index.iter().map(|(p, id)| (*id, p)).collect();
// Get wot path
let wot_path = duniter_conf::get_wot_path(conf.profile().clone().to_string(), &conf.currency());
// Open wot file
let (wot, wot_blockstamp): (RustyWebOfTrust, Blockstamp) =
open_wot_file(&WOT_FILE_FORMATER, &wot_path, *INFINITE_SIG_STOCK);
// Print wot blockstamp
println!("Wot : Current blockstamp = {}.", wot_blockstamp);
// Print members count
let members_count = wot.get_enabled().len();
println!(" Members count = {}.", members_count);
match *query {
DBExWotQuery::MemberDatas(ref uid) => {
if let Some(pubkey) =
duniter_dal::identity::get_pubkey_from_uid(&wot_databases.identities_db, uid)
.expect("get_pubkey_from_uid() : DALError !")
{
let wot_id = wot_index[&pubkey];
println!(
"{} : wot_id={}, pubkey={}.",
uid,
wot_id.0,
pubkey.to_string()
);
let sources = wot
.get_links_source(wot_id)
.expect("Fail to get links source !");
println!("Certifiers : {}", sources.len());
for (i, source) in sources.iter().enumerate() {
let source_uid = duniter_dal::identity::get_uid(
&wot_databases.identities_db,
*(wot_reverse_index[&source]),
).expect("get_uid() : DALError")
.expect("Not found source_uid !");
println!("{}: {}", i + 1, source_uid);
}
} else {
println!("Uid \"{}\" not found !", uid);
}
}
}
let req_process_duration = SystemTime::now()
.duration_since(req_process_begin)
.expect("duration_since error");
println!(
"Request processed in {}.{:06} seconds.",
req_process_duration.as_secs(),
req_process_duration.subsec_nanos() / 1_000
);
}
This diff is collapsed.
This diff is collapsed.
// Copyright (C) 2018 The Duniter Project Developers.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
extern crate serde_json;
extern crate sqlite;
use duniter_crypto::keys::*;
use duniter_documents::blockchain::v10::documents::block::{
BlockV10Parameters, CurrencyName, TxDocOrTxHash,
};
use duniter_documents::blockchain::v10::documents::identity::IdentityDocumentBuilder;
use duniter_documents::blockchain::v10::documents::membership::*;
use duniter_documents::blockchain::v10::documents::transaction::*;
use duniter_documents::blockchain::v10::documents::*;
use duniter_documents::blockchain::DocumentBuilder;
use duniter_documents::{BlockHash, BlockId, Blockstamp, Hash};
use duniter_network::{NetworkBlock, NetworkBlockV10};
use std::str::FromStr;
use sync::BlockHeader;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// MembershipParseError
pub enum MembershipParseError {
WrongFormat(),
}
/// Parse a block from duniter-ts database
pub fn parse_ts_block(row: &[sqlite::Value]) -> NetworkBlock {
let current_header = BlockHeader {
number: BlockId(row[16].as_integer().expect("Fail to parse block number") as u32),
hash: BlockHash(
Hash::from_hex(row[0].as_string().expect("Fail to parse block hash"))
.expect("Fail to parse block hash (2)"),
),
issuer: PubKey::Ed25519(
ed25519::PublicKey::from_base58(
row[4].as_string().expect("Fail to parse block issuer"),
).expect("Failt to parse block issuer (2)"),
),
};
let previous_header = if current_header.number.0 > 0 {
Some(BlockHeader {
number: BlockId(current_header.number.0 - 1),
hash: BlockHash(
Hash::from_hex(
row[6]
.as_string()
.expect("Fail to parse block previous hash"),
).expect("Fail to parse block previous hash (2)"),
),
issuer: PubKey::Ed25519(
ed25519::PublicKey::from_base58(
row[7]
.as_string()
.expect("Fail to parse previous block issuer"),
).expect("Fail to parse previous block issuer (2)"),
),
})
} else {
None
};
let currency = row[3].as_string().expect("Fail to parse currency");
let parameters = if let Some(params_str) = row[5].as_string() {
if let Ok(params) = BlockV10Parameters::from_str(params_str) {
Some(params)
} else {
None
}
} else {
None
};
let dividend = match row[12].as_integer() {
Some(dividend) => Some(dividend as usize),
None => None,
};
let json_identities: serde_json::Value = serde_json::from_str(
row[20].as_string().expect("Fail to parse block identities"),
).expect("Fail to parse block identities (2)");
let mut identities = Vec::new();
for raw_idty in json_identities
.as_array()
.expect("Fail to parse block identities (3)")
{
identities
.push(parse_compact_identity(&currency, &raw_idty).expect("Fail to parse block idty"));
}
let json_txs: serde_json::Value = serde_json::from_str(
row[18].as_string().expect("Fail to parse block txs"),
).expect("Fail to parse block txs (2)");
let mut transactions = Vec::new();
for json_tx in json_txs.as_array().expect("Fail to parse block txs (3)") {
transactions.push(TxDocOrTxHash::TxDoc(Box::new(
parse_transaction(currency, &json_tx).expect("Fail to parse block tx"),
)));
}
let previous_hash = match previous_header.clone() {
Some(previous_header_) => previous_header_.hash.0,
None => Hash::default(),
};
let previous_issuer = match previous_header {
Some(previous_header_) => Some(previous_header_.issuer),
None => None,
};
let excluded: serde_json::Value = serde_json::from_str(
row[25].as_string().expect("Fail to parse excluded"),
).expect("Fail to parse excluded (2)");
let uncompleted_block_doc = BlockDocument {
nonce: row[17].as_integer().expect("Fail to parse nonce") as u64,
number: current_header.number,
pow_min: row[15].as_integer().expect("Fail to parse pow_min") as usize,
time: row[14].as_integer().expect("Fail to parse time") as u64,
median_time: row[11].as_integer().expect("Fail to parse median_time") as u64,
members_count: row[9].as_integer().expect("Fail to parse members_count") as usize,
monetary_mass: row[10]
.as_string()
.expect("Fail to parse monetary_mass")
.parse()
.expect("Fail to parse monetary_mass (2)"),
unit_base: row[13].as_integer().expect("Fail to parse unit_base") as usize,
issuers_count: row[28].as_integer().expect("Fail to parse issuers_count") as usize,
issuers_frame: row[26].as_integer().expect("Fail to parse issuers_frame") as isize,
issuers_frame_var: row[27]
.as_integer()
.expect("Fail to parse issuers_frame_var") as isize,
currency: CurrencyName(String::from(currency)),
issuers: vec![PubKey::Ed25519(
ed25519::PublicKey::from_base58(row[4].as_string().expect("Fail to parse issuer"))
.expect("Fail to parse issuer '2)"),
)],
signatures: vec![Sig::Ed25519(
ed25519::Signature::from_base64(row[2].as_string().expect("Fail to parse signature"))
.expect("Fail to parse signature (2)"),
)],
hash: Some(current_header.hash),
parameters,
previous_hash,
previous_issuer,
inner_hash: Some(
Hash::from_hex(row[1].as_string().expect("Fail to parse block inner_hash"))
.expect("Fail to parse block inner_hash (2)"),
),
dividend,
identities,
joiners: parse_memberships(
currency,
MembershipType::In(),
row[21].as_string().expect("Fail to parse joiners"),
).expect("Fail to parse joiners (2)"),
actives: parse_memberships(
currency,
MembershipType::In(),
row[22].as_string().expect("Fail to parse actives"),
).expect("Fail to parse actives (2)"),
leavers: parse_memberships(
currency,
MembershipType::In(),
row[23].as_string().expect("Fail to parse leavers"),
).expect("Fail to parse leavers (2)"),
revoked: Vec::new(),
excluded: excluded
.as_array()
.expect("Fail to parse excluded (3)")
.to_vec()
.into_iter()
.map(|e| {
PubKey::Ed25519(
ed25519::PublicKey::from_base58(
e.as_str().expect("Fail to parse excluded (4)"),
).expect("Fail to parse excluded (5)"),
)
})
.collect(),
certifications: Vec::new(),
transactions,
inner_hash_and_nonce_str: String::new(),
};
let revoked: serde_json::Value = serde_json::from_str(
row[24].as_string().expect("Fail to parse revoked"),
).expect("Fail to parse revoked (2)");
let certifications: serde_json::Value = serde_json::from_str(
row[19].as_string().expect("Fail to parse certifications"),
).expect("Fail to parse certifications (2)");
// return NetworkBlock
NetworkBlock::V10(Box::new(NetworkBlockV10 {
uncompleted_block_doc,
revoked: revoked
.as_array()
.expect("Fail to parse revoked (3)")
.to_vec(),
certifications: certifications
.as_array()
.expect("Fail to parse certifications (3)")
.to_vec(),
}))
}
/// Parse a compact identity
pub fn parse_compact_identity(
currency: &str,
source: &serde_json::Value,
) -> Option<IdentityDocument> {
if source.is_string() {
let idty_elements: Vec<&str> = source.as_str().unwrap().split(':').collect();
let issuer = match ed25519::PublicKey::from_base58(idty_elements[0]) {
Ok(pubkey) => PubKey::Ed25519(pubkey),
Err(_) => return None,
};
let signature = match ed25519::Signature::from_base64(idty_elements[1]) {
Ok(sig) => Sig::Ed25519(sig),
Err(_) => return None,
};
let blockstamp = match Blockstamp::from_string(idty_elements[2]) {
Ok(blockstamp) => blockstamp,
Err(_) => return None,
};
let username = idty_elements[3];
let idty_doc_builder = IdentityDocumentBuilder {
currency,
username,
blockstamp: &blockstamp,
issuer: &issuer,
};
Some(idty_doc_builder.build_with_signature(vec![signature]))
} else {
None
}
}
/// Parse memberships documents from json string
pub fn parse_memberships(
currency: &str,
membership_type: MembershipType,
json_datas: &str,
) -> Option<Vec<MembershipDocument>> {
let raw_memberships: serde_json::Value = serde_json::from_str(json_datas).unwrap();
if raw_memberships.is_array() {
return Some(
parse_memberships_from_json_value(
currency,
membership_type,
raw_memberships.as_array().unwrap(),
).iter()
.map(|m| {
m.clone()
.expect("Fatal error : Fail to parse membership from local DB !")
})
.collect(),
);
}
None
}
/// Parse memberships documents from array of json values
pub fn parse_memberships_from_json_value(
currency: &str,
membership_type: MembershipType,
array_memberships: &[serde_json::Value],
) -> Vec<Result<MembershipDocument, MembershipParseError>> {
//let memberships: Vec<MembershipDocument> = Vec::new();
array_memberships
.iter()
.map(|membership| {
let membership_datas: Vec<&str> = membership.as_str().unwrap().split(':').collect();
if membership_datas.len() == 5 {
let membership_doc_builder = MembershipDocumentBuilder {
currency,
issuer: &PubKey::Ed25519(
ed25519::PublicKey::from_base58(membership_datas[0]).unwrap(),
),
blockstamp: &Blockstamp::from_string(membership_datas[2]).unwrap(),
membership: membership_type,
identity_username: membership_datas[4],
identity_blockstamp: &Blockstamp::from_string(membership_datas[3]).unwrap(),
};
let membership_sig =
Sig::Ed25519(ed25519::Signature::from_base64(membership_datas[1]).unwrap());
Ok(membership_doc_builder.build_with_signature(vec![membership_sig]))
} else {
Err(MembershipParseError::WrongFormat())
}
})
.collect()
}
/// Parse transaction from json value
pub fn parse_transaction(
currency: &str,
source: &serde_json::Value,
) -> Option<TransactionDocument> {
//debug!("transaction={:#?}", source);
let blockstamp = match Blockstamp::from_string(source.get("blockstamp")?.as_str()?) {
Ok(blockstamp) => blockstamp,
Err(_) => {
return None;
}
};
let locktime = source.get("locktime")?.as_i64()? as u64;
let issuers_array = source.get("issuers")?.as_array()?;
let mut issuers = Vec::with_capacity(issuers_array.len());
for issuer in issuers_array {
match ed25519::PublicKey::from_base58(issuer.as_str()?) {
Ok(pubkey) => issuers.push(PubKey::Ed25519(pubkey)),
Err(_) => {
return None;
}
}
}
let inputs_array = source.get("inputs")?.as_array()?;
let mut inputs = Vec::with_capacity(inputs_array.len());
for input in inputs_array {
let input_str = input.as_str()?;
match TransactionInput::parse_from_str(input_str) {
Ok(input) => inputs.push(input),
Err(_) => {
return None;
}
}
}
let unlocks_array = source.get("unlocks")?.as_array()?;
let mut unlocks = Vec::with_capacity(unlocks_array.len());
for unlock in unlocks_array {
match TransactionInputUnlocks::parse_from_str(unlock.as_str()?) {
Ok(unlock) => unlocks.push(unlock),
Err(_) => {
return None;
}
}
}
let outputs_array = source.get("outputs")?.as_array()?;
let mut outputs = Vec::with_capacity(outputs_array.len());
for output in outputs_array {
match TransactionOutput::parse_from_str(output.as_str()?) {
Ok(output) => outputs.push(output),
Err(_) => {
return None;
}
}
}
let signatures_array = source.get("signatures")?.as_array()?;
let mut signatures = Vec::with_capacity(signatures_array.len());
for signature in signatures_array {
match ed25519::Signature::from_base64(signature.as_str()?) {
Ok(signature) => signatures.push(Sig::Ed25519(signature)),
Err(_) => {
return None;
}
}
}
let comment = source.get("comment")?.as_str()?;
let tx_doc_builder = TransactionDocumentBuilder {
currency,
blockstamp: &blockstamp,
locktime: &locktime,
issuers: &issuers,
inputs: &inputs,
unlocks: &unlocks,
outputs: &outputs,
comment,
};
Some(tx_doc_builder.build_with_signature(signatures))
}
...@@ -327,19 +327,13 @@ pub fn write_conf_file(file_path: &PathBuf, conf: &DuniterConf) -> Result<(), st ...@@ -327,19 +327,13 @@ pub fn write_conf_file(file_path: &PathBuf, conf: &DuniterConf) -> Result<(), st
} }
/// Returns the path to the database containing the blockchain /// Returns the path to the database containing the blockchain
pub fn get_db_path(profile: &str, currency: &Currency, sync: bool) -> PathBuf { pub fn get_blockchain_db_path(profile: &str, currency: &Currency) -> PathBuf {
if sync {
let mut db_path = PathBuf::new();
let mut db_name = String::from(profile);
db_name.push_str("_durs.db");
db_path.push("/dev/shm");
db_path.push(db_name);
db_path
} else {
let mut db_path = datas_path(profile, &currency); let mut db_path = datas_path(profile, &currency);
db_path.push("blockchain.db"); db_path.push("blockchain/");
db_path if !db_path.as_path().exists() {
fs::create_dir(db_path.as_path()).expect("Impossible to create blockchain dir !");
} }
db_path
} }
/// Returns the path to the binary file containing the state of the web of trust /// Returns the path to the binary file containing the state of the web of trust
......
...@@ -39,18 +39,29 @@ subcommands: ...@@ -39,18 +39,29 @@ subcommands:
short: c short: c
long: cautious long: cautious
help: cautious mode (check all protocol rules, very slow) help: cautious mode (check all protocol rules, very slow)
- msync_ts: - dbex:
about: synchronization in memory mode via a duniter-ts database about: durs databases explorer
version: "0.1.0"
author: Elois L. <elois@duniter.org>
subcommands:
- member:
about: durs databases explorer (wot members datas)
version: "0.1.0" version: "0.1.0"
author: Elois L. <elois@duniter.org> author: Elois L. <elois@duniter.org>
args: args:
- TS_PROFILE: - UID:
help: Set the ts profile to use help : choose member uid
index: 1 index: 1
- cautious: required: true
short: c - balance:
long: cautious about: durs databases explorer (balances datas)
help: cautious mode (check all protocol rules, very slow) version: "0.1.0"
author: Elois L. <elois@duniter.org>
args:
- ADDRESS:
help : public key or uid
index: 1
required: true
- reset: - reset:
about: reset data or conf or all about: reset data or conf or all
version: "0.1.0" version: "0.1.0"
......
...@@ -38,9 +38,8 @@ extern crate simplelog; ...@@ -38,9 +38,8 @@ extern crate simplelog;
extern crate sqlite; extern crate sqlite;
extern crate threadpool; extern crate threadpool;
use self::threadpool::ThreadPool;
use clap::{App, ArgMatches}; use clap::{App, ArgMatches};
use duniter_blockchain::BlockchainModule; use duniter_blockchain::{BlockchainModule, DBExQuery, DBExTxQuery, DBExWotQuery};
use duniter_conf::DuniterKeyPairs; use duniter_conf::DuniterKeyPairs;
use duniter_message::DuniterMessage; use duniter_message::DuniterMessage;
use duniter_module::*; use duniter_module::*;
...@@ -52,6 +51,7 @@ use std::fs::{File, OpenOptions}; ...@@ -52,6 +51,7 @@ use std::fs::{File, OpenOptions};
use std::sync::mpsc; use std::sync::mpsc;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use threadpool::ThreadPool;
#[derive(Debug)] #[derive(Debug)]
/// Duniter Core Datas /// Duniter Core Datas
...@@ -124,6 +124,21 @@ impl DuniterCore { ...@@ -124,6 +124,21 @@ impl DuniterCore {
let ts_profile = matches.value_of("TS_PROFILE").unwrap_or("duniter_default"); let ts_profile = matches.value_of("TS_PROFILE").unwrap_or("duniter_default");
sync_ts(&conf, ts_profile, matches.is_present("cautious")); sync_ts(&conf, ts_profile, matches.is_present("cautious"));
None None
} else if let Some(matches) = cli_args.subcommand_matches("dbex") {
if let Some(member_matches) = matches.subcommand_matches("member") {
let uid = member_matches.value_of("UID").unwrap_or("");
dbex(
&conf,
&DBExQuery::WotQuery(DBExWotQuery::MemberDatas(String::from(uid))),
);
} else if let Some(balance_matches) = matches.subcommand_matches("balance") {
let address = balance_matches.value_of("ADDRESS").unwrap_or("");
dbex(
&conf,
&DBExQuery::TxQuery(DBExTxQuery::Balance(String::from(address))),
);
}
None
} else if let Some(matches) = cli_args.subcommand_matches("reset") { } else if let Some(matches) = cli_args.subcommand_matches("reset") {
let mut profile_path = match env::home_dir() { let mut profile_path = match env::home_dir() {
Some(path) => path, Some(path) => path,
...@@ -135,7 +150,10 @@ impl DuniterCore { ...@@ -135,7 +150,10 @@ impl DuniterCore {
if !profile_path.as_path().exists() { if !profile_path.as_path().exists() {
panic!(format!("Error : {} profile don't exist !", profile)); panic!(format!("Error : {} profile don't exist !", profile));
} }
match matches.value_of("DATAS_TYPE").unwrap() { match matches
.value_of("DATAS_TYPE")
.expect("cli param DATAS_TYPE is missing !")
{
"data" => { "data" => {
let mut currency_datas_path = profile_path.clone(); let mut currency_datas_path = profile_path.clone();
currency_datas_path.push("g1"); currency_datas_path.push("g1");
...@@ -189,7 +207,6 @@ impl DuniterCore { ...@@ -189,7 +207,6 @@ impl DuniterCore {
let mut blockchain_module = BlockchainModule::load_blockchain_conf( let mut blockchain_module = BlockchainModule::load_blockchain_conf(
&self.conf, &self.conf,
RequiredKeysContent::MemberKeyPair(None), RequiredKeysContent::MemberKeyPair(None),
false,
); );
info!("Success to load Blockchain module."); info!("Success to load Blockchain module.");
...@@ -265,7 +282,7 @@ pub fn start( ...@@ -265,7 +282,7 @@ pub fn start(
let mut modules_senders: Vec<mpsc::Sender<DuniterMessage>> = Vec::new(); let mut modules_senders: Vec<mpsc::Sender<DuniterMessage>> = Vec::new();
let mut modules_count_expected = None; let mut modules_count_expected = None;
while modules_count_expected.is_none() while modules_count_expected.is_none()
|| modules_senders.len() < modules_count_expected.unwrap() + 1 || modules_senders.len() < modules_count_expected.expect("safe unwrap") + 1
{ {
match main_receiver.recv_timeout(Duration::from_secs(20)) { match main_receiver.recv_timeout(Duration::from_secs(20)) {
Ok(mess) => { Ok(mess) => {
...@@ -363,7 +380,13 @@ pub fn start( ...@@ -363,7 +380,13 @@ pub fn start(
/// Launch synchronisation from a duniter-ts database /// Launch synchronisation from a duniter-ts database
pub fn sync_ts(conf: &DuniterConf, ts_profile: &str, cautious: bool) { pub fn sync_ts(conf: &DuniterConf, ts_profile: &str, cautious: bool) {
// Launch sync-ts // Launch sync-ts
BlockchainModule::sync_ts(&conf, ts_profile, cautious); BlockchainModule::sync_ts(conf, ts_profile, cautious);
}
/// Launch databases explorer
pub fn dbex(conf: &DuniterConf, query: &DBExQuery) {
// Launch databases explorer
BlockchainModule::dbex(conf, query);
} }
/// Initialize logger /// Initialize logger
...@@ -418,9 +441,7 @@ pub fn init_logger(profile: &str, soft_name: &'static str, cli_args: &ArgMatches ...@@ -418,9 +441,7 @@ pub fn init_logger(profile: &str, soft_name: &'static str, cli_args: &ArgMatches
).expect("Fatal error : fail to create log file path !"); ).expect("Fatal error : fail to create log file path !");
} }
CombinedLogger::init(vec![ CombinedLogger::init(vec![WriteLogger::new(
TermLogger::new(LevelFilter::Error, logger_config).unwrap(),
WriteLogger::new(
log_level.to_level_filter(), log_level.to_level_filter(),
logger_config, logger_config,
OpenOptions::new() OpenOptions::new()
...@@ -432,6 +453,5 @@ pub fn init_logger(profile: &str, soft_name: &'static str, cli_args: &ArgMatches ...@@ -432,6 +453,5 @@ pub fn init_logger(profile: &str, soft_name: &'static str, cli_args: &ArgMatches
.expect("Fatal error : fail to get log file path !"), .expect("Fatal error : fail to get log file path !"),
) )
.expect("Fatal error : fail to open log file !"), .expect("Fatal error : fail to open log file !"),
), )]).expect("Fatal error : fail to init logger !");
]).expect("Fatal error : fail to init logger !");
} }
...@@ -16,6 +16,7 @@ base58 = "0.1.0" ...@@ -16,6 +16,7 @@ base58 = "0.1.0"
base64 = "0.9.1" base64 = "0.9.1"
rust-crypto = "0.2.36" rust-crypto = "0.2.36"
serde = "1.0.57" serde = "1.0.57"
serde_derive = "1.0.57"
[features] [features]
# Treat warnings as a build error. # Treat warnings as a build error.
......
...@@ -21,20 +21,17 @@ ...@@ -21,20 +21,17 @@
extern crate serde; extern crate serde;
use std::collections::hash_map::DefaultHasher; use self::serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
use std::fmt::Debug; use self::serde::ser::{Serialize, SerializeSeq, Serializer};
use std::fmt::Display; use super::{BaseConvertionError, PrivateKey as PrivateKeyMethods, PublicKey as PublicKeyMethods};
use std::fmt::Error;
use std::fmt::Formatter;
use std::hash::{Hash, Hasher};
use self::serde::ser::{Serialize, Serializer};
use base58::{FromBase58, FromBase58Error, ToBase58}; use base58::{FromBase58, FromBase58Error, ToBase58};
use base64; use base64;
use base64::DecodeError; use base64::DecodeError;
use crypto; use crypto;
use std::collections::hash_map::DefaultHasher;
use super::{BaseConvertionError, PrivateKey as PrivateKeyMethods, PublicKey as PublicKeyMethods}; use std::fmt::{self, Debug, Display, Error, Formatter};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
/// Store a ed25519 signature. /// Store a ed25519 signature.
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
...@@ -47,6 +44,73 @@ impl Hash for Signature { ...@@ -47,6 +44,73 @@ impl Hash for Signature {
} }
} }
impl Serialize for Signature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(64))?;
for e in self.0.iter() {
seq.serialize_element(e)?;
}
seq.end()
}
}
struct SignatureVisitor {
marker: PhantomData<fn() -> Signature>,
}
impl SignatureVisitor {
fn new() -> Self {
SignatureVisitor {
marker: PhantomData,
}
}
}
impl<'de> Visitor<'de> for SignatureVisitor {
// The type that our Visitor is going to produce.
type Value = Signature;
// Format a message stating what data this Visitor expects to receive.
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("Signature datas")
}
// Deserialize Signature from an abstract "map" provided by the
// Deserializer. The MapAccess input is a callback provided by
// the Deserializer to let us see each entry in the map.
fn visit_seq<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: SeqAccess<'de>,
{
let mut map = Vec::with_capacity(access.size_hint().unwrap_or(0));
// While there are entries remaining in the input, add them
// into our map.
while let Some(value) = access.next_element()? {
map.push(value);
}
let mut sig_datas: [u8; 64] = [0; 64];
sig_datas.copy_from_slice(&map[0..64]);
Ok(Signature(sig_datas))
}
}
// This is the trait that informs Serde how to deserialize Signature.
impl<'de> Deserialize<'de> for Signature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Instantiate our Visitor and ask the Deserializer to drive
// it over the input data, resulting in an instance of Signature.
deserializer.deserialize_seq(SignatureVisitor::new())
}
}
impl super::Signature for Signature { impl super::Signature for Signature {
fn from_base64(base64_data: &str) -> Result<Signature, BaseConvertionError> { fn from_base64(base64_data: &str) -> Result<Signature, BaseConvertionError> {
match base64::decode(base64_data) { match base64::decode(base64_data) {
...@@ -104,7 +168,7 @@ impl Eq for Signature {} ...@@ -104,7 +168,7 @@ impl Eq for Signature {}
/// Can be generated with [`KeyPairGenerator`]. /// Can be generated with [`KeyPairGenerator`].
/// ///
/// [`KeyPairGenerator`]: struct.KeyPairGenerator.html /// [`KeyPairGenerator`]: struct.KeyPairGenerator.html
#[derive(Copy, Clone, PartialEq, Eq, Hash)] #[derive(Copy, Clone, Deserialize, PartialEq, Eq, Hash, Serialize)]
pub struct PublicKey(pub [u8; 32]); pub struct PublicKey(pub [u8; 32]);
impl ToBase58 for PublicKey { impl ToBase58 for PublicKey {
...@@ -126,15 +190,6 @@ impl Debug for PublicKey { ...@@ -126,15 +190,6 @@ impl Debug for PublicKey {
} }
} }
impl Serialize for PublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{}", self))
}
}
impl super::PublicKey for PublicKey { impl super::PublicKey for PublicKey {
type Signature = Signature; type Signature = Signature;
......
...@@ -48,7 +48,6 @@ ...@@ -48,7 +48,6 @@
extern crate serde; extern crate serde;
use self::serde::ser::{Serialize, Serializer};
use base58::ToBase58; use base58::ToBase58;
use std::fmt::Debug; use std::fmt::Debug;
use std::fmt::Display; use std::fmt::Display;
...@@ -109,7 +108,7 @@ pub trait Signature: Clone + Display + Debug + PartialEq + Eq + Hash { ...@@ -109,7 +108,7 @@ pub trait Signature: Clone + Display + Debug + PartialEq + Eq + Hash {
} }
/// Store a cryptographic signature. /// Store a cryptographic signature.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum Sig { pub enum Sig {
/// Store a ed25519 Signature /// Store a ed25519 Signature
Ed25519(ed25519::Signature), Ed25519(ed25519::Signature),
...@@ -171,7 +170,7 @@ pub trait PublicKey: Clone + Display + Debug + PartialEq + Eq + Hash + ToBase58 ...@@ -171,7 +170,7 @@ pub trait PublicKey: Clone + Display + Debug + PartialEq + Eq + Hash + ToBase58
} }
/// Store a cryptographic public key. /// Store a cryptographic public key.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum PubKey { pub enum PubKey {
/// Store a ed25519 public key. /// Store a ed25519 public key.
Ed25519(ed25519::PublicKey), Ed25519(ed25519::PublicKey),
...@@ -203,15 +202,6 @@ impl Display for PubKey { ...@@ -203,15 +202,6 @@ impl Display for PubKey {
} }
} }
impl Serialize for PubKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{}", self))
}
}
impl PublicKey for PubKey { impl PublicKey for PubKey {
type Signature = Sig; type Signature = Sig;
......
...@@ -22,6 +22,9 @@ ...@@ -22,6 +22,9 @@
unused_qualifications unused_qualifications
)] )]
#[macro_use]
extern crate serde_derive;
extern crate base58; extern crate base58;
extern crate base64; extern crate base64;
extern crate crypto; extern crate crypto;
......
...@@ -17,9 +17,9 @@ duniter-wotb = { path = "../wotb" } ...@@ -17,9 +17,9 @@ duniter-wotb = { path = "../wotb" }
lazy_static = "1.0.0" lazy_static = "1.0.0"
log = "0.4.1" log = "0.4.1"
rand = "0.4.2" rand = "0.4.2"
rustbreak = {version = "2.0.0-rc2", features = ["bin_enc"]}
rust-crypto = "0.2.36" rust-crypto = "0.2.36"
regex = "1.0.0" regex = "1.0.0"
sqlite = "0.23.9"
serde = "1.0.57" serde = "1.0.57"
serde_derive = "1.0.57" serde_derive = "1.0.57"
serde_json = "1.0.17" serde_json = "1.0.17"
......
// Copyright (C) 2018 The Duniter Project Developers.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use sources::*;
use *;
pub fn get_address_balance(
balances_db: &BinFileDB<BalancesV10Datas>,
address: &TransactionOutputConditionGroup,
) -> Result<Option<SourceAmount>, DALError> {
Ok(balances_db.read(|db| {
if let Some(balance_and_utxos) = db.get(address) {
Some(balance_and_utxos.0)
} else {
None
}
})?)
}
This diff is collapsed.
// Copyright (C) 2018 The Duniter Project Developers.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
extern crate duniter_documents;
extern crate duniter_wotb;
use duniter_documents::BlockId;
use duniter_wotb::NodeId;
use rustbreak::backend::Backend;
use std::collections::HashMap;
use std::fmt::Debug;
use {BinDB, CertsExpirV10Datas, DALError};
/// Find certifications that emitted in indicated blocks expiring
pub fn find_expire_certs<B: Backend + Debug>(
certs_db: &BinDB<CertsExpirV10Datas, B>,
blocks_expiring: Vec<BlockId>,
) -> Result<HashMap<(NodeId, NodeId), BlockId>, DALError> {
Ok(certs_db.read(|db| {
let mut all_expire_certs = HashMap::new();
for expire_block_id in blocks_expiring {
if let Some(expire_certs) = db.get(&expire_block_id) {
for (source, target) in expire_certs {
all_expire_certs.insert((*source, *target), expire_block_id);
}
}
}
all_expire_certs
})?)
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment