diff --git a/.github/workflows/cd.yaml b/.github/workflows/cd.yaml index 956814e..6110009 100644 --- a/.github/workflows/cd.yaml +++ b/.github/workflows/cd.yaml @@ -10,7 +10,10 @@ jobs: name: Linux Release runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - name: Checkout + uses: actions/checkout@v6 + with: + submodules: recursive - name: Build run: cargo build --release - name: Archive @@ -32,7 +35,9 @@ jobs: runs-on: macos-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v6 + with: + submodules: recursive - name: Build run: cargo build --release - name: Archive @@ -53,7 +58,9 @@ jobs: runs-on: windows-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v6 + with: + submodules: recursive - name: Build run: cargo build --release - name: Archive diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 783258e..989bfb6 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -9,7 +9,9 @@ jobs: matrix: job_args: [api, config, controller, impls, libwallet, .] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v6 + with: + submodules: recursive - name: Test ${{ matrix.job_args }} working-directory: ${{ matrix.job_args }} run: cargo test --release @@ -19,7 +21,9 @@ jobs: runs-on: macos-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v6 + with: + submodules: recursive - name: Tests run: cargo test --release --all @@ -28,6 +32,8 @@ jobs: runs-on: windows-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v6 + with: + submodules: recursive - name: Tests run: cargo test --release --all \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..e974e83 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "grin"] + path = grin + branch = staging + url = https://github.com/mimblewimble/grin diff --git a/.hooks/pre-commit b/.hooks/pre-commit old mode 100644 new mode 100755 diff --git a/Cargo.lock b/Cargo.lock index 336af48..44b607c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -27,18 +27,31 @@ dependencies = [ ] [[package]] -name = "age" -version = "0.7.2" +name = "aes" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "815e87cc8c39227cfff259f9550bd9f1c1a082370eccf4e9a176327fb7f906c9" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if 1.0.4", + "cipher 0.4.4", + "cpufeatures 0.2.17", + "zeroize", +] + +[[package]] +name = "age" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf6575916925dce67e5cc5588066ec50db90be641b5de10e2495d1a4045d55c" dependencies = [ "age-core", "base64 0.13.1", "bech32 0.8.1", "chacha20poly1305", + "cipher 0.4.4", "cookie-factory", "hkdf", - "hmac 0.11.0", + "hmac 0.12.1", "i18n-embed", "i18n-embed-fl", "lazy_static", @@ -48,6 +61,7 @@ dependencies = [ "rand 0.8.6", "rust-embed", "scrypt", + "sha2 0.10.9", "sha2 0.9.9", "subtle", "x25519-dalek 1.1.1", @@ -56,18 +70,19 @@ dependencies = [ [[package]] name = "age-core" -version = "0.7.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70afa630ef12a4fc666277713efbe6da2bc87bb3f3af0f1149415b701362c615" +checksum = "00a5c8d8a33abc74ad393896a6305351dd159d0e184788f4729e3c80e397fa45" dependencies = [ "base64 0.13.1", "chacha20poly1305", "cookie-factory", "hkdf", + "io_tee", "nom", "rand 0.8.6", - "secrecy 0.8.0", - "sha2 0.9.9", + "secrecy", + "sha2 0.10.9", ] [[package]] @@ -79,6 +94,52 @@ dependencies = [ "memchr", ] +[[package]] +name = "amplify" +version = "4.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f7fb4ac7c881e54a8e7015e399b6112a2a5bc958b6c89ac510840ff20273b31" +dependencies = [ + "amplify_derive", + "amplify_num", + "ascii", + "getrandom 0.2.17", + "getrandom 0.3.4", + "wasm-bindgen", +] + +[[package]] +name = "amplify_derive" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a6309e6b8d89b36b9f959b7a8fa093583b94922a0f6438a24fb08936de4d428" +dependencies = [ + "amplify_syn", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 1.0.109", +] + +[[package]] +name = "amplify_num" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afed304556696656d2d71495e1e5f2c4b524a3fb6eb0f2f3778ffc482a40b8a8" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "amplify_syn" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7736fb8d473c0d83098b5bac44df6a561e20470375cd8bcae30516dc889fd62a" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 1.0.109", +] + [[package]] name = "android_system_properties" version = "0.1.5" @@ -88,35 +149,26 @@ dependencies = [ "libc", ] -[[package]] -name = "ansi_term" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" -dependencies = [ - "winapi 0.3.9", -] - [[package]] name = "ansi_term" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" dependencies = [ - "winapi 0.3.9", + "winapi", ] [[package]] name = "anyhow" -version = "1.0.102" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" [[package]] name = "arc-swap" -version = "1.9.1" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a3a1fd6f75306b68087b831f025c712524bcb19aad54e557b1129cfa0a2b207" +checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" dependencies = [ "rustversion", ] @@ -144,32 +196,199 @@ checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] -name = "async-stream" -version = "0.3.6" +name = "arti-client" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +checksum = "841d54b6c87059a9b6562bfe585f3a637b72f90cddaa327ac29b5ddf082a54b4" dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite 0.2.17", + "async-trait", + "cfg-if 1.0.4", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "educe", + "fs-mistrust", + "futures 0.3.32", + "hostname-validator", + "humantime 2.4.0", + "humantime-serde", + "libc", + "once_cell", + "postage", + "rand 0.10.2", + "safelog", + "serde", + "tempfile", + "thiserror 2.0.18", + "time", + "tor-async-utils", + "tor-basic-utils", + "tor-chanmgr", + "tor-circmgr", + "tor-config", + "tor-config-path", + "tor-dircommon", + "tor-dirmgr", + "tor-error", + "tor-guardmgr", + "tor-hsclient", + "tor-hscrypto", + "tor-hsservice", + "tor-keymgr", + "tor-linkspec", + "tor-llcrypto", + "tor-memquota", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-ptmgr", + "tor-rtcompat", + "tracing", + "void", + "web-time-compat", ] [[package]] -name = "async-stream-impl" -version = "0.3.6" +name = "ascii" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits 0.2.19", + "rusticata-macros", + "thiserror 2.0.18", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", + "synstructure", ] +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "assert_matches" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" + +[[package]] +name = "async-compression" +version = "0.4.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e79b3f8a79cccc2898f31920fc69f304859b3bd567490f75ebf51ae1c792a9ac" +dependencies = [ + "compression-codecs", + "compression-core", + "futures-io", + "pin-project-lite", +] + +[[package]] +name = "async-native-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37dd6b179962fe4048a6f81d4c0d7ed419a21fdf49204b4c6b04971693358e79" +dependencies = [ + "futures-util", + "native-tls", + "thiserror 2.0.18", + "url", +] + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "async_executors" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a982d2f86de6137cc05c9db9a915a19886c97911f9790d04f174cede74be01a5" +dependencies = [ + "blanket", + "futures-core", + "futures-task", + "futures-util", + "pin-project", + "rustc_version", + "tokio", +] + +[[package]] +name = "asynchronous-codec" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a860072022177f903e59730004fb5dc13db9275b79bb2aef7ba8ce831956c233" +dependencies = [ + "bytes 1.12.0", + "futures-sink", + "futures-util", + "memchr", + "pin-project-lite", +] + +[[package]] +name = "atomic" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" + +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "atty" version = "0.2.14" @@ -178,7 +397,7 @@ checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" dependencies = [ "hermit-abi 0.1.19", "libc", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -196,6 +415,29 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-lc-rs" +version = "1.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4342d8937fc7e5dd9b1c60292261c0670c882a2cd1719cfc11b1af41731e32ad" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9ceb1da931507a12f4fccea479dccd00da1943e1b4ae72d8e502d707361444" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "backtrace" version = "0.3.76" @@ -211,6 +453,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.9.3" @@ -239,6 +487,12 @@ version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64ct" version = "1.8.3" @@ -275,6 +529,16 @@ dependencies = [ "serde", ] +[[package]] +name = "bincode" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" +dependencies = [ + "serde", + "unty", +] + [[package]] name = "bit-vec" version = "0.6.3" @@ -289,13 +553,25 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.12.1" +version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84d7ced0ae9557296835c32bf1b1e02b44c746701f898460fb000d7eaa84f00a" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" dependencies = [ "serde_core", ] +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + [[package]] name = "blake2-rfc" version = "0.2.18" @@ -317,6 +593,17 @@ dependencies = [ "constant_time_eq", ] +[[package]] +name = "blanket" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0b121a9fe0df916e362fb3271088d071159cdf11db0e4182d02152850756eff" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + [[package]] name = "block-buffer" version = "0.7.3" @@ -362,6 +649,26 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "476e9cd489f9e121e02ffa6014a8ef220ecb15c05ed23fc34cca13925dc283fb" +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bstr" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + [[package]] name = "built" version = "0.8.1" @@ -377,28 +684,30 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + [[package]] name = "byte-tools" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" +[[package]] +name = "bytemuck" +version = "1.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" + [[package]] name = "byteorder" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" -[[package]] -name = "bytes" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "206fdffcfa2df7cbe15601ef46c813fce0965eb3286db6b56c583b814b51c81c" -dependencies = [ - "byteorder", - "iovec", -] - [[package]] name = "bytes" version = "0.5.6" @@ -407,15 +716,21 @@ checksum = "0e4cec68f03f32e44924783795810fa50a7035d8c8ebe78580ad7e6c703fba38" [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" + +[[package]] +name = "caret" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bb840a063107846780a14acc022b55bf6c174997a393ffde8b58ff6630c1b56" [[package]] name = "cc" -version = "1.2.63" +version = "1.2.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f" +checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996" dependencies = [ "find-msvc-tools", "jobserver", @@ -435,6 +750,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + [[package]] name = "chacha20" version = "0.8.2" @@ -442,11 +763,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c80e5460aa66fe3b91d40bcbdab953a597b60053e34d684ac6903f863b680a6" dependencies = [ "cfg-if 1.0.4", - "cipher", - "cpufeatures", + "cipher 0.3.0", + "cpufeatures 0.2.17", "zeroize", ] +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if 1.0.4", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + [[package]] name = "chacha20poly1305" version = "0.9.1" @@ -454,17 +786,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a18446b09be63d457bbec447509e85f662f32952b035ce892290396bc0b0cff5" dependencies = [ "aead", - "chacha20", - "cipher", + "chacha20 0.8.2", + "cipher 0.3.0", "poly1305", "zeroize", ] [[package]] name = "chrono" -version = "0.4.44" +version = "0.4.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", "js-sys", @@ -483,13 +815,24 @@ dependencies = [ "generic-array 0.14.7", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", + "zeroize", +] + [[package]] name = "clap" version = "2.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" dependencies = [ - "ansi_term 0.12.1", + "ansi_term", "atty", "bitflags 1.3.2", "strsim 0.8.0", @@ -499,6 +842,17 @@ dependencies = [ "yaml-rust", ] +[[package]] +name = "clipboard-win" +version = "4.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7191c27c2357d9b7ef96baac1773290d4ca63b24205b82a3fd8a0637afcf0362" +dependencies = [ + "error-code", + "str-buf", + "winapi", +] + [[package]] name = "cloudabi" version = "0.0.3" @@ -508,12 +862,91 @@ dependencies = [ "bitflags 1.3.2", ] +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "coarsetime" +version = "0.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e58eb270476aa4fc7843849f8a35063e8743b4dbcdf6dd0f8ea0886980c204c2" +dependencies = [ + "libc", + "wasix", + "wasm-bindgen", +] + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes 1.12.0", + "memchr", +] + +[[package]] +name = "compression-codecs" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf" +dependencies = [ + "compression-core", + "flate2", + "liblzma", + "zstd", + "zstd-safe", +] + +[[package]] +name = "compression-core" +version = "0.4.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "constant_time_eq" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "cookie-factory" version = "0.3.3" @@ -558,6 +991,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.0" @@ -620,6 +1062,18 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array 0.14.7", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -631,10 +1085,19 @@ dependencies = [ ] [[package]] -name = "crypto-mac" -version = "0.11.1" +name = "crypto-common" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1d1a86f49236c215f271d40892d5fc950490551400b02ef360692c29815c714" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "crypto-mac" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25fab6889090c8133f3deb8f73ba3c65a7f456f66436fc012a1b1e272b1e103e" dependencies = [ "generic-array 0.14.7", "subtle", @@ -647,7 +1110,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" dependencies = [ "csv-core", - "itoa 1.0.18", + "itoa", "ryu", "serde_core", ] @@ -662,26 +1125,12 @@ dependencies = [ ] [[package]] -name = "ctor" -version = "0.1.26" +name = "ctr" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d2301688392eb071b0bf1a37be05c469d3cc4dbbd95df672fe28ab021e6a096" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" dependencies = [ - "quote 1.0.45", - "syn 1.0.109", -] - -[[package]] -name = "curve25519-dalek" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a9b85542f99a2dfa2a1b8e192662741c9859a846b296bef1c92ef9b58b5a216" -dependencies = [ - "byteorder", - "digest 0.8.1", - "rand_core 0.5.1", - "subtle", - "zeroize", + "cipher 0.4.4", ] [[package]] @@ -697,14 +1146,86 @@ dependencies = [ "zeroize", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if 1.0.4", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto 0.2.9", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if 1.0.4", + "cpufeatures 0.3.0", + "curve25519-dalek-derive", + "fiat-crypto 0.3.0", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + [[package]] name = "darling" version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.13.4", + "darling_macro 0.13.4", +] + +[[package]] +name = "darling" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" +dependencies = [ + "darling_core 0.14.4", + "darling_macro 0.14.4", +] + +[[package]] +name = "darling" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +dependencies = [ + "darling_core 0.21.3", + "darling_macro 0.21.3", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", ] [[package]] @@ -716,22 +1237,95 @@ dependencies = [ "fnv", "ident_case", "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "strsim 0.10.0", "syn 1.0.109", ] +[[package]] +name = "darling_core" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2 1.0.106", + "quote 1.0.46", + "strsim 0.10.0", + "syn 1.0.109", +] + +[[package]] +name = "darling_core" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2 1.0.106", + "quote 1.0.46", + "strsim 0.11.1", + "syn 2.0.118", +] + [[package]] name = "darling_macro" version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" dependencies = [ - "darling_core", - "quote 1.0.45", + "darling_core 0.13.4", + "quote 1.0.46", "syn 1.0.109", ] +[[package]] +name = "darling_macro" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" +dependencies = [ + "darling_core 0.14.4", + "quote 1.0.46", + "syn 1.0.109", +] + +[[package]] +name = "darling_macro" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +dependencies = [ + "darling_core 0.21.3", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core 0.23.0", + "quote 1.0.46", + "syn 2.0.118", +] + [[package]] name = "dashmap" version = "5.5.3" @@ -740,9 +1334,9 @@ checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" dependencies = [ "cfg-if 1.0.4", "hashbrown 0.14.5", - "lock_api 0.4.14", + "lock_api", "once_cell", - "parking_lot_core 0.9.12", + "parking_lot_core", ] [[package]] @@ -751,6 +1345,100 @@ version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "cookie-factory", + "displaydoc", + "nom", + "num-traits 0.2.19", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive-deftly" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bc153c91ebf221a2e7feb166aee259acf8a00ecf35c83df8b79fe8f5c3861d7" +dependencies = [ + "derive-deftly-macros", + "heck 0.5.0", +] + +[[package]] +name = "derive-deftly-macros" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1747ed5fb4ab3a9f8253da3401efe7ca8f8e5ec373b2e700ff55c3304d84e31f" +dependencies = [ + "heck 0.5.0", + "indexmap 2.14.0", + "itertools 0.15.0", + "proc-macro-crate", + "proc-macro2 1.0.106", + "quote 1.0.46", + "sha3 0.12.0", + "strum 0.28.0", + "syn 2.0.118", + "unicode-ident", + "void", +] + +[[package]] +name = "derive_builder_core_fork_arti" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24c1b715c79be6328caa9a5e1a387a196ea503740f0722ec3dd8f67a9e72314d" +dependencies = [ + "darling 0.14.4", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_fork_arti" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3eae24d595f4d0ecc90a9a5a6d11c2bd8dafe2375ec4a1ec63250e5ade7d228" +dependencies = [ + "derive_builder_macro_fork_arti", +] + +[[package]] +name = "derive_builder_macro_fork_arti" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69887769a2489cd946bf782eb2b1bb2cb7bc88551440c94a765d4f040c08ebf3" +dependencies = [ + "derive_builder_core_fork_arti", + "syn 1.0.109", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -766,10 +1454,11 @@ version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" dependencies = [ + "convert_case", "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "rustc_version", - "syn 2.0.117", + "syn 2.0.118", "unicode-xid 0.2.6", ] @@ -779,12 +1468,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c877555693c14d2f84191cfd3ad8582790fc52b5e2274b40b59cf5f5cea25c7" -[[package]] -name = "difference" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198" - [[package]] name = "digest" version = "0.8.1" @@ -810,10 +1493,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", - "crypto-common", + "const-oid 0.9.6", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "const-oid 0.10.2", + "crypto-common 0.2.2", +] + +[[package]] +name = "directories" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" +dependencies = [ + "dirs-sys 0.5.0", +] + [[package]] name = "dirs" version = "1.0.5" @@ -822,7 +1525,7 @@ checksum = "3fd78930633bd1c6e35c4b42b1df7b0cbc6bc191146e512bb3bedf243fcc3901" dependencies = [ "libc", "redox_users 0.3.5", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -832,7 +1535,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13aea89a5c93364a98e9b37b2fa237effbb694d5cfe01c5b70941f7eb087d5e3" dependencies = [ "cfg-if 0.1.10", - "dirs-sys", + "dirs-sys 0.3.7", ] [[package]] @@ -841,17 +1544,16 @@ version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" dependencies = [ - "dirs-sys", + "dirs-sys 0.3.7", ] [[package]] -name = "dirs-next" -version = "1.0.2" +name = "dirs" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf36e65a80337bea855cd4ef9b8401ffce06a7baedf2e85ec467b1ac3f6e82b6" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" dependencies = [ - "cfg-if 1.0.4", - "dirs-sys-next", + "dirs-sys 0.5.0", ] [[package]] @@ -872,7 +1574,19 @@ checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" dependencies = [ "libc", "redox_users 0.4.6", - "winapi 0.3.9", + "winapi", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.5.2", + "windows-sys 0.61.2", ] [[package]] @@ -883,7 +1597,7 @@ checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" dependencies = [ "libc", "redox_users 0.4.6", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -893,19 +1607,37 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] +[[package]] +name = "downcast-rs" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" + [[package]] name = "doxygen-rs" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "415b6ec780d34dcf624666747194393603d0373b7141eef01d12ee58881507d9" dependencies = [ - "phf", + "phf 0.11.3", ] +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "easy-jsonrpc-mw" version = "0.5.4" @@ -932,34 +1664,82 @@ dependencies = [ ] [[package]] -name = "ed25519" -version = "1.5.3" +name = "ecdsa" +version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91cff35c70bba8a626e3185d8cd48cc11b5437e1a5bcd15b9b5fa3c64b6dfee7" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", "signature", ] [[package]] name = "ed25519-dalek" -version = "1.0.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c762bae6dcaf24c4c84667b8579785430908723d5c889f469d76a41d59cc7a9d" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ - "curve25519-dalek 3.2.0", + "curve25519-dalek 4.1.3", "ed25519", - "rand 0.7.3", + "merlin", + "rand_core 0.6.4", "serde", - "sha2 0.9.9", + "sha2 0.10.9", + "subtle", "zeroize", ] +[[package]] +name = "educe" +version = "0.4.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f0042ff8246a363dbe77d2ceedb073339e85a804b9a47636c6e016a9a32c05f" +dependencies = [ + "enum-ordinalize", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 1.0.109", +] + [[package]] name = "either" version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array 0.14.7", + "group", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "encode_unicode" version = "1.0.0" @@ -975,6 +1755,37 @@ dependencies = [ "cfg-if 1.0.4", ] +[[package]] +name = "endian-type" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d" + +[[package]] +name = "enum-ordinalize" +version = "3.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf1fa3f06bbff1ea5b1a9c7b14aa992a39657db60a2759457328d7e058f49ee" +dependencies = [ + "num-bigint 0.4.8", + "num-traits 0.2.19", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "enum_dispatch" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" +dependencies = [ + "once_cell", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + [[package]] name = "enum_primitive" version = "0.1.1" @@ -984,6 +1795,40 @@ dependencies = [ "num-traits 0.1.43", ] +[[package]] +name = "enumset" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c4174b41e75c8f7306110b2c51996a293b8d1d850edd529011841d9fede7d" +dependencies = [ + "enumset_derive", +] + +[[package]] +name = "enumset_derive" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd536557b58c682b217b8fb199afdff47cd3eff260623f19e77074eb073d63a" +dependencies = [ + "darling 0.21.3", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "env_logger" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" +dependencies = [ + "atty", + "humantime 1.3.0", + "log", + "regex", + "termcolor", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -1000,19 +1845,108 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f18991e7bf11e7ffee451b5318b5c1a73c52d0d0ada6e5a3017c8c1ced6a21" +dependencies = [ + "libc", + "str-buf", +] + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "fd-lock" +version = "3.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef033ed5e9bad94e55838ca0ca906db0e043f517adda0c8b79c7a8c66c93c1b5" +dependencies = [ + "cfg-if 1.0.4", + "rustix 0.38.44", + "windows-sys 0.48.0", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + +[[package]] +name = "figment" +version = "0.10.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" +dependencies = [ + "atomic 0.6.1", + "serde", + "toml 0.8.23", + "uncased", + "version_check", +] + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if 1.0.4", + "libc", +] + [[package]] name = "find-crate" version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59a98bbaacea1c0eb6a0876280051b892eb73594fd90cf3b20e9c817029c57d2" dependencies = [ - "toml", + "toml 0.5.11", ] [[package]] @@ -1075,6 +2009,12 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "fluid-let" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "749cff877dc1af878a0b31a41dd221a753634401ea0ef2f87b62d3171522485a" + [[package]] name = "fnv" version = "1.0.7" @@ -1087,6 +2027,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "foreign-types" version = "0.3.2" @@ -1111,6 +2057,39 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-mistrust" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd938e053fbfb6dba36106f4bcf27c53362e6152adc9341700c4bc2264cd4a8f" +dependencies = [ + "derive_builder_fork_arti", + "dirs 6.0.0", + "libc", + "pwd-grp", + "serde", + "thiserror 2.0.18", + "void", + "walkdir", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "fslock-guard" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63307a37c3d90d55a90eefa5441ec12cbd291ff456b6bf1126656c5bc43b058" +dependencies = [ + "libc", + "thiserror 2.0.18", + "windows-sys 0.61.2", +] + [[package]] name = "fuchsia-cprng" version = "0.1.1" @@ -1118,20 +2097,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" [[package]] -name = "fuchsia-zircon" -version = "0.3.3" +name = "funty" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" -dependencies = [ - "bitflags 1.3.2", - "fuchsia-zircon-sys", -] - -[[package]] -name = "fuchsia-zircon-sys" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" @@ -1164,6 +2133,18 @@ dependencies = [ "futures-sink", ] +[[package]] +name = "futures-copy" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcad91f8ba72542347d5cc8ee43891abe4698429fa7b3de56f17f4bb6fa514c4" +dependencies = [ + "futures 0.3.32", + "libc", + "pin-project", + "windows-sys 0.61.2", +] + [[package]] name = "futures-core" version = "0.3.32" @@ -1194,8 +2175,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -1223,7 +2204,7 @@ dependencies = [ "futures-sink", "futures-task", "memchr", - "pin-project-lite 0.2.17", + "pin-project-lite", "slab", ] @@ -1244,6 +2225,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -1264,8 +2246,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if 1.0.4", + "js-sys", "libc", "wasi 0.11.1+wasi-snapshot-preview1", + "wasm-bindgen", ] [[package]] @@ -1275,22 +2259,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if 1.0.4", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if 1.0.4", + "js-sys", "libc", "r-efi 6.0.0", - "wasip2", - "wasip3", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "getset" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cf442baaabe4213ce7d1239afc26c039180b6456da2cededa316ae2c8a77a77" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -1305,50 +2303,53 @@ version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddddbf932745a6be37109b6112d3ee09696106f848449069d3a57bba937ab82e" dependencies = [ - "bitflags 2.12.1", + "bitflags 2.13.0", "libc", "libgit2-sys", "log", ] +[[package]] +name = "glob-match" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985c9503b412198aa4197559e9a318524ebc4519c229bfa05a535828c950b9d" + [[package]] name = "grin_api" -version = "5.4.0" -source = "git+https://github.com/mimblewimble/grin?rev=cf2ed3f3becd62b5e754ec964fd90e332b9a021f#cf2ed3f3becd62b5e754ec964fd90e332b9a021f" +version = "5.5.1-alpha.0" dependencies = [ - "async-stream", - "bytes 1.11.1", + "bytes 1.12.0", "easy-jsonrpc-mw", "futures 0.3.32", "grin_chain", "grin_core", "grin_p2p", "grin_pool", - "grin_store", "grin_util", - "http", - "hyper 0.14.32", - "hyper-rustls 0.23.2", + "http-body-util", + "hyper", + "hyper-rustls", "hyper-timeout", + "hyper-util", "lazy_static", "log", "regex", - "ring 0.16.20", - "rustls 0.20.9", + "rustls", "rustls-pemfile", "serde", "serde_derive", "serde_json", + "subtle", "thiserror 1.0.69", - "tokio 1.52.3", - "tokio-rustls 0.23.4", + "tokio", + "tokio-rustls", "url", ] [[package]] name = "grin_chain" -version = "5.4.0" -source = "git+https://github.com/mimblewimble/grin?rev=cf2ed3f3becd62b5e754ec964fd90e332b9a021f#cf2ed3f3becd62b5e754ec964fd90e332b9a021f" +version = "5.5.1-alpha.0" dependencies = [ "bit-vec", "bitflags 1.3.2", @@ -1356,6 +2357,7 @@ dependencies = [ "chrono", "croaring", "enum_primitive", + "env_logger", "grin_core", "grin_keychain", "grin_store", @@ -1363,6 +2365,7 @@ dependencies = [ "lazy_static", "log", "lru-cache", + "rand 0.6.5", "serde", "serde_derive", "thiserror 1.0.69", @@ -1370,8 +2373,7 @@ dependencies = [ [[package]] name = "grin_core" -version = "5.4.0" -source = "git+https://github.com/mimblewimble/grin?rev=cf2ed3f3becd62b5e754ec964fd90e332b9a021f#cf2ed3f3becd62b5e754ec964fd90e332b9a021f" +version = "5.5.1-alpha.0" dependencies = [ "blake2-rfc", "byteorder", @@ -1385,10 +2387,11 @@ dependencies = [ "log", "lru-cache", "num", - "num-bigint", + "num-bigint 0.2.6", "rand 0.6.5", "serde", "serde_derive", + "serde_json", "siphasher 0.3.11", "thiserror 1.0.69", "zeroize", @@ -1396,8 +2399,7 @@ dependencies = [ [[package]] name = "grin_keychain" -version = "5.4.0" -source = "git+https://github.com/mimblewimble/grin?rev=cf2ed3f3becd62b5e754ec964fd90e332b9a021f#cf2ed3f3becd62b5e754ec964fd90e332b9a021f" +version = "5.5.1-alpha.0" dependencies = [ "blake2-rfc", "byteorder", @@ -1418,8 +2420,7 @@ dependencies = [ [[package]] name = "grin_p2p" -version = "5.4.0" -source = "git+https://github.com/mimblewimble/grin?rev=cf2ed3f3becd62b5e754ec964fd90e332b9a021f#cf2ed3f3becd62b5e754ec964fd90e332b9a021f" +version = "5.5.1-alpha.0" dependencies = [ "bitflags 1.3.2", "built", @@ -1428,6 +2429,7 @@ dependencies = [ "enum_primitive", "grin_chain", "grin_core", + "grin_pool", "grin_store", "grin_util", "log", @@ -1441,11 +2443,11 @@ dependencies = [ [[package]] name = "grin_pool" -version = "5.4.0" -source = "git+https://github.com/mimblewimble/grin?rev=cf2ed3f3becd62b5e754ec964fd90e332b9a021f#cf2ed3f3becd62b5e754ec964fd90e332b9a021f" +version = "5.5.1-alpha.0" dependencies = [ "blake2-rfc", "chrono", + "grin_chain", "grin_core", "grin_keychain", "grin_util", @@ -1462,7 +2464,7 @@ version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf7bb95f155b1eede2648a1b9afbba82bc3d9f2af0518b478767559a572bd973" dependencies = [ - "arrayvec 0.7.6", + "arrayvec 0.7.8", "cc", "libc", "rand 0.5.6", @@ -1473,17 +2475,20 @@ dependencies = [ [[package]] name = "grin_store" -version = "5.4.0" -source = "git+https://github.com/mimblewimble/grin?rev=cf2ed3f3becd62b5e754ec964fd90e332b9a021f#cf2ed3f3becd62b5e754ec964fd90e332b9a021f" +version = "5.5.1-alpha.0" dependencies = [ "byteorder", + "chrono", "croaring", + "env_logger", + "filetime", "grin_core", "grin_util", "heed", "libc", "log", "memmap", + "rand 0.6.5", "serde", "serde_derive", "tempfile", @@ -1492,18 +2497,16 @@ dependencies = [ [[package]] name = "grin_util" -version = "5.4.0" -source = "git+https://github.com/mimblewimble/grin?rev=cf2ed3f3becd62b5e754ec964fd90e332b9a021f#cf2ed3f3becd62b5e754ec964fd90e332b9a021f" +version = "5.5.1-alpha.0" dependencies = [ "anyhow", "backtrace", "base64 0.12.3", - "byteorder", "grin_secp256k1zkp", "lazy_static", "log", "log4rs", - "parking_lot 0.10.2", + "parking_lot", "rand 0.6.5", "serde", "serde_derive", @@ -1514,7 +2517,7 @@ dependencies = [ [[package]] name = "grin_wallet" -version = "5.4.0-alpha.1" +version = "5.4.1" dependencies = [ "built", "clap", @@ -1528,17 +2531,13 @@ dependencies = [ "grin_wallet_controller", "grin_wallet_impls", "grin_wallet_libwallet", - "grin_wallet_util", "lazy_static", "linefeed", "log", - "prettytable-rs", - "remove_dir_all", "rpassword", "rustyline", - "semver 0.10.0", + "semver", "serde", - "serde_derive", "serde_json", "thiserror 1.0.69", "url", @@ -1546,7 +2545,7 @@ dependencies = [ [[package]] name = "grin_wallet_api" -version = "5.4.0-alpha.1" +version = "5.4.1" dependencies = [ "base64 0.12.3", "chrono", @@ -1561,7 +2560,7 @@ dependencies = [ "grin_wallet_util", "log", "rand 0.6.5", - "ring 0.16.20", + "ring", "serde", "serde_derive", "serde_json", @@ -1571,27 +2570,26 @@ dependencies = [ [[package]] name = "grin_wallet_config" -version = "5.4.0-alpha.1" +version = "5.4.1" dependencies = [ "dirs 2.0.2", "grin_core", "grin_util", - "grin_wallet_util", - "pretty_assertions", + "lazy_static", "rand 0.6.5", "serde", "serde_derive", - "toml", + "tempfile", + "toml 0.5.11", + "toml_edit 0.22.27", ] [[package]] name = "grin_wallet_controller" -version = "5.4.0-alpha.1" +version = "5.4.1" dependencies = [ - "chrono", "easy-jsonrpc-mw", "ed25519-dalek", - "futures 0.3.32", "grin_api", "grin_chain", "grin_core", @@ -1602,76 +2600,81 @@ dependencies = [ "grin_wallet_impls", "grin_wallet_libwallet", "grin_wallet_util", - "hyper 0.14.32", + "http-body-util", + "hyper", "lazy_static", "log", "prettytable-rs", "qr_code", "rand 0.7.3", - "remove_dir_all", - "ring 0.16.20", "serde", - "serde_derive", "serde_json", "term 0.6.1", "thiserror 1.0.69", - "tokio 0.2.25", - "url", + "tokio", "uuid", ] [[package]] name = "grin_wallet_impls" -version = "5.4.0-alpha.1" +version = "5.4.1" dependencies = [ + "arti-client", "base64 0.12.3", "blake2-rfc", - "byteorder", + "bytes 1.12.0", "chrono", - "data-encoding", "ed25519-dalek", + "fs-mistrust", + "fslock-guard", "futures 0.3.32", "grin_api", "grin_chain", "grin_core", "grin_keychain", - "grin_store", "grin_util", "grin_wallet_config", "grin_wallet_libwallet", "grin_wallet_util", + "http-body-util", + "hyper", + "hyper-util", "lazy_static", "log", "rand 0.6.5", "regex", - "remove_dir_all", "reqwest", - "ring 0.16.20", + "ring", "serde", "serde_derive", "serde_json", - "sysinfo", + "sha2 0.10.9", + "sysinfo 0.29.11", "thiserror 1.0.69", "timer", - "tokio 0.2.25", + "tokio", + "tor-hscrypto", + "tor-hsrproxy", + "tor-hsservice", + "tor-keymgr", + "tor-llcrypto", + "tor-rtcompat", "url", - "uuid", - "x25519-dalek 0.6.0", ] [[package]] name = "grin_wallet_libwallet" -version = "5.4.0-alpha.1" +version = "5.4.1" dependencies = [ "age", "base64 0.9.3", "bech32 0.7.3", "blake2-rfc", - "bs58", + "bs58 0.3.1", "byteorder", - "chacha20", + "chacha20 0.8.2", "chrono", - "curve25519-dalek 2.1.3", + "curve25519-dalek 5.0.0", "ed25519-dalek", "grin_core", "grin_keychain", @@ -1682,73 +2685,73 @@ dependencies = [ "hmac 0.12.1", "lazy_static", "log", - "num-bigint", + "num-bigint 0.2.6", "rand 0.6.5", "regex", - "secrecy 0.6.0", "serde", "serde_derive", "serde_json", - "serde_with", + "serde_with 1.14.0", "sha2 0.10.9", - "strum", - "strum_macros", + "strum 0.18.0", + "strum_macros 0.18.0", "thiserror 1.0.69", "uuid", - "x25519-dalek 0.6.0", + "x25519-dalek 2.0.1", ] [[package]] name = "grin_wallet_util" -version = "5.4.0-alpha.1" +version = "5.4.1" dependencies = [ "data-encoding", "ed25519-dalek", "grin_util", - "pretty_assertions", - "rand 0.6.5", "serde", "serde_derive", - "sha3", + "sha3 0.8.2", "thiserror 1.0.69", ] [[package]] -name = "h2" -version = "0.2.7" +name = "group" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e4728fd124914ad25e99e3d15a9361a879f6620f63cb56bbb08f95abb97a535" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ - "bytes 0.5.6", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http", - "indexmap 1.9.3", - "slab", - "tokio 0.2.25", - "tokio-util 0.3.1", - "tracing", - "tracing-futures", + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "growable-bloom-filter" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d174ccb4ba660d431329e7f0797870d0a4281e36353ec4b4a3c5eab6c2cfb6f1" +dependencies = [ + "serde", + "serde_bytes", + "serde_derive", + "xxhash-rust", ] [[package]] name = "h2" -version = "0.3.27" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" +checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" dependencies = [ - "bytes 1.11.1", + "atomic-waker", + "bytes 1.12.0", "fnv", "futures-core", "futures-sink", - "futures-util", "http", "indexmap 2.14.0", "slab", - "tokio 1.52.3", - "tokio-util 0.7.18", + "tokio", + "tokio-util", "tracing", ] @@ -1770,7 +2773,16 @@ version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ - "foldhash", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash 0.2.0", ] [[package]] @@ -1779,6 +2791,15 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "hashlink" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" +dependencies = [ + "hashbrown 0.16.1", +] + [[package]] name = "heck" version = "0.3.3" @@ -1800,7 +2821,7 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad82d6598ccf1dac15c8b758a1bd282b755b6776be600429176757190a1b0202" dependencies = [ - "bitflags 2.12.1", + "bitflags 2.13.0", "byteorder", "heed-traits", "heed-types", @@ -1825,7 +2846,7 @@ version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c255bdf46e07fb840d120a36dcc81f385140d7191c76a7391672675c01a55d" dependencies = [ - "bincode", + "bincode 1.3.3", "byteorder", "heed-traits", "serde", @@ -1848,13 +2869,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" [[package]] -name = "hkdf" -version = "0.11.0" +name = "hex" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01706d578d5c281058480e673ae4086a9f4710d8df1ad80a5b03e39ece5f886b" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" dependencies = [ - "digest 0.9.0", - "hmac 0.11.0", + "hmac 0.12.1", ] [[package]] @@ -1876,36 +2902,43 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "hostname-validator" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f558a64ac9af88b5ba400d99b579451af0d39c6d360980045b91aac966d705e2" + [[package]] name = "http" -version = "0.2.12" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" dependencies = [ - "bytes 1.11.1", - "fnv", - "itoa 1.0.18", + "bytes 1.12.0", + "itoa", ] [[package]] name = "http-body" -version = "0.3.1" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13d5ff830006f7646652e057693569bfe0d51760c0085a071769d142a205111b" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" dependencies = [ - "bytes 0.5.6", + "bytes 1.12.0", "http", ] [[package]] -name = "http-body" -version = "0.4.6" +name = "http-body-util" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.0", + "futures-core", "http", - "pin-project-lite 0.2.17", + "http-body", + "pin-project-lite", ] [[package]] @@ -1914,12 +2947,6 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" -[[package]] -name = "httpdate" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494b4d60369511e7dea41cf646832512a94e542f68bb9c49e54518e0f468eb47" - [[package]] name = "httpdate" version = "1.0.3" @@ -1928,112 +2955,113 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "humantime" -version = "2.3.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" +checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" +dependencies = [ + "quick-error", +] [[package]] -name = "hyper" -version = "0.13.10" +name = "humantime" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a6f157065790a3ed2f88679250419b5cdd96e714a0d65f7797fd337186e96bb" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + +[[package]] +name = "humantime-serde" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c" dependencies = [ - "bytes 0.5.6", - "futures-channel", - "futures-core", - "futures-util", - "h2 0.2.7", - "http", - "http-body 0.3.1", - "httparse", - "httpdate 0.3.2", - "itoa 0.4.8", - "pin-project", - "socket2 0.3.19", - "tokio 0.2.25", - "tower-service", - "tracing", - "want", + "humantime 2.4.0", + "serde", +] + +[[package]] +name = "hybrid-array" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" +dependencies = [ + "typenum", ] [[package]] name = "hyper" -version = "0.14.32" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" +checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" dependencies = [ - "bytes 1.11.1", + "atomic-waker", + "bytes 1.12.0", "futures-channel", "futures-core", - "futures-util", - "h2 0.3.27", + "h2", "http", - "http-body 0.4.6", + "http-body", "httparse", - "httpdate 1.0.3", - "itoa 1.0.18", - "pin-project-lite 0.2.17", - "socket2 0.5.10", - "tokio 1.52.3", - "tower-service", - "tracing", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", "want", ] [[package]] name = "hyper-rustls" -version = "0.21.0" +version = "0.27.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37743cc83e8ee85eacfce90f2f4102030d9ff0a95244098d781e9bee4a90abb6" -dependencies = [ - "bytes 0.5.6", - "futures-util", - "hyper 0.13.10", - "log", - "rustls 0.18.1", - "tokio 0.2.25", - "tokio-rustls 0.14.1", - "webpki 0.21.4", -] - -[[package]] -name = "hyper-rustls" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ "http", - "hyper 0.14.32", + "hyper", + "hyper-util", "log", - "rustls 0.20.9", + "rustls", "rustls-native-certs", - "tokio 1.52.3", - "tokio-rustls 0.23.4", + "tokio", + "tokio-rustls", + "tower-service", ] [[package]] name = "hyper-timeout" -version = "0.4.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbb958482e8c7be4bc3cf272a766a2b0bf1a6755e7a6ae777f017a31d11b13b1" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" dependencies = [ - "hyper 0.14.32", - "pin-project-lite 0.2.17", - "tokio 1.52.3", - "tokio-io-timeout", + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", ] [[package]] -name = "hyper-tls" -version = "0.4.3" +name = "hyper-util" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d979acc56dcb5b8dddba3917601745e877576475aa046df3226eabdecef78eed" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ - "bytes 0.5.6", - "hyper 0.13.10", - "native-tls", - "tokio 0.2.25", - "tokio-tls", + "base64 0.22.1", + "bytes 1.12.0", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", ] [[package]] @@ -2064,7 +3092,7 @@ dependencies = [ "intl-memoizer", "lazy_static", "log", - "parking_lot 0.12.5", + "parking_lot", "rust-embed", "thiserror 1.0.69", "unic-langid", @@ -2086,9 +3114,9 @@ dependencies = [ "lazy_static", "proc-macro-error", "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "strsim 0.10.0", - "syn 2.0.117", + "syn 2.0.118", "unic-langid", ] @@ -2101,8 +3129,8 @@ dependencies = [ "find-crate", "i18n-config", "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -2211,12 +3239,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "ident_case" version = "1.0.1" @@ -2244,6 +3266,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "imara-diff" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f01d462f766df78ab820dd06f5eb700233c51f0f4c2e846520eaf4ba6aa5c5c" +dependencies = [ + "hashbrown 0.15.5", + "memchr", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -2252,6 +3284,7 @@ checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" dependencies = [ "autocfg 1.5.1", "hashbrown 0.12.3", + "serde", ] [[package]] @@ -2266,6 +3299,35 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inotify" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "533e68a5842e734946fe159fb03fc9bbbb254f590dd0d8ad321ae5ff7beca2c1" +dependencies = [ + "bitflags 2.13.0", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ea94e891b3606826e9c998be69ddca42247dad8ad50b1649a5cb7e1c9ae06fd" +dependencies = [ + "libc", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array 0.14.7", +] + [[package]] name = "intl-memoizer" version = "0.5.3" @@ -2286,14 +3348,20 @@ dependencies = [ ] [[package]] -name = "iovec" -version = "0.1.4" +name = "inventory" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e" +checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b" dependencies = [ - "libc", + "rustversion", ] +[[package]] +name = "io_tee" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b3f7cef34251886990511df1c61443aa928499d598a9473929ab5a90a527304" + [[package]] name = "ipnet" version = "2.12.0" @@ -2312,10 +3380,22 @@ dependencies = [ ] [[package]] -name = "itoa" -version = "0.4.8" +name = "itertools" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] [[package]] name = "itoa" @@ -2323,6 +3403,55 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if 1.0.4", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror 2.0.18", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "rustc_version", + "simd_cesu8", + "syn 2.0.118", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote 1.0.46", + "syn 2.0.118", +] + [[package]] name = "jobserver" version = "0.1.34" @@ -2335,13 +3464,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.99" +version = "0.3.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11" +checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" dependencies = [ "cfg-if 1.0.4", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -2358,23 +3486,53 @@ dependencies = [ "serde_json", ] +[[package]] +name = "k12" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4dc5fdb62af2f520116927304f15d25b3c2667b4817b90efdc045194c912c54" +dependencies = [ + "digest 0.10.7", + "sha3 0.10.9", +] + [[package]] name = "keccak" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653" dependencies = [ - "cpufeatures", + "cpufeatures 0.2.17", ] [[package]] -name = "kernel32-sys" -version = "0.2.2" +name = "keccak" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +checksum = "9e24a010dd405bd7ed803e5253182815b41bf2e6a80cc3bfc066658e03a198aa" dependencies = [ - "winapi 0.2.8", - "winapi-build", + "cfg-if 1.0.4", + "cpufeatures 0.3.0", +] + +[[package]] +name = "kqueue" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "273c0752728918e0ac4976f2b275b6fefb9ecd400585dec929419f3844cd87b5" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags 2.13.0", + "libc", ] [[package]] @@ -2382,12 +3540,9 @@ name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" +dependencies = [ + "spin", +] [[package]] name = "libc" @@ -2408,14 +3563,51 @@ dependencies = [ ] [[package]] -name = "libredox" -version = "0.1.17" +name = "liblzma" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f02ab6bace2054fb888a3c16f990117b579d14a3088e472d63c6011fa185c9d3" +checksum = "45aec2360b3933207e27908049d8e4df4e476b58180afb1e56b2a4fb72efe4ba" +dependencies = [ + "liblzma-sys", +] + +[[package]] +name = "liblzma-sys" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a046c7f353ba30f810545151e04f63545833803f5b86ee3ddf1517247fe560a5" +dependencies = [ + "cc", + "libc", + "pkg-config", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652" dependencies = [ "libc", ] +[[package]] +name = "libsqlite3-sys" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "libz-sys" version = "1.1.29" @@ -2436,7 +3628,7 @@ checksum = "28715d08e35c6c074f9ae6b2e6a2420bac75d050c66ecd669d7d5b98e2caa036" dependencies = [ "dirs 1.0.5", "mortal", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -2445,6 +3637,12 @@ version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -2468,15 +3666,6 @@ dependencies = [ "libc", ] -[[package]] -name = "lock_api" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4da24a77a3d8a6d4862d95f72e6fdb9c09a643ecdb402d754004a557f2bec75" -dependencies = [ - "scopeguard", -] - [[package]] name = "lock_api" version = "0.4.14" @@ -2488,9 +3677,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.31" +version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "113b30b4cd05f7c06868fdb2854f66a7b9fece9a48425351cd532e810d74024f" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" dependencies = [ "serde_core", ] @@ -2513,12 +3702,12 @@ dependencies = [ "derive_more", "flate2", "fnv", - "humantime", + "humantime 2.4.0", "libc", "log", "log-mdc", "mock_instant", - "parking_lot 0.12.5", + "parking_lot", "rand 0.9.4", "serde", "serde-value", @@ -2528,7 +3717,7 @@ dependencies = [ "thread-id", "typemap-ors", "unicode-segmentation", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -2541,10 +3730,25 @@ dependencies = [ ] [[package]] -name = "memchr" -version = "2.8.1" +name = "lru-slab" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" [[package]] name = "memmap" @@ -2553,7 +3757,37 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" dependencies = [ "libc", - "winapi 0.3.9", + "winapi", +] + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg 1.5.1", +] + +[[package]] +name = "merlin" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58c38e2799fc0978b65dfff8023ec7843e2330bb462f19198840b34b6582397d" +dependencies = [ + "byteorder", + "keccak 0.1.6", + "rand_core 0.6.4", + "zeroize", ] [[package]] @@ -2562,16 +3796,6 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" -[[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" -dependencies = [ - "mime", - "unicase", -] - [[package]] name = "minimal-lexical" version = "0.2.1" @@ -2588,25 +3812,6 @@ dependencies = [ "simd-adler32", ] -[[package]] -name = "mio" -version = "0.6.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4afd66f5b91bf2a3bc13fad0e21caedac168ca4c707504e75585648ae80e4cc4" -dependencies = [ - "cfg-if 0.1.10", - "fuchsia-zircon", - "fuchsia-zircon-sys", - "iovec", - "kernel32-sys", - "libc", - "log", - "miow 0.2.2", - "net2", - "slab", - "winapi 0.2.8", -] - [[package]] name = "mio" version = "1.2.1" @@ -2614,59 +3819,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" dependencies = [ "libc", + "log", "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.61.2", ] -[[package]] -name = "mio-named-pipes" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0840c1c50fd55e521b247f949c241c9997709f23bd7f023b9762cd561e935656" -dependencies = [ - "log", - "mio 0.6.23", - "miow 0.3.7", - "winapi 0.3.9", -] - -[[package]] -name = "mio-uds" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afcb699eb26d4332647cc848492bbc15eafb26f08d0304550d5aa1f612e066f0" -dependencies = [ - "iovec", - "libc", - "mio 0.6.23", -] - -[[package]] -name = "miow" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebd808424166322d4a38da87083bfddd3ac4c131334ed55856112eb06d46944d" -dependencies = [ - "kernel32-sys", - "net2", - "winapi 0.2.8", - "ws2_32-sys", -] - -[[package]] -name = "miow" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" -dependencies = [ - "winapi 0.3.9", -] - [[package]] name = "mock_instant" -version = "0.6.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce6dd36094cac388f119d2e9dc82dc730ef91c32a6222170d630e5414b956e6" +checksum = "9bb517913cfcfb9eeda59f36020269075a152701a01606c612f547e4890be399" [[package]] name = "mortal" @@ -2674,14 +3836,14 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c624fa1b7aab6bd2aff6e9b18565cc0363b6d45cbcd7465c9ed5e3740ebf097" dependencies = [ - "bitflags 2.12.1", + "bitflags 2.13.0", "libc", "nix 0.26.4", "smallstr", "terminfo", "unicode-normalization", "unicode-width", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -2693,35 +3855,34 @@ dependencies = [ "libc", "log", "openssl", - "openssl-probe 0.2.1", + "openssl-probe", "openssl-sys", "schannel", - "security-framework 3.7.0", + "security-framework", "security-framework-sys", "tempfile", ] [[package]] -name = "net2" -version = "0.2.39" +name = "nibble_vec" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b13b648036a2339d06de780866fbdfda0dde886de7b3af2ddeba8b14f4ee34ac" +checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43" dependencies = [ - "cfg-if 0.1.10", - "libc", - "winapi 0.3.9", + "smallvec", ] [[package]] name = "nix" -version = "0.18.0" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83450fe6a6142ddd95fb064b746083fc4ef1705fe81f64a64e1d4b39f54a1055" +checksum = "8f3790c00a0150112de0f4cd161e3d7fc4b2d8a5542ffc35f099a2562aecb35c" dependencies = [ "bitflags 1.3.2", "cc", - "cfg-if 0.1.10", + "cfg-if 1.0.4", "libc", + "memoffset", ] [[package]] @@ -2751,13 +3912,54 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "nonany" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b8866ec53810a9a4b3d434a29801e78c707430a9ae11c2db4b8b62bb9675a0" + +[[package]] +name = "notify" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" +dependencies = [ + "bitflags 2.13.0", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "walkdir", + "windows-sys 0.60.2", +] + +[[package]] +name = "notify-types" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" +dependencies = [ + "bitflags 2.13.0", +] + [[package]] name = "ntapi" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" dependencies = [ - "winapi 0.3.9", + "winapi", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", ] [[package]] @@ -2766,7 +3968,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8536030f9fea7127f841b45bb6243b27255787fb4eb83958aa1ef9d2fdc0c36" dependencies = [ - "num-bigint", + "num-bigint 0.2.6", "num-complex", "num-integer", "num-iter", @@ -2785,6 +3987,32 @@ dependencies = [ "num-traits 0.2.19", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits 0.2.19", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits 0.2.19", + "rand 0.8.6", + "smallvec", + "zeroize", +] + [[package]] name = "num-complex" version = "0.2.4" @@ -2795,6 +4023,12 @@ dependencies = [ "num-traits 0.2.19", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-integer" version = "0.1.46" @@ -2822,7 +4056,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c000134b5dbf44adc5cb772486d335293351644b801551abe8f75c84cfa4aef" dependencies = [ "autocfg 1.5.1", - "num-bigint", + "num-bigint 0.2.6", "num-integer", "num-traits 0.2.19", ] @@ -2843,16 +4077,48 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg 1.5.1", + "libm", ] [[package]] -name = "num_cpus" -version = "1.17.0" +name = "num_enum" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.0", +] + +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" dependencies = [ - "hermit-abi 0.5.2", "libc", + "objc2-core-foundation", ] [[package]] @@ -2870,6 +4136,15 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "oneshot-fused-workaround" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60d6f8f565703c8a15f98b7782e39526490f8c291910d80c9be54a753a822f6f" +dependencies = [ + "futures 0.3.32", +] + [[package]] name = "opaque-debug" version = "0.2.3" @@ -2884,11 +4159,11 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "openssl" -version = "0.10.80" +version = "0.10.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a45fa2aa886c42762255da344f0a0d313e254066c46aad76f300c3d3da62d967" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" dependencies = [ - "bitflags 2.12.1", + "bitflags 2.13.0", "cfg-if 1.0.4", "foreign-types", "libc", @@ -2903,16 +4178,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] -[[package]] -name = "openssl-probe" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" - [[package]] name = "openssl-probe" version = "0.2.1" @@ -2920,17 +4189,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" [[package]] -name = "openssl-sys" -version = "0.9.116" +name = "openssl-src" +version = "300.6.1+3.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28a22dc7140cda5f096e5e7724a6962ca81a7f8bfd2979f9b18c11af56318c4" +checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" +dependencies = [ + "cc", +] + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" dependencies = [ "cc", "libc", + "openssl-src", "pkg-config", "vcpkg", ] +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "ordered-float" version = "2.10.1" @@ -2941,12 +4226,50 @@ dependencies = [ ] [[package]] -name = "output_vt100" -version = "0.1.3" +name = "os_str_bytes" +version = "6.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "628223faebab4e3e40667ee0b2336d34a5b960ff60ea743ddfdbcf7770bcfb66" +checksum = "e2355d85b9a3786f481747ced0e0ff2ba35213a1f9bd406ed906554d7af805a1" dependencies = [ - "winapi 0.3.9", + "memchr", +] + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p521" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc9e2161f1f215afdfce23677034ae137bbd45016a880c2eb3ba8eb95f085b2" +dependencies = [ + "base16ct", + "ecdsa", + "elliptic-curve", + "primeorder", + "rand_core 0.6.4", + "sha2 0.10.9", ] [[package]] @@ -2956,18 +4279,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" dependencies = [ "libc", - "winapi 0.3.9", + "winapi", ] [[package]] -name = "parking_lot" -version = "0.10.2" +name = "parking" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3a704eb390aafdc107b0e392f56a82b668e3a71366993b5340f5833fd62505e" -dependencies = [ - "lock_api 0.3.4", - "parking_lot_core 0.7.3", -] +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" [[package]] name = "parking_lot" @@ -2975,22 +4294,8 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ - "lock_api 0.4.14", - "parking_lot_core 0.9.12", -] - -[[package]] -name = "parking_lot_core" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b93f386bb233083c799e6e642a9d73db98c24a5deeb95ffc85bf281255dffc98" -dependencies = [ - "cfg-if 0.1.10", - "cloudabi", - "libc", - "redox_syscall 0.1.57", - "smallvec", - "winapi 0.3.9", + "lock_api", + "parking_lot_core", ] [[package]] @@ -3008,15 +4313,21 @@ dependencies = [ [[package]] name = "password-hash" -version = "0.2.3" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77e0b28ace46c5a396546bcf443bf422b57049617433d8854227352a4a9b24e7" +checksum = "c1a5d4e9c205d2c1ae73b84aab6240e98218c0e72e63b50422cfb2d1ca952282" dependencies = [ "base64ct", "rand_core 0.6.4", "subtle", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "pbkdf2" version = "0.8.0" @@ -3039,6 +4350,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -3051,8 +4371,19 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ - "phf_macros", - "phf_shared", + "phf_macros 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", + "serde", ] [[package]] @@ -3061,8 +4392,8 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.11.3", + "phf_shared 0.11.3", ] [[package]] @@ -3071,21 +4402,44 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ - "phf_shared", + "phf_shared 0.11.3", "rand 0.8.6", ] +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + [[package]] name = "phf_macros" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.11.3", + "phf_shared 0.11.3", "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -3097,6 +4451,15 @@ dependencies = [ "siphasher 1.0.3", ] +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher 1.0.3", +] + [[package]] name = "pin-project" version = "1.1.13" @@ -3113,22 +4476,37 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] -[[package]] -name = "pin-project-lite" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "257b64915a082f7811703966789728173279bdebb956b143dbcd23f6f970a777" - [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.33" @@ -3141,11 +4519,26 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "048aeb476be11a4b6ca432ca569e375810de9294ae78f4774e78ea98a9246ede" dependencies = [ - "cpufeatures", + "cpufeatures 0.2.17", "opaque-debug 0.3.1", "universal-hash", ] +[[package]] +name = "postage" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1" +dependencies = [ + "atomic 0.5.3", + "crossbeam-queue", + "futures 0.3.32", + "parking_lot", + "pin-project", + "static_assertions", + "thiserror 1.0.69", +] + [[package]] name = "potential_utf" version = "0.1.5" @@ -3155,6 +4548,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -3164,28 +4563,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "pretty_assertions" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f81e1644e1b54f5a68959a29aa86cde704219254669da328ecfdf6a1f09d427" -dependencies = [ - "ansi_term 0.11.0", - "ctor", - "difference", - "output_vt100", -] - -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2 1.0.106", - "syn 2.0.117", -] - [[package]] name = "prettytable-rs" version = "0.10.0" @@ -3200,6 +4577,35 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "priority-queue" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93980406f12d9f8140ed5abe7155acb10bb1e69ea55c88960b9c2f117445ef96" +dependencies = [ + "equivalent", + "indexmap 2.14.0", + "serde", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.12+spec-1.1.0", +] + [[package]] name = "proc-macro-error" version = "1.0.4" @@ -3208,7 +4614,7 @@ checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" dependencies = [ "proc-macro-error-attr", "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "syn 1.0.109", "version_check", ] @@ -3220,7 +4626,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "version_check", ] @@ -3242,12 +4648,87 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pwd-grp" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e2023f41b5fcb7c30eb5300a5733edfaa9e0e0d502d51b586f65633fd39e40c" +dependencies = [ + "derive-deftly", + "libc", + "paste", + "thiserror 2.0.18", +] + [[package]] name = "qr_code" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5520fbcd7da152a449261c5a533a1c7fad044e9e8aa9528cfec3f464786c7926" +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes 1.12.0", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +dependencies = [ + "aws-lc-rs", + "bytes 1.12.0", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg 0.10.2", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "0.6.13" @@ -3259,9 +4740,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.45" +version = "1.0.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" dependencies = [ "proc-macro2 1.0.106", ] @@ -3278,6 +4759,22 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "radix_trie" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c069c179fcdc6a2fe24d8d18305cf085fdbd4f922c041943e203685d6a1c58fd" +dependencies = [ + "endian-type", + "nibble_vec", +] + [[package]] name = "rand" version = "0.5.6" @@ -3288,7 +4785,7 @@ dependencies = [ "fuchsia-cprng", "libc", "rand_core 0.3.1", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -3303,11 +4800,11 @@ dependencies = [ "rand_core 0.4.2", "rand_hc 0.1.0", "rand_isaac", - "rand_jitter", + "rand_jitter 0.1.4", "rand_os", - "rand_pcg", + "rand_pcg 0.1.2", "rand_xorshift", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -3344,6 +4841,17 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20 0.10.1", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + [[package]] name = "rand_chacha" version = "0.1.1" @@ -3384,6 +4892,16 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_chacha" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e6af7f3e25ded52c41df4e0b1af2d047e45896c2f3281792ed68a1c243daedb" +dependencies = [ + "ppv-lite86", + "rand_core 0.10.1", +] + [[package]] name = "rand_core" version = "0.3.1" @@ -3426,6 +4944,12 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "rand_hc" version = "0.1.0" @@ -3461,7 +4985,18 @@ checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" dependencies = [ "libc", "rand_core 0.4.2", - "winapi 0.3.9", + "winapi", +] + +[[package]] +name = "rand_jitter" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdcd80e68f0a8f9ca5ec7cfd02fd5fbb8fbe6ef4e9b90ea2f48bb929b74f88e" +dependencies = [ + "libc", + "rand_core 0.10.1", + "windows-sys 0.59.0", ] [[package]] @@ -3474,8 +5009,8 @@ dependencies = [ "fuchsia-cprng", "libc", "rand_core 0.4.2", - "rdrand", - "winapi 0.3.9", + "rdrand 0.4.0", + "winapi", ] [[package]] @@ -3488,6 +5023,15 @@ dependencies = [ "rand_core 0.4.2", ] +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "rand_xorshift" version = "0.1.1" @@ -3497,6 +5041,12 @@ dependencies = [ "rand_core 0.3.1", ] +[[package]] +name = "rangemap" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68" + [[package]] name = "rayon" version = "1.12.0" @@ -3526,6 +5076,15 @@ dependencies = [ "rand_core 0.3.1", ] +[[package]] +name = "rdrand" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92195228612ac8eed47adbc2ed0f04e513a4ccb98175b6f2bd04d963b533655" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "redox_syscall" version = "0.1.57" @@ -3538,7 +5097,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.12.1", + "bitflags 2.13.0", ] [[package]] @@ -3564,10 +5123,41 @@ dependencies = [ ] [[package]] -name = "regex" -version = "1.12.3" +name = "redox_users" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 2.0.18", +] + +[[package]] +name = "ref-cast" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "regex" +version = "1.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" dependencies = [ "aho-corasick", "memchr", @@ -3588,76 +5178,75 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.10" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" - -[[package]] -name = "remove_dir_all" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "882f368737489ea543bc5c340e6f3d34a28c39980bd9a979e47322b26f60ac40" -dependencies = [ - "libc", - "log", - "num_cpus", - "rayon", - "winapi 0.3.9", -] +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "reqwest" -version = "0.10.10" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0718f81a8e14c4dbb3b34cf23dc6aaf9ab8a0dfec160c534b3dbca1aaa21f47c" +checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" dependencies = [ - "base64 0.13.1", - "bytes 0.5.6", + "base64 0.22.1", + "bytes 1.12.0", "encoding_rs", "futures-core", - "futures-util", + "h2", "http", - "http-body 0.3.1", - "hyper 0.13.10", - "hyper-rustls 0.21.0", - "hyper-tls", - "ipnet", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", "js-sys", - "lazy_static", "log", "mime", - "mime_guess", - "native-tls", "percent-encoding", - "pin-project-lite 0.2.17", - "rustls 0.18.1", - "serde", - "serde_urlencoded", - "tokio 0.2.25", - "tokio-rustls 0.14.1", - "tokio-socks", - "tokio-tls", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "webpki-roots", - "winreg", ] [[package]] -name = "ring" -version = "0.16.20" +name = "reseeding_rng" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +checksum = "ecfc8e855ab517235426ec1290bfb0745e73fa478b29619eb66a2a81be9d8716" dependencies = [ - "cc", - "libc", - "once_cell", - "spin", - "untrusted 0.7.1", - "web-sys", - "winapi 0.3.9", + "rand_core 0.10.1", +] + +[[package]] +name = "retry-error" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c0e06f9b501df8600ad8bd073f4990f703f36e0f48e574b431f4a15d69b449" +dependencies = [ + "humantime 2.4.0", + "web-time", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", ] [[package]] @@ -3670,7 +5259,7 @@ dependencies = [ "cfg-if 1.0.4", "getrandom 0.2.17", "libc", - "untrusted 0.9.0", + "untrusted", "windows-sys 0.52.0", ] @@ -3687,12 +5276,70 @@ dependencies = [ [[package]] name = "rpassword" -version = "4.0.5" +version = "7.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99371657d3c8e4d816fb6221db98fa408242b0b53bac08f8676a41f8554fe99f" +checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196" dependencies = [ "libc", - "winapi 0.3.9", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits 0.2.19", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "sha2 0.10.9", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror 2.0.18", +] + +[[package]] +name = "rtoolbox" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50a0e551c1e27e1731aba276dbeaeac73f53c7cd34d1bda485d02bd1e0f36844" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "rusqlite" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0d2b0146dd9661bf67bb107c0bb2a55064d556eeb3fc314151b957f313bcd4e" +dependencies = [ + "bitflags 2.13.0", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", + "time", ] [[package]] @@ -3725,9 +5372,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49b94b81e5b2c284684141a2fb9e2a31be90638caf040bf9afbc5a0416afe1ac" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "rust-embed-utils", - "syn 2.0.117", + "syn 2.0.118", "walkdir", ] @@ -3755,9 +5402,9 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" [[package]] name = "rustc-hash" -version = "2.1.2" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" [[package]] name = "rustc_version" @@ -3765,7 +5412,29 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" dependencies = [ - "semver 1.0.28", + "semver", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.0", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", ] [[package]] @@ -3774,48 +5443,39 @@ version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags 2.12.1", + "bitflags 2.13.0", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.12.1", "windows-sys 0.61.2", ] [[package]] name = "rustls" -version = "0.18.1" +version = "0.23.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d1126dcf58e93cee7d098dbda643b5f92ed724f1f6a63007c1116eed6700c81" +checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" dependencies = [ - "base64 0.12.3", + "aws-lc-rs", "log", - "ring 0.16.20", - "sct 0.6.1", - "webpki 0.21.4", -] - -[[package]] -name = "rustls" -version = "0.20.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b80e3dec595989ea8510028f30c408a4630db12c9cbb8de34203b89d6577e99" -dependencies = [ - "log", - "ring 0.16.20", - "sct 0.7.1", - "webpki 0.22.4", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", ] [[package]] name = "rustls-native-certs" -version = "0.6.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" dependencies = [ - "openssl-probe 0.1.6", - "rustls-pemfile", + "openssl-probe", + "rustls-pki-types", "schannel", - "security-framework 2.11.1", + "security-framework", ] [[package]] @@ -3827,6 +5487,55 @@ dependencies = [ "base64 0.21.7", ] +[[package]] +name = "rustls-pki-types" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.22" @@ -3835,21 +5544,26 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "rustyline" -version = "6.3.0" +version = "9.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f0d5e7b0219a3eadd5439498525d4765c59b7c993ef0c12244865cd2d988413" +checksum = "db7826789c0e25614b03e5a54a0717a86f9ff6e6e5247f92b369472869320039" dependencies = [ - "cfg-if 0.1.10", - "dirs-next 1.0.2", + "bitflags 1.3.2", + "cfg-if 1.0.4", + "clipboard-win", + "dirs-next", + "fd-lock", "libc", "log", "memchr", - "nix 0.18.0", + "nix 0.23.2", + "radix_trie", "scopeguard", + "smallvec", "unicode-segmentation", "unicode-width", "utf8parse", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -3858,6 +5572,19 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "safelog" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c0812d386a9992c036500b92565c41f84c28fd2e48fe853a395c393261b730b" +dependencies = [ + "derive_more", + "educe", + "either", + "fluid-let", + "thiserror 2.0.18", +] + [[package]] name = "safemem" version = "0.3.3" @@ -3866,11 +5593,11 @@ checksum = "ef703b7cb59335eae2eb93ceb664c0eb7ea6bf567079d843e09420219668e072" [[package]] name = "salsa20" -version = "0.9.0" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0fbb5f676da676c260ba276a8f43a8dc67cf02d1438423aeb1c677a7212686" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" dependencies = [ - "cipher", + "cipher 0.4.4", ] [[package]] @@ -3882,6 +5609,21 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "sanitize-filename" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc984f4f9ceb736a7bb755c3e3bd17dc56370af2600c9780dcc48c66453da34d" +dependencies = [ + "regex", +] + +[[package]] +name = "saturating-time" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "802bdbfcca9a239cb46eeaaedea507e37bb13ba1a673762d2e2ef7a9dac63144" + [[package]] name = "schannel" version = "0.1.29" @@ -3891,6 +5633,30 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -3899,9 +5665,9 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "scrypt" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e73d6d7c6311ebdbd9184ad6c4447b2f36337e327bda107d3ba9e3c374f9d325" +checksum = "ba0aaf3911fff0d942c10a49779de7754699810fc7dbe3df515613b2ecc8195a" dependencies = [ "hmac 0.12.1", "pbkdf2 0.10.1", @@ -3910,31 +5676,16 @@ dependencies = [ ] [[package]] -name = "sct" -version = "0.6.1" +name = "sec1" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce" -dependencies = [ - "ring 0.16.20", - "untrusted 0.7.1", -] - -[[package]] -name = "sct" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" -dependencies = [ - "ring 0.17.14", - "untrusted 0.9.0", -] - -[[package]] -name = "secrecy" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9182278ed645df3477a9c27bfee0621c621aa16f6972635f7f795dae3d81070f" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ + "base16ct", + "der", + "generic-array 0.14.7", + "pkcs8", + "subtle", "zeroize", ] @@ -3947,26 +5698,13 @@ dependencies = [ "zeroize", ] -[[package]] -name = "security-framework" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags 2.12.1", - "core-foundation 0.9.4", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - [[package]] name = "security-framework" version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.12.1", + "bitflags 2.13.0", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -3998,27 +5736,12 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b12e76d157a900eb52e81bc6e9f3069344290341720e9178cde2407113ac8d89" -[[package]] -name = "semver" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "394cec28fa623e00903caf7ba4fa6fb9a0e260280bb8cdbbba029611108a0190" -dependencies = [ - "semver-parser", -] - [[package]] name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - [[package]] name = "serde" version = "1.0.228" @@ -4039,6 +5762,16 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.228" @@ -4055,8 +5788,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "serde_ignored" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798" +dependencies = [ + "serde", + "serde_core", ] [[package]] @@ -4065,7 +5808,7 @@ version = "1.0.150" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" dependencies = [ - "itoa 1.0.18", + "itoa", "memchr", "serde", "serde_core", @@ -4073,17 +5816,23 @@ dependencies = [ ] [[package]] -name = "serde_urlencoded" -version = "0.7.1" +name = "serde_spanned" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" dependencies = [ - "form_urlencoded", - "itoa 1.0.18", - "ryu", "serde", ] +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_with" version = "1.14.0" @@ -4092,7 +5841,27 @@ checksum = "678b5a069e50bf00ecd22d0cd8ddf7c236f68581b03db652061ed5eb13a312ff" dependencies = [ "chrono", "serde", - "serde_with_macros", + "serde_with_macros 1.5.2", +] + +[[package]] +name = "serde_with" +version = "3.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c" +dependencies = [ + "base64 0.22.1", + "bs58 0.5.1", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.0", + "schemars 0.9.0", + "schemars 1.2.1", + "serde_core", + "serde_json", + "serde_with_macros 3.21.0", + "time", ] [[package]] @@ -4101,12 +5870,24 @@ version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e182d6ec6f05393cc0e5ed1bf81ad6db3a8feedf8ee515ecdd369809bcce8082" dependencies = [ - "darling", + "darling 0.13.4", "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "syn 1.0.109", ] +[[package]] +name = "serde_with_macros" +version = "3.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660" +dependencies = [ + "darling 0.23.0", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + [[package]] name = "serde_yaml" version = "0.9.34+deprecated" @@ -4114,12 +5895,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" dependencies = [ "indexmap 2.14.0", - "itoa 1.0.18", + "itoa", "ryu", "serde", "unsafe-libyaml", ] +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if 1.0.4", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha2" version = "0.9.9" @@ -4128,7 +5920,7 @@ checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" dependencies = [ "block-buffer 0.9.0", "cfg-if 1.0.4", - "cpufeatures", + "cpufeatures 0.2.17", "digest 0.9.0", "opaque-debug 0.3.1", ] @@ -4140,7 +5932,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if 1.0.4", - "cpufeatures", + "cpufeatures 0.2.17", "digest 0.10.7", ] @@ -4153,10 +5945,51 @@ dependencies = [ "block-buffer 0.7.3", "byte-tools", "digest 0.8.1", - "keccak", + "keccak 0.1.6", "opaque-debug 0.2.3", ] +[[package]] +name = "sha3" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874" +dependencies = [ + "digest 0.10.7", + "keccak 0.1.6", +] + +[[package]] +name = "sha3" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759" +dependencies = [ + "digest 0.11.3", + "keccak 0.2.0", + "sponge-cursor", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shellexpand" +version = "3.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8" +dependencies = [ + "bstr", + "dirs 6.0.0", + "os_str_bytes", +] + [[package]] name = "shlex" version = "2.0.1" @@ -4175,9 +6008,13 @@ dependencies = [ [[package]] name = "signature" -version = "1.6.4" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] [[package]] name = "simd-adler32" @@ -4185,6 +6022,22 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simd_cesu8" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "siphasher" version = "0.3.11" @@ -4203,6 +6056,29 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "serde", + "version_check", +] + +[[package]] +name = "slotmap-careful" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7cd5208f878dce99cfbefa73c692c67edf946ac53e0cc4455e2dabe43d54af7" +dependencies = [ + "paste", + "serde", + "slotmap", + "thiserror 2.0.18", + "void", +] + [[package]] name = "smallstr" version = "0.2.0" @@ -4214,30 +6090,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.15.1" +version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" - -[[package]] -name = "socket2" -version = "0.3.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "122e570113d28d773067fab24266b66753f6ea915758651696b6e35e49f88d6e" -dependencies = [ - "cfg-if 1.0.4", - "libc", - "winapi 0.3.9", -] - -[[package]] -name = "socket2" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" [[package]] name = "socket2" @@ -4251,9 +6106,79 @@ dependencies = [ [[package]] name = "spin" -version = "0.5.2" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sponge-cursor" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620" + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + +[[package]] +name = "ssh-cipher-fork-arti" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "125c5795103fc93fced42d123c8044180afc55469caa1ab56487c3c5543c898d" +dependencies = [ + "cipher 0.4.4", + "ssh-encoding-fork-arti", +] + +[[package]] +name = "ssh-encoding-fork-arti" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0cf03c3a7ea88451ff83a129a79451fd9891d44fc76c25e916a11848b81814c" +dependencies = [ + "base64ct", + "pem-rfc7468", + "sha2 0.10.9", +] + +[[package]] +name = "ssh-key-fork-arti" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433782176b73ea7907763dc314c4a17438a231864d4aa683ba47c07c1cf0a388" +dependencies = [ + "num-bigint-dig", + "p256", + "p384", + "p521", + "rand_core 0.6.4", + "rsa", + "sec1", + "sha2 0.10.9", + "signature", + "ssh-cipher-fork-arti", + "ssh-encoding-fork-arti", + "subtle", + "zeroize", +] [[package]] name = "stable_deref_trait" @@ -4261,6 +6186,18 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "str-buf" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e08d8363704e6c71fc928674353e6b7c23dcea9d82d7012c8faf2a3a025f8d0" + [[package]] name = "strsim" version = "0.8.0" @@ -4273,12 +6210,27 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57bd81eb48f4c437cadc685403cad539345bf703d78e63707418431cecd4522b" +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros 0.28.0", +] + [[package]] name = "strum_macros" version = "0.18.0" @@ -4287,15 +6239,27 @@ checksum = "87c85aa3f8ea653bfd3ddf25f7ee357ee4d204731f6aa9ad04002306f6e2774c" dependencies = [ "heck 0.3.3", "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "syn 1.0.109", ] [[package]] -name = "subtle" -version = "2.4.1" +name = "strum_macros" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck 0.5.0", + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" @@ -4315,21 +6279,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "unicode-ident", ] [[package]] name = "syn" -version = "2.0.117" +version = "2.0.118" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", + "quote 1.0.46", "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + [[package]] name = "synchronoise" version = "1.0.1" @@ -4346,8 +6319,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -4362,9 +6335,50 @@ dependencies = [ "ntapi", "once_cell", "rayon", - "winapi 0.3.9", + "winapi", ] +[[package]] +name = "sysinfo" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ab6a2f8bfe508deb3c6406578252e491d299cbbf3bc0529ecc3313aee4a52f" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.0", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + [[package]] name = "tempfile" version = "3.27.0" @@ -4372,9 +6386,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.2", + "getrandom 0.4.3", "once_cell", - "rustix", + "rustix 1.1.4", "windows-sys 0.61.2", ] @@ -4385,7 +6399,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0863a3345e70f61d613eab32ee046ccd1bcc5f9105fe402c61fcd0c13eeb8b5" dependencies = [ "dirs 2.0.2", - "winapi 0.3.9", + "winapi", ] [[package]] @@ -4394,9 +6408,18 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f" dependencies = [ - "dirs-next 2.0.0", + "dirs-next", "rustversion", - "winapi 0.3.9", + "winapi", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", ] [[package]] @@ -4408,7 +6431,7 @@ dependencies = [ "dirs 4.0.0", "fnv", "nom", - "phf", + "phf 0.11.3", "phf_codegen", ] @@ -4446,8 +6469,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -4457,8 +6480,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -4471,6 +6494,46 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if 1.0.4", +] + +[[package]] +name = "time" +version = "0.3.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18dfaaeddcb932337b5e7866ee7d0ce9b76d2fd092997146f187ec09b4558a50" +dependencies = [ + "deranged", + "js-sys", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c431b87111666e491a90baa837f914fb45cd5dc3c268591b0220ff5057f2085f" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "timer" version = "0.2.0" @@ -4506,68 +6569,23 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" -[[package]] -name = "tokio" -version = "0.2.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6703a273949a90131b290be1fe7b039d0fc884aa1935860dfcbe056f28cd8092" -dependencies = [ - "bytes 0.5.6", - "fnv", - "futures-core", - "iovec", - "lazy_static", - "libc", - "memchr", - "mio 0.6.23", - "mio-named-pipes", - "mio-uds", - "num_cpus", - "pin-project-lite 0.1.12", - "signal-hook-registry", - "slab", - "tokio-macros 0.2.6", - "winapi 0.3.9", -] - [[package]] name = "tokio" version = "1.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.0", "libc", - "mio 1.2.1", - "parking_lot 0.12.5", - "pin-project-lite 0.2.17", + "mio", + "parking_lot", + "pin-project-lite", "signal-hook-registry", - "socket2 0.6.4", - "tokio-macros 2.7.0", + "socket2", + "tokio-macros", "windows-sys 0.61.2", ] -[[package]] -name = "tokio-io-timeout" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bd86198d9ee903fedd2f9a2e72014287c0d9167e4ae43b5853007205dda1b76" -dependencies = [ - "pin-project-lite 0.2.17", - "tokio 1.52.3", -] - -[[package]] -name = "tokio-macros" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e44da00bfc73a25f814cd8d7e57a68a5c31b74b3152a0a1d1f590c97ed06265a" -dependencies = [ - "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 1.0.109", -] - [[package]] name = "tokio-macros" version = "2.7.0" @@ -4575,68 +6593,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] name = "tokio-rustls" -version = "0.14.1" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e12831b255bcfa39dc0436b01e19fea231a37db570686c06ee72c423479f889a" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" dependencies = [ - "futures-core", - "rustls 0.18.1", - "tokio 0.2.25", - "webpki 0.21.4", -] - -[[package]] -name = "tokio-rustls" -version = "0.23.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" -dependencies = [ - "rustls 0.20.9", - "tokio 1.52.3", - "webpki 0.22.4", -] - -[[package]] -name = "tokio-socks" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d611fd5d241872372d52a0a3d309c52d0b95a6a67671a6c8f7ab2c4a37fb2539" -dependencies = [ - "bytes 0.4.12", - "either", - "futures 0.3.32", - "thiserror 1.0.69", - "tokio 0.2.25", -] - -[[package]] -name = "tokio-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a70f4fcd7b3b24fb194f837560168208f669ca8cb70d0c4b862944452396343" -dependencies = [ - "native-tls", - "tokio 0.2.25", -] - -[[package]] -name = "tokio-util" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be8242891f2b6cbef26a2d7e8605133c2c554cd35b3e4948ea892d6d68436499" -dependencies = [ - "bytes 0.5.6", - "futures-core", - "futures-sink", - "log", - "pin-project-lite 0.1.12", - "tokio 0.2.25", + "rustls", + "tokio", ] [[package]] @@ -4645,11 +6613,12 @@ version = "0.7.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.0", "futures-core", + "futures-io", "futures-sink", - "pin-project-lite 0.2.17", - "tokio 1.52.3", + "pin-project-lite", + "tokio", ] [[package]] @@ -4661,6 +6630,1294 @@ dependencies = [ "serde", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee" +dependencies = [ + "indexmap 2.14.0", + "serde_core", + "serde_spanned 1.1.1", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.3", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap 2.14.0", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + +[[package]] +name = "toml_edit" +version = "0.25.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7" +dependencies = [ + "indexmap 2.14.0", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "winnow 1.0.3", +] + +[[package]] +name = "toml_parser" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +dependencies = [ + "winnow 1.0.3", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "toml_writer" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" + +[[package]] +name = "tor-async-utils" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58580b41636378f79500bca6a178787e0e434207e0880dd90698ae3f686f24d6" +dependencies = [ + "cfg-if 1.0.4", + "derive-deftly", + "educe", + "futures 0.3.32", + "oneshot-fused-workaround", + "pin-project", + "postage", + "sync_wrapper", + "thiserror 2.0.18", + "tokio", + "tokio-util", + "tor-basic-utils", + "tor-rtcompat", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-basic-utils" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd3046aa299df67da91b45c02c24d48d40ae1845f9b91e27f9c8adbde78315ba" +dependencies = [ + "derive-deftly", + "derive_more", + "getrandom 0.4.3", + "hex", + "itertools 0.14.0", + "libc", + "paste", + "rand 0.10.2", + "rand_chacha 0.10.0", + "serde", + "slab", + "smallvec", + "thiserror 2.0.18", + "tracing", + "weak-table", + "web-time-compat", +] + +[[package]] +name = "tor-bytes" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b4833cc8ab3fca79eabc06f3ca97db102a3b7db861d77848d39932a6f0ed598" +dependencies = [ + "bytes 1.12.0", + "derive-deftly", + "digest 0.10.7", + "educe", + "getrandom 0.4.3", + "safelog", + "thiserror 2.0.18", + "tor-error", + "tor-llcrypto", + "zeroize", +] + +[[package]] +name = "tor-cell" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73a01cb2ac6697c12b647729d3d7db404e306d1e08a7a3aacdbee08e35170ebd" +dependencies = [ + "amplify", + "bitflags 2.13.0", + "bytes 1.12.0", + "caret", + "derive-deftly", + "derive_more", + "educe", + "itertools 0.14.0", + "paste", + "rand 0.10.2", + "smallvec", + "thiserror 2.0.18", + "tor-basic-utils", + "tor-bytes", + "tor-cert", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-memquota", + "tor-protover", + "tor-units", + "void", +] + +[[package]] +name = "tor-cert" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162d44b975e445de099b3a495710689652bbd0a9a3a0e4946341acbb3138b22b" +dependencies = [ + "caret", + "derive_builder_fork_arti", + "derive_more", + "digest 0.10.7", + "saturating-time", + "thiserror 2.0.18", + "tor-bytes", + "tor-checkable", + "tor-error", + "tor-llcrypto", + "web-time-compat", +] + +[[package]] +name = "tor-chanmgr" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf15c4cbafa5745def4fced9e8e59148533a2bfc8d938e9fad7a0d6d16757712" +dependencies = [ + "async-trait", + "base64ct", + "caret", + "cfg-if 1.0.4", + "derive-deftly", + "derive_more", + "educe", + "futures 0.3.32", + "httparse", + "oneshot-fused-workaround", + "percent-encoding", + "postage", + "rand 0.10.2", + "safelog", + "serde", + "serde_with 3.21.0", + "thiserror 2.0.18", + "tor-async-utils", + "tor-basic-utils", + "tor-cell", + "tor-config", + "tor-error", + "tor-keymgr", + "tor-linkspec", + "tor-llcrypto", + "tor-memquota", + "tor-netdir", + "tor-proto", + "tor-rtcompat", + "tor-socksproto", + "tor-units", + "tracing", + "url", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-checkable" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef81835cb0b2db460c694678eae8c4cbad5f31847e473aac42605f9b945fb31a" +dependencies = [ + "humantime 2.4.0", + "signature", + "thiserror 2.0.18", + "tor-llcrypto", + "web-time-compat", +] + +[[package]] +name = "tor-circmgr" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b63cca1f18282f82b905b6a8c20c6f247787bc010d1b317d9eb98503e4352bf" +dependencies = [ + "amplify", + "async-trait", + "cfg-if 1.0.4", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "downcast-rs", + "dyn-clone", + "educe", + "futures 0.3.32", + "humantime-serde", + "itertools 0.14.0", + "once_cell", + "oneshot-fused-workaround", + "pin-project", + "rand 0.10.2", + "retry-error", + "safelog", + "serde", + "thiserror 2.0.18", + "tor-async-utils", + "tor-basic-utils", + "tor-cell", + "tor-chanmgr", + "tor-config", + "tor-dircommon", + "tor-error", + "tor-guardmgr", + "tor-linkspec", + "tor-memquota", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-relay-selection", + "tor-rtcompat", + "tor-units", + "tracing", + "void", + "weak-table", + "web-time-compat", +] + +[[package]] +name = "tor-config" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a699adfb8bdb34699afcca7cbbd9d26329246940bc9dbc32f380c87578017350" +dependencies = [ + "amplify", + "cfg-if 1.0.4", + "derive-deftly", + "derive_builder_fork_arti", + "educe", + "either", + "figment", + "fs-mistrust", + "futures 0.3.32", + "humantime-serde", + "itertools 0.14.0", + "notify", + "paste", + "postage", + "regex", + "serde", + "serde-value", + "serde_ignored", + "strum 0.28.0", + "thiserror 2.0.18", + "toml 1.1.2+spec-1.1.0", + "tor-basic-utils", + "tor-error", + "tor-rtcompat", + "tracing", + "void", +] + +[[package]] +name = "tor-config-path" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38001695121fc778e67ac7a1c733d3158ee8942a55cfa343981b50d90f5daa" +dependencies = [ + "directories", + "serde", + "shellexpand", + "thiserror 2.0.18", + "tor-error", + "tor-general-addr", +] + +[[package]] +name = "tor-consdiff" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80e9e3eb11e91ea4c1affe5e1f73628726c283942715739850546acb94bbe028" +dependencies = [ + "derive_more", + "digest 0.10.7", + "hex", + "imara-diff", + "static_assertions", + "thiserror 2.0.18", + "tor-error", + "tor-llcrypto", + "tor-netdoc", +] + +[[package]] +name = "tor-dirclient" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0027cd2a58abab9ebaf61c3c1da9b0fa9e6cbc914b88fedb7b3102bd4f4dd656" +dependencies = [ + "async-compression", + "base64ct", + "derive_more", + "futures 0.3.32", + "hex", + "http", + "httparse", + "httpdate", + "itertools 0.14.0", + "memchr", + "thiserror 2.0.18", + "tor-circmgr", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-netdoc", + "tor-proto", + "tor-rtcompat", + "tracing", + "web-time-compat", +] + +[[package]] +name = "tor-dircommon" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d2047b2f1ad3453c1060e5e39203bd87ead266e6873707bd7333b1d6bdac768" +dependencies = [ + "base64ct", + "derive-deftly", + "getset", + "humantime 2.4.0", + "humantime-serde", + "serde", + "tor-basic-utils", + "tor-checkable", + "tor-config", + "tor-linkspec", + "tor-llcrypto", + "tor-netdoc", + "tracing", +] + +[[package]] +name = "tor-dirmgr" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57ebc162ccd628ef8e96912a9e42e848cd7305eb2a5a455a6002f54ad6826422" +dependencies = [ + "async-trait", + "base64ct", + "derive_builder_fork_arti", + "derive_more", + "digest 0.10.7", + "educe", + "event-listener", + "fs-mistrust", + "fslock-guard", + "futures 0.3.32", + "hex", + "humantime 2.4.0", + "humantime-serde", + "itertools 0.14.0", + "memmap2", + "oneshot-fused-workaround", + "paste", + "postage", + "rand 0.10.2", + "rusqlite", + "safelog", + "scopeguard", + "serde", + "serde_json", + "signature", + "static_assertions", + "strum 0.28.0", + "thiserror 2.0.18", + "time", + "tor-async-utils", + "tor-basic-utils", + "tor-checkable", + "tor-circmgr", + "tor-config", + "tor-consdiff", + "tor-dirclient", + "tor-dircommon", + "tor-error", + "tor-guardmgr", + "tor-llcrypto", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-rtcompat", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-error" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6a7ed4aee3e0613a75d420032116dac82d7702594e28566befdfa6707a8fd0e" +dependencies = [ + "derive_more", + "futures 0.3.32", + "paste", + "retry-error", + "static_assertions", + "strum 0.28.0", + "thiserror 2.0.18", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-general-addr" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfee544a33dd3e67e0311cc46ef8f667cbf9c02c7c00ef4f25098a25b2b6e1cf" +dependencies = [ + "derive_more", + "thiserror 2.0.18", + "void", +] + +[[package]] +name = "tor-guardmgr" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1e8f52e4b1b08ba58970a9b9879b0b72c35dcba48bad389935f2778ed432d05" +dependencies = [ + "amplify", + "base64ct", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "dyn-clone", + "educe", + "futures 0.3.32", + "humantime 2.4.0", + "humantime-serde", + "itertools 0.14.0", + "num_enum", + "oneshot-fused-workaround", + "pin-project", + "postage", + "rand 0.10.2", + "safelog", + "serde", + "strum 0.28.0", + "thiserror 2.0.18", + "tor-async-utils", + "tor-basic-utils", + "tor-config", + "tor-dircommon", + "tor-error", + "tor-linkspec", + "tor-llcrypto", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-relay-selection", + "tor-rtcompat", + "tor-units", + "tracing", + "web-time-compat", +] + +[[package]] +name = "tor-hsclient" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dc813f71e63fd324c4b1b1647ddc2fcc4b6e77c45091e6769ae80e591726ec" +dependencies = [ + "async-trait", + "derive-deftly", + "derive_more", + "educe", + "either", + "futures 0.3.32", + "itertools 0.14.0", + "oneshot-fused-workaround", + "postage", + "rand 0.10.2", + "retry-error", + "safelog", + "slotmap-careful", + "strum 0.28.0", + "thiserror 2.0.18", + "tor-async-utils", + "tor-basic-utils", + "tor-bytes", + "tor-cell", + "tor-checkable", + "tor-circmgr", + "tor-config", + "tor-dirclient", + "tor-error", + "tor-hscrypto", + "tor-keymgr", + "tor-linkspec", + "tor-llcrypto", + "tor-memquota", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-rtcompat", + "tracing", + "web-time-compat", +] + +[[package]] +name = "tor-hscrypto" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f82fd6a5a6ede5ece5e7f52708bdf0a007e8f975f9825689b376f038845f1e88" +dependencies = [ + "cipher 0.4.4", + "data-encoding", + "derive-deftly", + "derive_more", + "digest 0.10.7", + "hex", + "humantime 2.4.0", + "itertools 0.14.0", + "paste", + "rand 0.10.2", + "safelog", + "serde", + "signature", + "subtle", + "thiserror 2.0.18", + "tor-basic-utils", + "tor-bytes", + "tor-error", + "tor-key-forge", + "tor-llcrypto", + "tor-memquota", + "tor-units", + "void", + "web-time-compat", + "zeroize", +] + +[[package]] +name = "tor-hsrproxy" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4231a55048af49ae2a8fcb2d41ea0df986b68c26bf6128f97f7f1324d47498" +dependencies = [ + "derive-deftly", + "futures 0.3.32", + "futures-copy", + "itertools 0.14.0", + "oneshot-fused-workaround", + "rangemap", + "safelog", + "serde", + "serde_with 3.21.0", + "strum 0.28.0", + "thiserror 2.0.18", + "tor-async-utils", + "tor-cell", + "tor-config", + "tor-error", + "tor-hsservice", + "tor-log-ratelim", + "tor-proto", + "tor-rtcompat", + "tracing", + "void", +] + +[[package]] +name = "tor-hsservice" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "170b66c977d3b16a5ff79ec344c06392076f0326d2d65146a58c450c50395dae" +dependencies = [ + "amplify", + "async-trait", + "base64ct", + "cfg-if 1.0.4", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "digest 0.10.7", + "educe", + "fs-mistrust", + "futures 0.3.32", + "growable-bloom-filter", + "hex", + "humantime 2.4.0", + "itertools 0.14.0", + "k12", + "once_cell", + "oneshot-fused-workaround", + "postage", + "rand 0.10.2", + "rand_core 0.10.1", + "retry-error", + "safelog", + "serde", + "serde_with 3.21.0", + "strum 0.28.0", + "thiserror 2.0.18", + "tor-async-utils", + "tor-basic-utils", + "tor-bytes", + "tor-cell", + "tor-circmgr", + "tor-config", + "tor-config-path", + "tor-dirclient", + "tor-error", + "tor-hscrypto", + "tor-keymgr", + "tor-linkspec", + "tor-llcrypto", + "tor-log-ratelim", + "tor-netdir", + "tor-netdoc", + "tor-persist", + "tor-proto", + "tor-protover", + "tor-relay-selection", + "tor-rtcompat", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-key-forge" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30f83389917e9908c43457c80d0b982ba6dcd3e6ea36a37b29167b7619d9eaa3" +dependencies = [ + "derive-deftly", + "derive_more", + "downcast-rs", + "paste", + "rand 0.10.2", + "rsa", + "signature", + "ssh-key-fork-arti", + "thiserror 2.0.18", + "tor-bytes", + "tor-cert", + "tor-checkable", + "tor-error", + "tor-llcrypto", +] + +[[package]] +name = "tor-keymgr" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7c18fb26d112c6022b7d1de558a4045b574fecfa1c504045145d8e1a9dc01a" +dependencies = [ + "amplify", + "arrayvec 0.7.8", + "cfg-if 1.0.4", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "downcast-rs", + "dyn-clone", + "fs-mistrust", + "glob-match", + "humantime 2.4.0", + "inventory", + "itertools 0.14.0", + "rand 0.10.2", + "safelog", + "serde", + "signature", + "ssh-key-fork-arti", + "thiserror 2.0.18", + "tor-basic-utils", + "tor-bytes", + "tor-config", + "tor-config-path", + "tor-error", + "tor-hscrypto", + "tor-key-forge", + "tor-llcrypto", + "tor-persist", + "tracing", + "visibility", + "walkdir", + "web-time-compat", + "zeroize", +] + +[[package]] +name = "tor-linkspec" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "638a849a5d65d4e37adb6a2fa597a5a5c0decb749c17e76d3c44c4aefd696270" +dependencies = [ + "base64ct", + "by_address", + "caret", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "hex", + "itertools 0.14.0", + "safelog", + "serde", + "serde_with 3.21.0", + "strum 0.28.0", + "thiserror 2.0.18", + "tor-basic-utils", + "tor-bytes", + "tor-config", + "tor-llcrypto", + "tor-memquota", + "tor-protover", +] + +[[package]] +name = "tor-llcrypto" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ef0e63e805e9c1da61511a93eca502dc29bcb0b8635e9668ec750b63a1e53a1" +dependencies = [ + "aes", + "base64ct", + "ctr", + "curve25519-dalek 4.1.3", + "der-parser", + "derive-deftly", + "derive_more", + "digest 0.10.7", + "ed25519-dalek", + "educe", + "getrandom 0.2.17", + "getrandom 0.3.4", + "getrandom 0.4.3", + "hex", + "rand 0.10.2", + "rand_chacha 0.10.0", + "rand_core 0.10.1", + "rand_core 0.6.4", + "rand_jitter 0.6.1", + "rdrand 0.8.3", + "reseeding_rng", + "rsa", + "safelog", + "serde", + "sha1", + "sha2 0.10.9", + "sha3 0.10.9", + "signature", + "subtle", + "thiserror 2.0.18", + "tor-error", + "tor-memquota-cost", + "visibility", + "x25519-dalek 2.0.1", + "zeroize", +] + +[[package]] +name = "tor-log-ratelim" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37d0f759a875b6f9b6f3657a2626a70e2474e698a4404501033babe63ad888a6" +dependencies = [ + "futures 0.3.32", + "humantime 2.4.0", + "thiserror 2.0.18", + "tor-error", + "tor-rtcompat", + "tracing", + "weak-table", + "web-time-compat", +] + +[[package]] +name = "tor-memquota" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c06f2e981120a4c1da1e361573cee4af618d05fa3c7ec37c139d766f1b8d47f" +dependencies = [ + "cfg-if 1.0.4", + "derive-deftly", + "derive_more", + "dyn-clone", + "educe", + "futures 0.3.32", + "itertools 0.14.0", + "paste", + "pin-project", + "serde", + "slotmap-careful", + "static_assertions", + "sysinfo 0.38.4", + "thiserror 2.0.18", + "tor-async-utils", + "tor-basic-utils", + "tor-config", + "tor-error", + "tor-log-ratelim", + "tor-memquota-cost", + "tor-rtcompat", + "tracing", + "void", +] + +[[package]] +name = "tor-memquota-cost" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b86eb903fee638e9211daddaddc146f0c5e4f5605d79983548fce6fec596325c" +dependencies = [ + "derive-deftly", + "itertools 0.14.0", + "paste", + "void", +] + +[[package]] +name = "tor-netdir" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8160580273eec3576158c3e833ff198870665dacebb373585892dde93cf9803" +dependencies = [ + "async-trait", + "bitflags 2.13.0", + "derive_more", + "digest 0.10.7", + "futures 0.3.32", + "hex", + "humantime 2.4.0", + "itertools 0.14.0", + "num_enum", + "rand 0.10.2", + "serde", + "strum 0.28.0", + "thiserror 2.0.18", + "time", + "tor-basic-utils", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-netdoc", + "tor-protover", + "tor-units", + "tracing", + "typed-index-collections", + "web-time-compat", +] + +[[package]] +name = "tor-netdoc" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51598bfd24866de2c51e0de7a6e2418f86c6278cfeba2f85295ce45367fd8e06" +dependencies = [ + "amplify", + "base64ct", + "cipher 0.4.4", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "digest 0.10.7", + "educe", + "enumset", + "hex", + "hostname-validator", + "humantime 2.4.0", + "ipnet", + "itertools 0.14.0", + "memchr", + "paste", + "phf 0.13.1", + "rand 0.10.2", + "saturating-time", + "serde", + "serde_with 3.21.0", + "signature", + "smallvec", + "strum 0.28.0", + "subtle", + "thiserror 2.0.18", + "time", + "tinystr", + "tor-basic-utils", + "tor-bytes", + "tor-cell", + "tor-cert", + "tor-checkable", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-protover", + "tor-units", + "void", + "web-time-compat", + "zeroize", +] + +[[package]] +name = "tor-persist" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2ff75e20adb6a1a7ad07e16b55e56d5376706cc0090ab8831f008f1a89243f2" +dependencies = [ + "amplify", + "derive-deftly", + "derive_more", + "filetime", + "fs-mistrust", + "fslock-guard", + "futures 0.3.32", + "itertools 0.14.0", + "oneshot-fused-workaround", + "paste", + "sanitize-filename", + "serde", + "serde_json", + "thiserror 2.0.18", + "time", + "tor-async-utils", + "tor-basic-utils", + "tor-error", + "tracing", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-proto" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b602da8ba5a4189d6ff551f5dd9db949b503780140d175435658970a1ea54" +dependencies = [ + "amplify", + "async-trait", + "asynchronous-codec", + "bitvec", + "bytes 1.12.0", + "caret", + "cfg-if 1.0.4", + "cipher 0.4.4", + "coarsetime", + "derive-deftly", + "derive_builder_fork_arti", + "derive_more", + "digest 0.10.7", + "educe", + "enum_dispatch", + "futures 0.3.32", + "futures-util", + "hkdf", + "hmac 0.12.1", + "itertools 0.14.0", + "nonany", + "oneshot-fused-workaround", + "pin-project", + "postage", + "rand 0.10.2", + "rand_core 0.10.1", + "safelog", + "slotmap-careful", + "smallvec", + "static_assertions", + "strum 0.28.0", + "subtle", + "thiserror 2.0.18", + "tokio", + "tokio-util", + "tor-async-utils", + "tor-basic-utils", + "tor-bytes", + "tor-cell", + "tor-cert", + "tor-checkable", + "tor-config", + "tor-error", + "tor-hscrypto", + "tor-linkspec", + "tor-llcrypto", + "tor-log-ratelim", + "tor-memquota", + "tor-protover", + "tor-rtcompat", + "tor-rtmock", + "tor-units", + "tracing", + "typenum", + "visibility", + "void", + "web-time-compat", + "zeroize", +] + +[[package]] +name = "tor-protover" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef84569d020c36eb322976f9a5dec1d3fa992db9739237ad1ae923b0ddeb298" +dependencies = [ + "caret", + "paste", + "serde_with 3.21.0", + "thiserror 2.0.18", + "tor-basic-utils", + "tor-bytes", +] + +[[package]] +name = "tor-ptmgr" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66db88ee6c5ba60a077b592b7e566d465220de61ccfd473fba6567c577cad475" +dependencies = [ + "async-trait", + "cfg-if 1.0.4", + "derive-deftly", + "derive_builder_fork_arti", + "fs-mistrust", + "futures 0.3.32", + "itertools 0.14.0", + "oneshot-fused-workaround", + "serde", + "thiserror 2.0.18", + "tor-async-utils", + "tor-basic-utils", + "tor-chanmgr", + "tor-config", + "tor-config-path", + "tor-error", + "tor-linkspec", + "tor-proto", + "tor-rtcompat", + "tor-socksproto", + "tracing", + "web-time-compat", +] + +[[package]] +name = "tor-relay-selection" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09778e3a45fdf49ca335fa16a0032abc5d4e1cacff9f46c3ed3e2a416d088aa6" +dependencies = [ + "rand 0.10.2", + "serde", + "tor-basic-utils", + "tor-linkspec", + "tor-netdir", + "tor-netdoc", +] + +[[package]] +name = "tor-rtcompat" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "981279291476ad7ec309c874fa99b8d31250432a48ff6eea3f7405edbbd254e1" +dependencies = [ + "amplify", + "async-native-tls", + "async-trait", + "async_executors", + "asynchronous-codec", + "cfg-if 1.0.4", + "coarsetime", + "derive_builder_fork_arti", + "derive_more", + "dyn-clone", + "educe", + "futures 0.3.32", + "hex", + "libc", + "native-tls", + "paste", + "pin-project", + "socket2", + "thiserror 2.0.18", + "tokio", + "tokio-util", + "tor-error", + "tor-general-addr", + "tracing", + "void", + "web-time-compat", + "zeroize", +] + +[[package]] +name = "tor-rtmock" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a3ee9695304cc44cc0de1dc673c9a71419318e214dc04ed7883a058d050654d" +dependencies = [ + "amplify", + "assert_matches", + "async-trait", + "derive-deftly", + "derive_more", + "educe", + "futures 0.3.32", + "humantime 2.4.0", + "itertools 0.14.0", + "oneshot-fused-workaround", + "pin-project", + "priority-queue", + "slotmap-careful", + "strum 0.28.0", + "thiserror 2.0.18", + "tor-error", + "tor-general-addr", + "tor-rtcompat", + "tracing", + "tracing-test", + "void", + "web-time-compat", +] + +[[package]] +name = "tor-socksproto" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbf78ef55dbfccb5a95cd75eb433621947923653cb91c9941d5a0a5116e510ee" +dependencies = [ + "amplify", + "caret", + "derive-deftly", + "educe", + "safelog", + "subtle", + "thiserror 2.0.18", + "tor-bytes", + "tor-error", +] + +[[package]] +name = "tor-units" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0325a93f3b35c5a9bda74705ce89b753e1c8e183af6945826188cef16687d80" +dependencies = [ + "derive-deftly", + "derive_more", + "serde", + "thiserror 2.0.18", + "tor-memquota", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.0", + "bytes 1.12.0", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + [[package]] name = "tower-service" version = "0.3.3" @@ -4673,11 +7930,22 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ - "log", - "pin-project-lite 0.2.17", + "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + [[package]] name = "tracing-core" version = "0.1.36" @@ -4685,16 +7953,57 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", ] [[package]] -name = "tracing-futures" -version = "0.2.5" +name = "tracing-log" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97d095ae15e245a057c8e8451bab9b3ee1e1f68e9ba2b4fbc18d0ac5237835f2" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" dependencies = [ - "pin-project", + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "tracing-test" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a4c448db514d4f24c5ddb9f73f2ee71bfb24c526cf0c570ba142d1119e0051" +dependencies = [ + "tracing-core", + "tracing-subscriber", + "tracing-test-macro", +] + +[[package]] +name = "tracing-test-macro" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad06847b7afb65c7866a36664b75c40b895e318cea4f71299f013fb22965329d" +dependencies = [ + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -4709,7 +8018,17 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" dependencies = [ - "rustc-hash 2.1.2", + "rustc-hash 2.1.3", +] + +[[package]] +name = "typed-index-collections" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "898160f1dfd383b4e92e17f0512a7d62f3c51c44937b23b6ffc3a1614a8eaccd" +dependencies = [ + "bincode 2.0.1", + "serde", ] [[package]] @@ -4727,6 +8046,15 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[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-langid" version = "0.9.6" @@ -4746,12 +8074,6 @@ dependencies = [ "tinystr", ] -[[package]] -name = "unicase" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" - [[package]] name = "unicode-ident" version = "1.0.24" @@ -4793,9 +8115,9 @@ checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "universal-hash" -version = "0.4.1" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f214e8f697e925001e66ec2c6e37a4ef93f0f78c2eed7814394e10c62025b05" +checksum = "8326b2c654932e3e4f9196e69d08fdf7cfd718e1dc6f66b347e6024a0c961402" dependencies = [ "generic-array 0.14.7", "subtle", @@ -4816,18 +8138,18 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - [[package]] name = "untrusted" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "unty" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" + [[package]] name = "url" version = "2.5.8" @@ -4854,14 +8176,22 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "0.8.2" +version = "1.23.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" +checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53" dependencies = [ - "getrandom 0.2.17", - "serde", + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "vcpkg" version = "0.2.15" @@ -4880,6 +8210,23 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "visibility" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d674d135b4a8c1d7e813e2f8d1c9a58308aee4a680323066025e53132218bd91" +dependencies = [ + "proc-macro2 1.0.106", + "quote 1.0.46", + "syn 2.0.118", +] + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" + [[package]] name = "walkdir" version = "2.5.0" @@ -4913,42 +8260,40 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasip2" -version = "1.0.3+wasi-0.2.9" +version = "1.0.4+wasi-0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" dependencies = [ - "wit-bindgen 0.57.1", + "wit-bindgen", ] [[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +name = "wasix" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +checksum = "ae86f02046da16a333a9129d31451423e1657737ecdafed4193838a5f54c5cfe" dependencies = [ - "wit-bindgen 0.51.0", + "wasi 0.11.1+wasi-snapshot-preview1", ] [[package]] name = "wasm-bindgen" -version = "0.2.122" +version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409" +checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" dependencies = [ "cfg-if 1.0.4", "once_cell", "rustversion", - "serde", - "serde_json", "wasm-bindgen-macro", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.72" +version = "0.4.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9473dbd2991ae90b6291c3c32c30c6187ac49aa32f9905d1cce280ec1e110b0f" +checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" dependencies = [ "js-sys", "wasm-bindgen", @@ -4956,115 +8301,80 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.122" +version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6" +checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" dependencies = [ - "quote 1.0.45", + "quote 1.0.46", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.122" +version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e" +checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" dependencies = [ "bumpalo", "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.122" +version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437" +checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" dependencies = [ "unicode-ident", ] [[package]] -name = "wasm-encoder" -version = "0.244.0" +name = "weak-table" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap 2.14.0", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.12.1", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver 1.0.28", -] +checksum = "323f4da9523e9a669e1eaf9c6e763892769b1d38c623913647bfdc1532fe4549" [[package]] name = "web-sys" -version = "0.3.99" +version = "0.3.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621441cfc37b84979402712047321980c178f299193a3589d05b99e8763436" +checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" dependencies = [ "js-sys", "wasm-bindgen", ] [[package]] -name = "webpki" -version = "0.21.4" +name = "web-time" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" dependencies = [ - "ring 0.16.20", - "untrusted 0.7.1", + "js-sys", + "wasm-bindgen", ] [[package]] -name = "webpki" -version = "0.22.4" +name = "web-time-compat" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed63aea5ce73d0ff405984102c42de94fc55a6b75765d621c65262469b3c9b53" +checksum = "af46dad42aa37be3b4a116fe613365f991b8bdae6cd6ce82d84fa9f9e8f70ae4" dependencies = [ - "ring 0.17.14", - "untrusted 0.9.0", + "web-time", ] [[package]] -name = "webpki-roots" -version = "0.20.0" +name = "webpki-root-certs" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f20dea7535251981a9670857150d571846545088359b28e4951d350bdaf179f" +checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267" dependencies = [ - "webpki 0.21.4", + "rustls-pki-types", ] -[[package]] -name = "winapi" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" - [[package]] name = "winapi" version = "0.3.9" @@ -5075,12 +8385,6 @@ dependencies = [ "winapi-x86_64-pc-windows-gnu", ] -[[package]] -name = "winapi-build" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" - [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" @@ -5102,6 +8406,27 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -5115,6 +8440,17 @@ dependencies = [ "windows-strings", ] +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -5122,8 +8458,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -5133,8 +8469,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -5143,6 +8479,27 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -5161,13 +8518,40 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", ] [[package]] @@ -5179,64 +8563,189 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -5244,21 +8753,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] -name = "winreg" -version = "0.7.0" +name = "windows_x86_64_msvc" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0120db82e8a1e0b9fb3345a539c478767c0048d842860994d96113d5b667bd69" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" dependencies = [ - "winapi 0.3.9", + "memchr", ] [[package]] -name = "wit-bindgen" -version = "0.51.0" +name = "winnow" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" dependencies = [ - "wit-bindgen-rust-macro", + "memchr", ] [[package]] @@ -5267,85 +8782,6 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck 0.5.0", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap 2.14.0", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.12.1", - "indexmap 2.14.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.14.0", - "log", - "semver 1.0.28", - "serde", - "serde_derive", - "serde_json", - "unicode-xid 0.2.6", - "wasmparser", -] - [[package]] name = "writeable" version = "0.6.3" @@ -5353,24 +8789,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" [[package]] -name = "ws2_32-sys" -version = "0.2.1" +name = "wyz" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" dependencies = [ - "winapi 0.2.8", - "winapi-build", -] - -[[package]] -name = "x25519-dalek" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "637ff90c9540fa3073bb577e65033069e4bae7c79d49d74aa3ffdf5342a53217" -dependencies = [ - "curve25519-dalek 2.1.3", - "rand_core 0.5.1", - "zeroize", + "tap", ] [[package]] @@ -5384,6 +8808,24 @@ dependencies = [ "zeroize", ] +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek 4.1.3", + "rand_core 0.6.4", + "serde", + "zeroize", +] + +[[package]] +name = "xxhash-rust" +version = "0.8.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d93c89cdc2d3a63c3ec48ffe926931bdc069eafa8e4402fe6d8f790c9d1e576" + [[package]] name = "yaml-rust" version = "0.3.5" @@ -5392,9 +8834,9 @@ checksum = "e66366e18dc58b46801afbf2ca7661a9f59cc8c5962c29892b6039b4f86fa992" [[package]] name = "yoke" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -5408,29 +8850,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", "synstructure", ] [[package]] name = "zerocopy" -version = "0.8.50" +version = "0.8.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1" +checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.50" +version = "0.8.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639" +checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -5449,29 +8891,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", "synstructure", ] [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" dependencies = [ "zeroize_derive", ] [[package]] name = "zeroize_derive" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -5504,8 +8946,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" dependencies = [ "proc-macro2 1.0.106", - "quote 1.0.45", - "syn 2.0.117", + "quote 1.0.46", + "syn 2.0.118", ] [[package]] @@ -5524,3 +8966,31 @@ name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml index acef614..18dfbf0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet" -version = "5.4.0-alpha.1" +version = "5.4.1" authors = ["Grin Developers "] description = "Simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format." license = "Apache-2.0" @@ -21,49 +21,26 @@ exclude = ["integration"] [dependencies] clap = { version = "2.33", features = ["yaml"] } -rpassword = "4.0" +rpassword = "7.5.4" thiserror = "1" -prettytable-rs = "0.10" log = "0.4" linefeed = "0.6" -semver = "0.10" -rustyline = "6" +semver = "1.0.28" +rustyline = "9" lazy_static = "1" -grin_wallet_api = { path = "./api", version = "5.4.0-alpha.1" } -grin_wallet_impls = { path = "./impls", version = "5.4.0-alpha.1" } -grin_wallet_libwallet = { path = "./libwallet", version = "5.4.0-alpha.1" } -grin_wallet_controller = { path = "./controller", version = "5.4.0-alpha.1" } -grin_wallet_config = { path = "./config", version = "5.4.0-alpha.1" } -grin_wallet_util = { path = "./util", version = "5.4.0-alpha.1" } - +grin_wallet_api = { path = "./api", version = "5.4.1" } +grin_wallet_impls = { path = "./impls", version = "5.4.1" } +grin_wallet_libwallet = { path = "./libwallet", version = "5.4.1" } +grin_wallet_controller = { path = "./controller", version = "5.4.1" } +grin_wallet_config = { path = "./config", version = "5.4.1" } ##### Grin Imports -# For Release -#grin_core = "5.4.0" -#grin_keychain = "5.4.0" -#grin_util = "5.4.0" -#grin_api = "5.4.0" - -# For beta release - -# grin_core = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3"} -# grin_keychain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_api = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } - -# For bleeding edge -grin_core = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_keychain = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_util = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_api = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } - -# For local testing -# grin_core = { path = "../grin/core"} -# grin_keychain = { path = "../grin/keychain"} -# grin_util = { path = "../grin/util"} -# grin_api = { path = "../grin/api"} +grin_core = { path = "grin/core"} +grin_keychain = { path = "grin/keychain"} +grin_util = { path = "grin/util"} +grin_api = { path = "grin/api"} ###### @@ -73,7 +50,5 @@ built = { version = "0.8.0", features = ["git2"]} [dev-dependencies] url = "2.1" serde = "1" -serde_derive = "1" serde_json = "1" -remove_dir_all = "0.7" easy-jsonrpc-mw = "0.5.4" \ No newline at end of file diff --git a/README.md b/README.md index 0554c4a..d8c5841 100644 --- a/README.md +++ b/README.md @@ -14,12 +14,28 @@ This is the reference implementation of [Grin's](https://github.com/mimblewimble * A reference command-line wallet, which provides a baseline wallet for Grin and demonstrates how the wallet APIs should be called. -# Usage +## Contributing + +To get involved, read our [contributing docs](https://github.com/mimblewimble/grin/blob/master/CONTRIBUTING.md). + +Find us: + +* Telegram: [Grin Development](https://t.me/grindevelopment) +* Chat: [Keybase](https://keybase.io/team/grincoin), more instructions on how to join [here](https://grin.mw/community). + +## Usage To use the command-line wallet, we recommend using the latest release from the [Releases page](https://github.com/mimblewimble/grin-wallet/releases). There are distributions for Linux, MacOS and Windows. Full documentation outlining how to use the command line wallet can be found on [Grin's Wiki](https://github.com/mimblewimble/docs/wiki/Wallet-User-Guide) -# License +To build locally install Rust and execute in the project directory: +``` +git submodule update --init --recursive +cargo build --release +./target/release/grin-wallet +``` + +## License Apache License v2.0 diff --git a/api/Cargo.toml b/api/Cargo.toml index b86cfbd..ee4a43c 100644 --- a/api/Cargo.toml +++ b/api/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_api" -version = "5.4.0-alpha.1" +version = "5.4.1" authors = ["Grin Developers "] description = "Grin Wallet API" license = "Apache-2.0" @@ -11,44 +11,27 @@ edition = "2021" [dependencies] log = "0.4" -uuid = { version = "0.8", features = ["serde", "v4"] } +uuid = { version = "1.23.4", features = ["serde", "v4"] } serde = "1" rand = "0.6" serde_derive = "1" serde_json = "1" easy-jsonrpc-mw = "0.5.4" chrono = { version = "0.4.11", features = ["serde"] } -ring = "0.16" +ring = "0.17.14" base64 = "0.12" -ed25519-dalek = "1.0.0-pre.4" +ed25519-dalek = "2" -grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-alpha.1" } -grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" } -grin_wallet_impls = { path = "../impls", version = "5.4.0-alpha.1" } -grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" } +grin_wallet_libwallet = { path = "../libwallet", version = "5.4.1" } +grin_wallet_config = { path = "../config", version = "5.4.1" } +grin_wallet_impls = { path = "../impls", version = "5.4.1" } +grin_wallet_util = { path = "../util", version = "5.4.1" } ##### Grin Imports -# For Release -#grin_core = "5.4.0" -#grin_keychain = "5.4.0" -#grin_util = "5.4.0" - -# For beta release - -# grin_core = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3"} -# grin_keychain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } - -# For bleeding edge -grin_core = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_keychain = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_util = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } - -# For local testing -# grin_core = { path = "../../grin/core"} -# grin_keychain = { path = "../../grin/keychain"} -# grin_util = { path = "../../grin/util"} +grin_core = { path = "../grin/core"} +grin_keychain = { path = "../grin/keychain"} +grin_util = { path = "../grin/util"} ##### diff --git a/api/src/foreign.rs b/api/src/foreign.rs index 0a1f670..cd2d142 100644 --- a/api/src/foreign.rs +++ b/api/src/foreign.rs @@ -14,9 +14,9 @@ //! Foreign API External Definition -use crate::config::TorConfig; use crate::keychain::Keychain; use crate::libwallet::api_impl::foreign; +use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::contract::proofs::InvoiceProof; use crate::libwallet::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI}; use crate::libwallet::{ @@ -26,7 +26,7 @@ use crate::libwallet::{ use crate::try_slatepack_sync_workflow; use crate::util::secp::key::SecretKey; use crate::util::Mutex; -use ed25519_dalek::PublicKey as DalekPublicKey; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use std::sync::Arc; /// ForeignAPI Middleware Check callback @@ -69,15 +69,14 @@ where { /// Wallet instance pub wallet_inst: Arc>>>, + /// Wallet configuration path + config_path: crate::ConfigPath, /// Flag to normalize some output during testing. Can mostly be ignored. pub doctest_mode: bool, /// foreign check middleware middleware: Option, /// Stored keychain mask (in case the stored wallet seed is tokenized) keychain_mask: Option, - /// Optional TOR configuration, holding address of sender and - /// data directory - tor_config: Mutex>, } impl<'a, L, C, K> Foreign<'a, L, C, K> @@ -97,6 +96,7 @@ where /// # Arguments /// * `wallet_in` - A reference-counted mutex containing an implementation of the /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. + /// * `config_path` - Path to the wallet configuration file /// * `keychain_mask` - Mask value stored internally to use when calling a wallet /// whose seed has been XORed with a token value (such as when running the foreign /// and owner listeners in the same instance) @@ -108,6 +108,7 @@ where /// /// # Example /// ``` + /// use std::path::PathBuf; /// use grin_keychain as keychain; /// use grin_util as util; /// use grin_core; @@ -142,7 +143,7 @@ where /// /// // A NodeClient must first be created to handle communication between /// // the wallet and the node. - /// let node_client = HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None).unwrap(); + /// let node_client = HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None, wallet_config.api_request_timeout()).unwrap(); /// /// // impls::DefaultWalletImpl is provided for convenience in instantiating the wallet /// // It contains the LMDBBackend, DefaultLCProvider (lifecycle) and ExtKeychain used @@ -166,39 +167,30 @@ where /// // All wallet functions operate on an Arc::Mutex to allow multithreading where needed /// let mut wallet = Arc::new(Mutex::new(wallet)); /// - /// let api_foreign = Foreign::new(wallet.clone(), None, None, false); + /// let api_foreign = Foreign::new(wallet.clone(), PathBuf::from(dir).join("grin-wallet.toml"), None, None, false); /// // .. perform wallet operations /// /// ``` - pub fn new( + pub fn new

( wallet_inst: Arc>>>, + config_path: P, keychain_mask: Option, middleware: Option, doctest_mode: bool, - ) -> Self { + ) -> Self + where + P: Into, + { Foreign { wallet_inst, + config_path: config_path.into(), doctest_mode, middleware, keychain_mask, - tor_config: Mutex::new(None), } } - /// Set the TOR configuration for this instance of the ForeignAPI, used during - /// `recieve_tx` when a return address is specified - /// - /// # Arguments - /// * `tor_config` - The optional [TorConfig](#) to use - /// # Returns - /// * Nothing - - pub fn set_tor_config(&self, tor_config: Option) { - let mut lock = self.tor_config.lock(); - *lock = tor_config; - } - /// Return the version capabilities of the running ForeignApi Node /// # Arguments /// None @@ -209,7 +201,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config); /// - /// let mut api_foreign = Foreign::new(wallet.clone(), None, None, false); + /// let mut api_foreign = Foreign::new(wallet.clone(), std::path::PathBuf::from("grin-wallet.toml"), None, None, false); /// /// let version_info = api_foreign.check_version(); /// // check and proceed accordingly @@ -261,7 +253,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config); /// - /// let mut api_foreign = Foreign::new(wallet.clone(), None, None, false); + /// let mut api_foreign = Foreign::new(wallet.clone(), std::path::PathBuf::from("grin-wallet.toml"), None, None, false); /// /// let block_fees = BlockFees { /// fees: 800000, @@ -336,7 +328,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config); /// - /// let mut api_foreign = Foreign::new(wallet.clone(), None, None, false); + /// let mut api_foreign = Foreign::new(wallet.clone(), std::path::PathBuf::from("grin-wallet.toml"), None, None, false); /// # let slate = Slate::blank(2, false); /// /// // . . . @@ -356,6 +348,10 @@ where r_addr: Option, ) -> Result { let mut w_lock = self.wallet_inst.lock(); + let tor_config = r_addr + .as_ref() + .map(|_| crate::tor_config::load(&self.config_path.get())) + .transpose()?; let w = w_lock.lc_provider()?.wallet_inst()?; if let Some(m) = self.middleware.as_ref() { m( @@ -373,18 +369,32 @@ where )?; match r_addr { Some(a) => { - let tor_config_lock = self.tor_config.lock(); - let res = try_slatepack_sync_workflow( - &ret_slate, - &a, - tor_config_lock.clone(), - None, - true, - self.doctest_mode, - ); + let tc = tor_config.ok_or_else(|| { + Error::TorConfig("Tor config was not loaded with a return address".into()) + })?; + let can_send = tc.send_tor(None); + if self.doctest_mode || !can_send { + return Ok(ret_slate); + } + let res = try_slatepack_sync_workflow(&ret_slate, &a, Some(tc), None, true); match res { - Ok(s) => Ok(s.unwrap()), - Err(_) => Ok(ret_slate), + Ok(s) => { + let parent_key_id = w.parent_key_id(); + match update_tx_slate_state( + w, + (&self.keychain_mask).as_ref(), + &parent_key_id, + &s, + ) { + Ok(_) => {} + Err(e) => error!("Error on updating slate state: {}", e), + } + Ok(s) + } + Err(e) => { + error!("Error on sending over Tor: {}", e); + Ok(ret_slate) + } } } None => Ok(ret_slate), @@ -419,8 +429,8 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); - /// let mut api_foreign = Foreign::new(wallet.clone(), None, None, false); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); + /// let mut api_foreign = Foreign::new(wallet.clone(), std::path::PathBuf::from("grin-wallet.toml"), None, None, false); /// /// // . . . /// // Issue the invoice tx via the owner API @@ -528,8 +538,12 @@ macro_rules! doctest_helper_setup_doc_env_foreign { wallet_config.data_file_dir = dir.to_owned(); let pw = ZeroingString::from(""); - let node_client = - HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None).unwrap(); + let node_client = HTTPNodeClient::new( + &wallet_config.check_node_api_http_addr, + None, + wallet_config.api_request_timeout(), + ) + .unwrap(); let mut wallet = Box::new(DefaultWalletImpl::::new(node_client.clone()).unwrap()) as Box< diff --git a/api/src/foreign_rpc.rs b/api/src/foreign_rpc.rs index 9970fac..028a69e 100644 --- a/api/src/foreign_rpc.rs +++ b/api/src/foreign_rpc.rs @@ -21,6 +21,8 @@ use crate::libwallet::{ }; use crate::{Foreign, ForeignCheckMiddlewareFn}; use easy_jsonrpc_mw; +use grin_wallet_config::initial_setup_wallet; +use std::path::PathBuf; /// Public definition used to generate Foreign jsonrpc api. /// * When running `grin-wallet listen` with defaults, the V2 api is available at @@ -365,6 +367,14 @@ pub fn run_doctest_foreign( let _ = fs::remove_dir_all(test_dir); global::set_local_chain_type(ChainTypes::AutomatedTesting); + let _ = fs::create_dir_all(test_dir); + let config = initial_setup_wallet( + &ChainTypes::AutomatedTesting, + Some(PathBuf::from(test_dir)), + false, + ) + .unwrap(); + let mut wallet_proxy: WalletProxy< DefaultLCProvider, LocalWalletClient, @@ -513,8 +523,20 @@ pub fn run_doctest_foreign( } let mut api_foreign = match init_invoice_tx { - false => Foreign::new(wallet1, mask1, Some(test_check_middleware), true), - true => Foreign::new(wallet2, mask2, Some(test_check_middleware), true), + false => Foreign::new( + wallet1, + config.config_file_path, + mask1, + Some(test_check_middleware), + true, + ), + true => Foreign::new( + wallet2, + config.config_file_path, + mask2, + Some(test_check_middleware), + true, + ), }; api_foreign.doctest_mode = true; let foreign_api = &api_foreign as &dyn ForeignRpc; diff --git a/api/src/lib.rs b/api/src/lib.rs index 1b79491..8827d5f 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -42,12 +42,15 @@ mod foreign_rpc; mod owner; mod owner_rpc; +mod tor_config; mod types; pub use crate::foreign::{Foreign, ForeignCheckMiddleware, ForeignCheckMiddlewareFn}; pub use crate::foreign_rpc::ForeignRpc; pub use crate::owner::{try_slatepack_sync_workflow, Owner}; pub use crate::owner_rpc::OwnerRpc; +#[doc(hidden)] +pub use crate::tor_config::ConfigPath; pub use crate::foreign_rpc::foreign_rpc as foreign_rpc_client; pub use crate::foreign_rpc::run_doctest_foreign; diff --git a/api/src/owner.rs b/api/src/owner.rs index d8da054..ec7a9e1 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -14,19 +14,14 @@ //! Owner API External Definition -use chrono::prelude::*; -use ed25519_dalek::SecretKey as DalekSecretKey; -use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, SwapReq}; -use grin_wallet_libwallet::RetrieveTxQueryArgs; -use uuid::Uuid; - use crate::config::{TorConfig, WalletConfig}; use crate::core::core::OutputFeatures; use crate::core::global; -use crate::impls::HttpSlateSender; use crate::impls::SlateSender as _; +use crate::impls::TorSlateSender; use crate::keychain::{Identifier, Keychain}; use crate::libwallet::api_impl::owner_updater::{start_updater_log_thread, StatusMessage}; +use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::api_impl::{owner, owner_updater}; use crate::libwallet::contract::proofs::InvoiceProof; use crate::libwallet::contract::types::{ @@ -40,13 +35,25 @@ use crate::libwallet::{ use crate::util::logger::LoggingConfig; use crate::util::secp::{key::SecretKey, pedersen::Commitment}; use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString}; +use grin_wallet_config::config::{ + reload_global_config, update_global_config, WALLET_CONFIG_FILE_NAME, +}; +use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, SwapReq}; +use grin_wallet_libwallet::RetrieveTxQueryArgs; use grin_wallet_util::OnionV3Address; + +use chrono::prelude::*; +use ed25519_dalek::SigningKey as DalekSecretKey; use std::convert::TryFrom; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{channel, Sender}; use std::sync::Arc; use std::thread; use std::time::Duration; +use uuid::Uuid; /// Main interface into all wallet API functions. /// Wallet APIs are split into two seperate blocks of functionality @@ -68,11 +75,13 @@ where C: NodeClient + 'static, K: Keychain + 'static, { - /// contain all methods to manage the wallet + /// Contains all methods to manage the wallet pub wallet_inst: Arc>>>, + /// Wallet configuration path + config_path: crate::ConfigPath, /// Flag to normalize some output during testing. Can mostly be ignored. pub doctest_mode: bool, - /// retail TLD during doctest + /// Retail TLD during doctest pub doctest_retain_tld: bool, /// Share ECDH key pub shared_key: Arc>>, @@ -85,9 +94,6 @@ where /// Holds all update and status messages returned by the /// updater process updater_messages: Arc>>, - /// Optional TOR configuration, holding address of sender and - /// data directory - tor_config: Mutex>, } impl Owner @@ -106,15 +112,17 @@ where /// /// # Arguments /// * `wallet_in` - A reference-counted mutex containing an implementation of the + /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. /// * `custom_channel` - A custom MPSC Tx/Rx pair to capture status /// updates - /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. + /// * `config_path` - Path to the wallet configuration file /// /// # Returns /// * An instance of the OwnerApi holding a reference to the provided wallet /// /// # Example /// ``` + /// use std::path::PathBuf; /// use grin_keychain as keychain; /// use grin_util as util; /// use grin_core; @@ -148,7 +156,7 @@ where /// /// // A NodeClient must first be created to handle communication between /// // the wallet and the node. - /// let node_client = HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None).unwrap(); + /// let node_client = HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None, wallet_config.api_request_timeout()).unwrap(); /// /// // impls::DefaultWalletImpl is provided for convenience in instantiating the wallet /// // It contains the WalletBackend, DefaultLCProvider (lifecycle) and ExtKeychain used @@ -172,15 +180,19 @@ where /// // All wallet functions operate on an Arc::Mutex to allow multithreading where needed /// let mut wallet = Arc::new(Mutex::new(wallet)); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, PathBuf::from(dir).join("grin-wallet.toml")); /// // .. perform wallet operations /// /// ``` - pub fn new( + pub fn new

( wallet_inst: Arc>>>, custom_channel: Option>, - ) -> Self { + config_path: P, + ) -> Self + where + P: Into, + { let updater_running = Arc::new(AtomicBool::new(false)); let updater = Arc::new(Mutex::new(owner_updater::Updater::new( wallet_inst.clone(), @@ -199,6 +211,7 @@ where Owner { wallet_inst, + config_path: config_path.into(), doctest_mode: false, doctest_retain_tld: false, shared_key: Arc::new(Mutex::new(None)), @@ -206,21 +219,49 @@ where updater_running, status_tx: Mutex::new(Some(tx)), updater_messages, - tor_config: Mutex::new(None), } } + /// Return the active wallet configuration path. + pub fn config_path(&self) -> PathBuf { + self.config_path.get() + } + + /// Return the shared wallet configuration path. + #[doc(hidden)] + pub fn shared_config_path(&self) -> crate::ConfigPath { + self.config_path.clone() + } + /// Set the TOR configuration for this instance of the OwnerAPI, used during - /// `init_send_tx` when send args are present and a TOR address is specified + /// `init_send_tx` when send args are present and a TOR address is specified, + /// this will also update persistent config and will restart foreign listener /// /// # Arguments /// * `tor_config` - The optional [TorConfig](#) to use /// # Returns - /// * Nothing + /// * Result Containing: + /// * `Ok(())` if the config was correctly saved + /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. + /// - pub fn set_tor_config(&self, tor_config: Option) { - let mut lock = self.tor_config.lock(); - *lock = tor_config; + pub fn set_tor_config(&self, tor_config: Option) -> Result<(), Error> { + let _wallet_lock = self.wallet_inst.lock(); + update_global_config(&self.config_path(), |config| { + if let Some(tor_config) = tor_config { + config.members.tor = Some(tor_config); + } else if let Some(tor) = config.members.tor.as_mut() { + tor.use_tor_listener = false; + tor.skip_send_attempt = Some(true); + } else { + let mut tor_config = config.tor_config(); + tor_config.use_tor_listener = false; + tor_config.skip_send_attempt = Some(true); + config.members.tor = Some(tor_config); + } + Ok(()) + }) + .map_err(|e| Error::TorConfig(format!("{}", e))) } /// Returns a list of accounts stored in the wallet (i.e. mappings between @@ -245,7 +286,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let result = api_owner.accounts(None); /// @@ -296,7 +337,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let result = api_owner.create_account_path(None, "account1"); /// @@ -343,7 +384,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let result = api_owner.create_account_path(None, "account1"); /// @@ -399,7 +440,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let show_spent = false; /// let update_from_node = true; /// let tx_id = None; @@ -470,7 +511,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let update_from_node = true; /// let tx_id = None; /// let tx_slate_id = None; @@ -549,7 +590,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let update_from_node = true; /// let minimum_confirmations=10; /// @@ -636,7 +677,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// // Attempt to create a transaction using the 'default' account /// let args = InitTxArgs { /// src_acct_name: None, @@ -666,41 +707,33 @@ where args: InitTxArgs, ) -> Result { let send_args = args.send_args.clone(); - let slate = { + let (slate, tor_config) = { let mut w_lock = self.wallet_inst.lock(); + let tor_config = send_args + .as_ref() + .map(|_| crate::tor_config::load(&self.config_path())) + .transpose()?; let w = w_lock.lc_provider()?.wallet_inst()?; - owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)? + let slate = owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; + (slate, tor_config) }; // Helper functionality. If send arguments exist, attempt to send sync and // finalize - let skip_tor = match send_args.as_ref() { - None => false, - Some(sa) => sa.skip_tor, - }; match send_args { Some(sa) => { - let tor_config_lock = self.tor_config.lock(); - let tc = tor_config_lock.clone(); - let tc = match tc { - Some(mut c) => { - c.skip_send_attempt = Some(skip_tor); - Some(c) - } - None => None, - }; - let res = try_slatepack_sync_workflow( - &slate, - &sa.dest, - tc, - None, - false, - self.doctest_mode, - ); + let tc = tor_config.ok_or_else(|| { + Error::TorConfig("Tor config was not loaded with send arguments".into()) + })?; + let can_send = tc.send_tor(sa.skip_tor); + if self.doctest_mode || !can_send { + return Ok(slate); + } + let res = try_slatepack_sync_workflow(&slate, &sa.dest, Some(tc), None, false); match res { - Ok(Some(s)) => { + Ok(s) => { + self.tx_lock_outputs(keychain_mask, &s)?; + let ret_slate = self.finalize_tx(keychain_mask, &s)?; if sa.post_tx { - self.tx_lock_outputs(keychain_mask, &s)?; - let ret_slate = self.finalize_tx(keychain_mask, &s)?; let result = self.post_tx(keychain_mask, &ret_slate, sa.fluff); match result { Ok(_) => { @@ -713,13 +746,13 @@ where } } } else { - self.tx_lock_outputs(keychain_mask, &s)?; - let ret_slate = self.finalize_tx(keychain_mask, &s)?; Ok(ret_slate) } } - Ok(None) => Ok(slate), - Err(_) => Ok(slate), + Err(e) => { + error!("Error on sending over Tor: {}", e); + Ok(slate) + } } } None => Ok(slate), @@ -748,7 +781,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let args = IssueInvoiceTxArgs { /// amount: 60_000_000_000, @@ -854,7 +887,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// // . . . /// // The slate has been recieved from the invoicer, somehow @@ -883,33 +916,52 @@ where slate: &Slate, args: InitTxArgs, ) -> Result { - let mut w_lock = self.wallet_inst.lock(); - let w = w_lock.lc_provider()?.wallet_inst()?; let send_args = args.send_args.clone(); - let slate = owner::process_invoice_tx(w, keychain_mask, slate, args, self.doctest_mode)?; + let (slate, tor_config) = { + let mut w_lock = self.wallet_inst.lock(); + let tor_config = send_args + .as_ref() + .map(|_| crate::tor_config::load(&self.config_path())) + .transpose()?; + let w = w_lock.lc_provider()?.wallet_inst()?; + let slate = + owner::process_invoice_tx(w, keychain_mask, slate, args, self.doctest_mode)?; + (slate, tor_config) + }; // Helper functionality. If send arguments exist, attempt to send match send_args { Some(sa) => { - let tor_config_lock = self.tor_config.lock(); - let tc = tor_config_lock.clone(); - let tc = match tc { - Some(mut c) => { - c.skip_send_attempt = Some(sa.skip_tor); - Some(c) - } - None => None, - }; - let res = try_slatepack_sync_workflow( - &slate, - &sa.dest, - tc, - None, - true, - self.doctest_mode, - ); + let tc = tor_config.ok_or_else(|| { + Error::TorConfig("Tor config was not loaded with send arguments".into()) + })?; + let can_send = tc.send_tor(sa.skip_tor); + if self.doctest_mode || !can_send { + return Ok(slate); + } + let res = try_slatepack_sync_workflow(&slate, &sa.dest, Some(tc), None, true); match res { - Ok(s) => Ok(s.unwrap()), - Err(_) => Ok(slate), + Ok(s) => { + // Update slate state. + { + let mut w_lock = self.wallet_inst.lock(); + let w = w_lock.lc_provider()?.wallet_inst()?; + let parent_key_id = w.parent_key_id(); + match update_tx_slate_state(w, keychain_mask, &parent_key_id, &s) { + Ok(_) => {} + Err(e) => error!("Error on updating slate state: {}", e), + } + } + // Output slatepack message to file. + match output_slatepack_file(&self, keychain_mask, &s, &sa.dest) { + Ok(_) => {} + Err(e) => error!("Error on saving output slatepack message: {}", e), + } + Ok(s) + } + Err(e) => { + error!("Error on sending over Tor: {}", e); + Ok(slate) + } } } None => Ok(slate), @@ -947,7 +999,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let args = InitTxArgs { /// src_acct_name: None, /// amount: 2_000_000_000, @@ -1009,7 +1061,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let args = InitTxArgs { /// src_acct_name: None, /// amount: 2_000_000_000, @@ -1068,7 +1120,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let args = InitTxArgs { /// src_acct_name: None, /// amount: 2_000_000_000, @@ -1139,7 +1191,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let args = InitTxArgs { /// src_acct_name: None, /// amount: 2_000_000_000, @@ -1210,7 +1262,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let update_from_node = true; /// let tx_id = None; /// let tx_slate_id = None; @@ -1254,7 +1306,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let result = api_owner.scan( /// None, /// Some(20000), @@ -1294,7 +1346,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let result = api_owner.scan( /// None, /// Some(20000), @@ -1358,7 +1410,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); + /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let result = api_owner.scan( /// None, /// Some(20000), @@ -1416,7 +1468,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let result = api_owner.node_height(None); /// /// if let Ok(node_height_result) = result { @@ -1473,7 +1525,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let result = api_owner.get_top_level_directory(); /// /// if let Ok(dir) = result { @@ -1498,6 +1550,9 @@ where /// Set [`get_top_level_directory`](struct.Owner.html#method.get_top_level_directory) for a /// description of the top level directory and default paths. /// + /// The wallet must be closed and the updater stopped before changing this directory. + /// Open the wallet again afterwards to load its database from the new location. + /// /// # Arguments /// /// * `dir`: The new top-level directory path (either relative to current directory or @@ -1521,7 +1576,7 @@ where /// # .ok_or("Failed to convert tmpdir path to string.".to_owned()) /// # .unwrap(); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from(dir)); /// let result = api_owner.set_top_level_directory(dir); /// /// if let Ok(dir) = result { @@ -1530,9 +1585,25 @@ where /// ``` pub fn set_top_level_directory(&self, dir: &str) -> Result<(), Error> { + if self.updater_running.load(Ordering::Relaxed) { + return Err(Error::Lifecycle( + "Stop the updater before changing the top-level directory".into(), + )); + } let mut w_lock = self.wallet_inst.lock(); let lc = w_lock.lc_provider()?; - lc.set_top_level_directory(dir) + if lc.wallet_inst().is_ok() { + return Err(Error::Lifecycle( + "Close the wallet before changing the top-level directory".into(), + )); + } + let config_path = PathBuf::from(dir).join(WALLET_CONFIG_FILE_NAME); + if config_path.exists() { + reload_global_config(&config_path)?; + } + lc.set_top_level_directory(dir)?; + self.config_path.set(config_path); + Ok(()) } /// Create a `grin-wallet.toml` configuration file in the top-level directory for the @@ -1571,7 +1642,7 @@ where /// # .ok_or("Failed to convert tmpdir path to string.".to_owned()) /// # .unwrap(); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from(dir)); /// let _ = api_owner.set_top_level_directory(dir); /// /// let result = api_owner.create_config(&ChainTypes::Mainnet, None, None, None); @@ -1640,7 +1711,7 @@ where /// # .to_str() /// # .ok_or("Failed to convert tmpdir path to string.".to_owned()) /// # .unwrap(); - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from(dir)); /// let _ = api_owner.set_top_level_directory(dir); /// /// // Create configuration @@ -1707,7 +1778,7 @@ where /// # .to_str() /// # .ok_or("Failed to convert tmpdir path to string.".to_owned()) /// # .unwrap(); - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from(dir)); /// let _ = api_owner.set_top_level_directory(dir); /// /// // Create configuration @@ -1764,7 +1835,7 @@ where /// use grin_core::global::ChainTypes; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let res = api_owner.close_wallet(None); /// @@ -1800,7 +1871,7 @@ where /// use grin_core::global::ChainTypes; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let pw = ZeroingString::from("my_password"); /// let res = api_owner.get_mnemonic(None, pw); @@ -1845,7 +1916,7 @@ where /// use grin_core::global::ChainTypes; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let old = ZeroingString::from("my_password"); /// let new = ZeroingString::from("new_password"); @@ -1888,7 +1959,7 @@ where /// use grin_core::global::ChainTypes; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let res = api_owner.delete_wallet(None); /// @@ -1944,7 +2015,7 @@ where /// use std::time::Duration; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let res = api_owner.start_updater(None, Duration::from_secs(60)); /// @@ -1999,7 +2070,7 @@ where /// use std::time::Duration; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let res = api_owner.start_updater(None, Duration::from_secs(60)); /// @@ -2041,7 +2112,7 @@ where /// use std::time::Duration; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let res = api_owner.start_updater(None, Duration::from_secs(60)); /// @@ -2107,7 +2178,7 @@ where /// use std::time::Duration; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let res = api_owner.get_slatepack_address(None, 0); /// @@ -2147,7 +2218,7 @@ where /// use std::time::Duration; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// let res = api_owner.get_slatepack_secret_key(None, 0); /// @@ -2188,9 +2259,8 @@ where /// use std::time::Duration; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// - /// let mut api_owner = Owner::new(wallet.clone(), None); /// let args = InitTxArgs { /// src_acct_name: None, /// amount: 2_000_000_000, @@ -2258,7 +2328,7 @@ where /// use std::time::Duration; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// // ... receive a slatepack from somewhere /// # let slatepack_string = String::from(""); /// let res = api_owner.slate_from_slatepack_message( @@ -2308,7 +2378,7 @@ where /// use std::time::Duration; /// /// // Set up as above - /// # let api_owner = Owner::new(wallet.clone(), None); + /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// # let slatepack_string = String::from(""); /// // .. receive a slatepack from somewhere /// let res = api_owner.decode_slatepack_message( @@ -2366,7 +2436,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let update_from_node = true; /// let tx_id = None; /// let tx_slate_id = Some(Uuid::parse_str("0436430c-2b02-624c-2032-570501212b00").unwrap()); @@ -2462,7 +2532,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let update_from_node = true; /// let tx_id = None; /// let tx_slate_id = Some(Uuid::parse_str("0436430c-2b02-624c-2032-570501212b00").unwrap()); @@ -2524,7 +2594,7 @@ where /// ``` /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// - /// let api_owner = Owner::new(wallet.clone(), None); + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let keychain_mask = None; /// let params = MixnetReqCreationParams { /// server_keys: vec![], // Public keys here in secret key representation @@ -2571,83 +2641,63 @@ pub fn try_slatepack_sync_workflow( slate: &Slate, dest: &str, tor_config: Option, - tor_sender: Option, + tor_sender: Option, send_to_finalize: bool, - test_mode: bool, -) -> Result, Error> { - if let Some(tc) = &tor_config { - if tc.skip_send_attempt == Some(true) { - return Ok(None); - } - } +) -> Result { let mut ret_slate = Slate::blank(2, false); - let mut send_sync = |mut sender: HttpSlateSender, method_str: &str| match sender - .send_tx(&slate, send_to_finalize) - { - Ok(s) => { - ret_slate = s; - return Ok(()); - } - Err(e) => { - debug!( - "Send ({}): Could not send Slate via {}: {}", - method_str, method_str, e - ); - return Err(e); - } + let mut send_sync = |mut sender: TorSlateSender, method_str: &str| { + return match sender.send_tx(&slate, send_to_finalize) { + Ok(s) => { + ret_slate = s; + Ok(()) + } + Err(e) => { + debug!( + "Send ({}): Could not send Slate via {}: {}", + method_str, method_str, e + ); + Err(e) + } + }; }; - // Try parsing Slatepack address + // Try parsing Slatepack address. match SlatepackAddress::try_from(dest) { Ok(address) => { - let tor_addr = OnionV3Address::try_from(&address).unwrap(); - // Try sending to the destination via TOR + let tor_addr = OnionV3Address::try_from(&address).map_err(|_| { + Error::SlatepackAddress(format!( + "Destination {} is not a valid Onion address.", + dest + )) + })?; + // Try sending to the destination via Tor. let sender = match tor_sender { None => { - if test_mode { - None - } else { - match HttpSlateSender::with_socks_proxy( - &tor_addr.to_http_str(), - &tor_config.as_ref().unwrap().socks_proxy_addr, - &tor_config.as_ref().unwrap().send_config_dir, - tor_config.as_ref().unwrap().bridge.clone(), - tor_config.as_ref().unwrap().proxy.clone(), - ) { - Ok(s) => Some(s), + if let Some(tc) = tor_config { + match TorSlateSender::new(&tor_addr.to_http_str(), tc) { + Ok(s) => s, Err(e) => { - debug!("Send (TOR): Cannot create TOR Slate sender {:?}", e); - None + debug!("Send (Tor): Cannot create TOR Slate sender {:?}", e); + return Err(e); } } - } - } - Some(s) => { - if test_mode { - None } else { - Some(s) + return Err(Error::TorConfig("Tor config is not set".to_string())); } } + Some(s) => s, }; - if let Some(s) = sender { - warn!("Attempting to send transaction via TOR"); - match send_sync(s, "TOR") { - Ok(_) => return Ok(Some(ret_slate)), - Err(e) => { - debug!("Unable to send via TOR: {}", e); - warn!("Unable to send transaction via TOR"); - } - } + warn!("Attempting to send transaction via Tor"); + match send_sync(sender, "Tor") { + Ok(_) => Ok(ret_slate), + Err(e) => Err(e), } } Err(e) => { - debug!("Send (TOR): Destination is not SlatepackAddress {:?}", e); - warn!("Destination is not a valid Slatepack address. Will output Slatepack.") + error!("Destination {} is not a valid Slatepack address.", dest); + Err(e) } } - - Ok(None) } #[doc(hidden)] @@ -2697,8 +2747,12 @@ macro_rules! doctest_helper_setup_doc_env { wallet_config.data_file_dir = dir.to_owned(); let pw = ZeroingString::from(""); - let node_client = - HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None).unwrap(); + let node_client = HTTPNodeClient::new( + &wallet_config.check_node_api_http_addr, + None, + wallet_config.api_request_timeout(), + ) + .unwrap(); let mut wallet = Box::new(DefaultWalletImpl::::new(node_client.clone()).unwrap()) as Box< @@ -2715,3 +2769,38 @@ macro_rules! doctest_helper_setup_doc_env { let mut $wallet = Arc::new(Mutex::new(wallet)); }; } + +/// Output slatepack message to file. +fn output_slatepack_file( + api: &Owner, + keychain_mask: Option<&SecretKey>, + slate: &Slate, + dest: &str, +) -> Result<(), Error> +where + L: WalletLCProvider<'static, C, K> + 'static, + C: NodeClient + 'static, + K: Keychain + 'static, +{ + let address = match SlatepackAddress::try_from(dest) { + Ok(a) => Some(a), + Err(_) => None, + }; + // encrypt for recipient by default + let recipients = match address.clone() { + Some(a) => vec![a], + None => vec![], + }; + let message = api.create_slatepack_message(keychain_mask, &slate, Some(0), recipients)?; + let tld = api.get_top_level_directory()?; + + // Create a directory to which files will be output. + let slate_dir = format!("{}/{}", tld, "slatepack"); + let _ = std::fs::create_dir_all(slate_dir.clone()); + let out_file_name = format!("{}/{}.{}.slatepack", slate_dir, slate.id, slate.state); + + let mut output = File::create(out_file_name.clone())?; + output.write_all(&message.as_bytes())?; + output.sync_all()?; + Ok(()) +} diff --git a/api/src/owner_rpc.rs b/api/src/owner_rpc.rs index 0fb4ad9..8b8a2bf 100644 --- a/api/src/owner_rpc.rs +++ b/api/src/owner_rpc.rs @@ -39,6 +39,7 @@ use easy_jsonrpc_mw; use grin_wallet_util::OnionV3Address; use rand::thread_rng; use std::convert::TryFrom; +use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -1241,6 +1242,9 @@ pub trait OwnerRpc { /** Networked version of [Owner::set_top_level_directory](struct.Owner.html#method.set_top_level_directory). + + The wallet must be closed and the updater stopped before calling this method. Running listeners + should be restarted after opening the wallet from the new directory. ``` # grin_wallet_api::doctest_helper_json_rpc_owner_assert_response!( # r#" @@ -2500,7 +2504,7 @@ where } fn set_tor_config(&self, tor_config: Option) -> Result<(), Error> { - Owner::set_tor_config(self, tor_config); + Owner::set_tor_config(self, tor_config)?; Ok(()) } @@ -2564,6 +2568,7 @@ pub fn run_doctest_owner( ) -> Result, String> { use easy_jsonrpc_mw::Handler; use grin_keychain::ExtKeychain; + use grin_wallet_config::initial_setup_wallet; use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy}; use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl}; use grin_wallet_libwallet::{api_impl, WalletInst}; @@ -2577,6 +2582,14 @@ pub fn run_doctest_owner( let _ = fs::remove_dir_all(test_dir); global::set_local_chain_type(ChainTypes::AutomatedTesting); + let _ = fs::create_dir_all(test_dir); + let config = initial_setup_wallet( + &ChainTypes::AutomatedTesting, + Some(PathBuf::from(test_dir)), + false, + ) + .unwrap(); + let mut wallet_proxy: WalletProxy< DefaultLCProvider, LocalWalletClient, @@ -2584,11 +2597,11 @@ pub fn run_doctest_owner( > = WalletProxy::new(test_dir); let chain = wallet_proxy.chain.clone(); - let rec_phrase_1 = util::ZeroingString::from( + let rec_phrase_1 = ZeroingString::from( "fat twenty mean degree forget shell check candy immense awful \ flame next during february bulb bike sun wink theory day kiwi embrace peace lunch", ); - let empty_string = util::ZeroingString::from(""); + let empty_string = ZeroingString::from(""); let client1 = LocalWalletClient::new("wallet1", wallet_proxy.tx.clone()); let mut wallet1 = @@ -2623,7 +2636,7 @@ pub fn run_doctest_owner( let mut slate_outer = Slate::blank(2, false); - let rec_phrase_2 = util::ZeroingString::from( + let rec_phrase_2 = ZeroingString::from( "hour kingdom ripple lunch razor inquiry coyote clay stamp mean \ sell finish magic kid tiny wage stand panther inside settle feed song hole exile", ); @@ -2746,8 +2759,11 @@ pub fn run_doctest_owner( ); } - let mut api_owner = Owner::new(wallet1, None); + let mut api_owner = Owner::new(wallet1, None, config.config_file_path); api_owner.doctest_mode = true; + if request["method"] == "set_top_level_directory" { + api_owner.close_wallet(None).unwrap(); + } let owner_api = &api_owner as &dyn OwnerRpc; let res = owner_api.handle_request(request).as_option(); let _ = fs::remove_dir_all(test_dir); diff --git a/api/src/tor_config.rs b/api/src/tor_config.rs new file mode 100644 index 0000000..3ef7a2f --- /dev/null +++ b/api/src/tor_config.rs @@ -0,0 +1,45 @@ +// Copyright 2026 The Grin Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::config::TorConfig; +use crate::libwallet::Error; +use crate::util::Mutex; +use grin_wallet_config::config::get_global_config; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +/// Shared path to the active wallet configuration. +#[doc(hidden)] +#[derive(Clone)] +pub struct ConfigPath(Arc>); + +impl ConfigPath { + pub(crate) fn get(&self) -> PathBuf { + self.0.lock().clone() + } + + pub(crate) fn set(&self, path: PathBuf) { + *self.0.lock() = path; + } +} + +impl From for ConfigPath { + fn from(path: PathBuf) -> Self { + Self(Arc::new(Mutex::new(path))) + } +} + +pub(crate) fn load(config_path: &Path) -> Result { + Ok(get_global_config(config_path)?.tor_config()) +} diff --git a/api/src/types.rs b/api/src/types.rs index 4ac88a3..797901a 100644 --- a/api/src/types.rs +++ b/api/src/types.rs @@ -16,7 +16,7 @@ use crate::libwallet::slate_versions::ser as dalek_ser; use crate::libwallet::Error; use crate::util::secp::key::{PublicKey, SecretKey}; use crate::util::{from_hex, ToHex}; -use ed25519_dalek::SecretKey as DalekSecretKey; +use ed25519_dalek::SigningKey as DalekSecretKey; use base64; use rand::{thread_rng, Rng}; diff --git a/config/Cargo.toml b/config/Cargo.toml index 137dc36..a50f1e4 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_config" -version = "5.4.0-alpha.1" +version = "5.4.1" authors = ["Grin Developers "] description = "Configuration for grin wallet , a simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format." license = "Apache-2.0" @@ -14,31 +14,17 @@ rand = "0.6" serde = "1" serde_derive = "1" toml = "0.5" +toml_edit = "0.22" dirs = "2.0" - -grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" } +lazy_static = "1" ##### Grin Imports -# For Release -#grin_core = "5.4.0" -#grin_util = "5.4.0" - -# For beta release - -#grin_core = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3"} -#grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } - -# For bleeding edge -grin_core = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_util = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } - -# For local testing -# grin_core = { path = "../../grin/core"} -# grin_util = { path = "../../grin/util"} +grin_core = { path = "../grin/core"} +grin_util = { path = "../grin/util"} ##### [dev-dependencies] -pretty_assertions = "0.6" +tempfile = "3.1" diff --git a/config/src/comments.rs b/config/src/comments.rs index c027042..a303c62 100644 --- a/config/src/comments.rs +++ b/config/src/comments.rs @@ -70,6 +70,13 @@ fn comments() -> HashMap { "check_node_api_http_addr".to_string(), " #where the wallet should find a running node +" + .to_string(), + ); + retval.insert( + "node_api_request_timeout_secs".to_string(), + " +#total timeout for requests to node API " .to_string(), ); @@ -206,16 +213,24 @@ fn comments() -> HashMap { "[tor]".to_string(), " ######################################### -### TOR CONFIGURATION (Experimental) ### +### TOR CONFIGURATION ### ######################################### " .to_string(), ); + retval.insert( + "use_integrated".to_string(), + " +#Whether to use integrated Tor library +" + .to_string(), + ); + retval.insert( "skip_send_attempt".to_string(), " -#Whether to skip send attempts (used for debugging) +#Whether to skip send attempts (default false) " .to_string(), ); @@ -244,6 +259,22 @@ fn comments() -> HashMap { .to_string(), ); + retval.insert( + "request_timeout_secs".to_string(), + " +#Tor request timeout in seconds +" + .to_string(), + ); + + retval.insert( + "bootstrap_timeout_secs".to_string(), + " +#Tor bootstrap timeout in seconds +" + .to_string(), + ); + retval.insert( "[tor.bridge]".to_string(), " @@ -259,8 +290,11 @@ fn comments() -> HashMap { " #Tor bridge relay: allow to send and receive via TOR in a country where it is censored. #Enable it by entering a single bridge line. To disable it, you must comment it. -#Support of the transport: obfs4, meek and snowflake. -#obfs4proxy or snowflake client binary must be installed and on your path. +#Support of the transport: webtunnel, obfs4, and snowflake. +#webtunnel, obfs4proxy or snowflake client binary must be installed and on your path. +#Custom path for client binary +#bridge_bin_path = \"\" + #For example, the bridge line must be in the following format for obfs4 transport: \"obfs4 [IP:PORT] [FINGERPRINT] cert=[CERT] iat-mode=[IAT-MODE]\" #bridge_line = \"\" @@ -279,10 +313,10 @@ fn comments() -> HashMap { } fn get_key(line: &str) -> String { - if line.contains('[') && line.contains(']') { + if line.starts_with('[') && line.ends_with(']') { line.to_owned() - } else if line.contains('=') { - line.split('=').collect::>()[0].trim().to_owned() + } else if let Some((key, _)) = line.split_once('=') { + key.trim().to_owned() } else { "NOT_FOUND".to_owned() } @@ -306,91 +340,3 @@ pub fn insert_comments(orig: String) -> String { } ret_val } - -pub fn migrate_comments( - old_config: String, - new_config: String, - old_version: Option, -) -> String { - let comments = comments(); - // Prohibe the key we are basing on to introduce new comments for [tor.proxy] - let prohibited_key = match old_version { - None => vec!["[logging]"], - Some(_) => vec![], - }; - let mut vec_old_conf = vec![]; - let mut hm_key_cmt_old = HashMap::new(); - let old_conf: Vec<&str> = old_config.split_inclusive('\n').collect(); - // collect old key in a vec and insert old key/comments from the old conf in a hashmap - let vec_key_old = old_conf - .iter() - .filter_map(|line| { - let line_nospace = line.trim(); - let is_ascii_control = line_nospace.chars().all(|x| x.is_ascii_control()); - match line.contains("#") || is_ascii_control { - true => { - vec_old_conf.push(line.to_owned()); - None - } - false => { - let comments: String = vec_old_conf.iter().flat_map(|s| s.chars()).collect(); - let key = get_key(line_nospace); - match key != "NOT_FOUND" { - true => { - vec_old_conf.clear(); - hm_key_cmt_old.insert(key.clone(), comments); - Some(key) - } - false => None, - } - } - } - }) - .collect::>(); - - let new_conf: Vec<&str> = new_config.split_inclusive('\n').collect(); - // collect new key and the whole key line from the new config - let vec_key_cmt_new = new_conf - .iter() - .filter_map(|line| { - let line_nospace = line.trim(); - let is_ascii_control = line_nospace.chars().all(|x| x.is_ascii_control()); - match !line.contains("#") && !is_ascii_control { - true => { - let key = get_key(line_nospace); - match key != "NOT_FOUND" { - true => Some((key, line_nospace.to_string())), - false => None, - } - } - false => None, - } - }) - .collect::>(); - - let mut new_config_str = String::from(""); - // Merging old comments in the new config (except if the key is contained in the prohibited vec) with all new introduced key comments - for (key, key_line) in vec_key_cmt_new { - let old_key_exist = vec_key_old.iter().any(|old_key| *old_key == key); - let key_fmt = format!("{}\n", key_line); - if old_key_exist { - if prohibited_key.contains(&key.as_str()) { - // push new config key/comments - let value = comments.get(&key).unwrap(); - new_config_str.push_str(value); - new_config_str.push_str(&key_fmt); - } else { - // push old config key/comment - let value = hm_key_cmt_old.get(&key).unwrap(); - new_config_str.push_str(value); - new_config_str.push_str(&key_fmt); - } - } else { - // old key does not exist, we push new key/comments - let value = comments.get(&key).unwrap(); - new_config_str.push_str(value); - new_config_str.push_str(&key_fmt); - } - } - new_config_str -} diff --git a/config/src/config.rs b/config/src/config.rs index 2c37ae7..c32a5bb 100644 --- a/config/src/config.rs +++ b/config/src/config.rs @@ -14,24 +14,57 @@ //! Configuration file management -use crate::comments::{insert_comments, migrate_comments}; +use crate::comments::insert_comments; use crate::core::global; use crate::types::{ ConfigError, GlobalWalletConfig, GlobalWalletConfigMembers, TorBridgeConfig, TorProxyConfig, }; use crate::types::{TorConfig, WalletConfig}; use crate::util::logger::LoggingConfig; +use crate::util::{Mutex, RwLock}; + +use lazy_static::lazy_static; use rand::distributions::{Alphanumeric, Distribution}; -use rand::thread_rng; +use rand::{thread_rng, Rng}; +use std::collections::hash_map::Entry; +use std::collections::HashMap; use std::env; -use std::fs::{self, File}; +use std::fs::{self, File, OpenOptions}; use std::io::prelude::*; use std::io::BufReader; use std::path::{Path, PathBuf}; +use std::sync::mpsc::Sender; +use std::sync::Arc; use toml; +use toml_edit::{DocumentMut, Table}; + +type ConfigListeners = HashMap>; +type ConfigRegistry = HashMap; + +lazy_static! { + /// Global configuration instances and change listeners mapped to config path. + static ref CONFIG_INSTANCES: Arc> = + Arc::new(RwLock::new(HashMap::new())); + static ref CONFIG_SAVE_LOCK: Mutex<()> = Mutex::new(()); +} + +fn cache_loaded_config( + configs: &mut ConfigRegistry, + config_path: &Path, + config: GlobalWalletConfig, +) -> GlobalWalletConfig { + match configs.entry(config_path.to_path_buf()) { + Entry::Vacant(entry) => { + entry.insert((config.clone(), HashMap::new())); + config + } + Entry::Occupied(entry) => entry.get().0.clone(), + } +} /// Wallet configuration file name pub const WALLET_CONFIG_FILE_NAME: &str = "grin-wallet.toml"; +/// Wallet logging file name const WALLET_LOG_FILE_NAME: &str = "grin-wallet.log"; /// .grin folder, usually in home/.grin pub const GRIN_HOME: &str = ".grin"; @@ -42,6 +75,91 @@ pub const API_SECRET_FILE_NAME: &str = ".foreign_api_secret"; /// Owner API secret pub const OWNER_API_SECRET_FILE_NAME: &str = ".owner_api_secret"; +fn set_global_config(config: GlobalWalletConfig) { + let mut configs = CONFIG_INSTANCES.write(); + let mut listeners = if let Some((_, l)) = configs.get(&config.config_file_path) { + l.clone() + } else { + HashMap::new() + }; + // Update config. + configs.insert( + config.config_file_path.clone(), + (config.clone(), listeners.clone()), + ); + // Notify listeners. + let mut failed = vec![]; + for l in listeners.clone() { + match l.1.send(()) { + Ok(_) => {} + Err(_) => { + failed.push(l.0.to_string()); + } + } + } + for f in &failed { + listeners.remove(f); + } + // Update listener list. + if !failed.is_empty() { + configs.insert(config.config_file_path.clone(), (config, listeners)); + } +} + +/// Reload configuration from disk and update the global instance. +pub fn reload_global_config(config_path: &Path) -> Result { + let _save_lock = CONFIG_SAVE_LOCK.lock(); + let config = GlobalWalletConfig::new(config_path.to_path_buf())?; + set_global_config(config.clone()); + Ok(config) +} + +/// Get global configuration using provided path. +pub fn get_global_config(config_path: &Path) -> Result { + { + let configs = CONFIG_INSTANCES.read(); + if let Some((config, _)) = configs.get(config_path) { + return Ok(config.clone()); + } + } + let config = GlobalWalletConfig::new(config_path.to_path_buf())?; + let mut configs = CONFIG_INSTANCES.write(); + Ok(cache_loaded_config(&mut configs, config_path, config)) +} + +/// Load, update and save a configuration as one operation. +pub fn update_global_config(config_path: &Path, update: F) -> Result<(), ConfigError> +where + F: FnOnce(&mut GlobalWalletConfig) -> Result<(), ConfigError>, +{ + let _save_lock = CONFIG_SAVE_LOCK.lock(); + let mut config = GlobalWalletConfig::new(config_path.to_path_buf())?; + update(&mut config)?; + config.save_locked() +} + +/// Add listener on config change. +pub fn add_global_config_listener(config_path: &PathBuf, listener_id: &str, tx: Sender<()>) { + let mut w_l = CONFIG_INSTANCES.write(); + match w_l.get_mut(config_path) { + None => {} + Some((_, listeners)) => { + listeners.insert(listener_id.to_string(), tx); + } + } +} + +/// Remove listener on config change. +pub fn remove_global_config_listener(config_path: &PathBuf, listener_id: &str) { + let mut w_l = CONFIG_INSTANCES.write(); + match w_l.get_mut(config_path) { + None => {} + Some((_, listeners)) => { + listeners.remove(listener_id); + } + } +} + /// Function to locate the wallet dir and grin-wallet.toml in the order /// a) config in top-dir if provided, b) in working dir, c) default dir /// Function to get wallet dir and create dirs if not existing @@ -50,7 +168,7 @@ pub fn get_wallet_path( create_path: bool, ) -> Result { // A - Detect grin-wallet.toml in working dir - let mut config_path = std::env::current_dir()?; + let mut config_path = env::current_dir()?; config_path.push(WALLET_CONFIG_FILE_NAME); if create_path == false && config_path.exists() { config_path.pop(); @@ -58,10 +176,7 @@ pub fn get_wallet_path( return Ok(config_path); }; // B - Select home directory - let mut wallet_path = match dirs::home_dir() { - Some(p) => p, - None => PathBuf::new(), - }; + let mut wallet_path = dirs::home_dir().unwrap_or_else(|| PathBuf::new()); wallet_path.push(GRIN_HOME); wallet_path.push(chain_type.shortname()); // Create if the default path doesn't exist @@ -96,10 +211,7 @@ pub fn get_node_path( Ok(node_path) // 1) B If top dir exists, but no api_secret, return home dir } else { - let mut node_path = match dirs::home_dir() { - Some(p) => p, - None => PathBuf::new(), - }; + let mut node_path = dirs::home_dir().unwrap_or_else(|| PathBuf::new()); node_path.push(GRIN_HOME); node_path.push(chain_type.shortname()); Ok(node_path) @@ -107,10 +219,7 @@ pub fn get_node_path( } // 2) If there is no top_dir provided, always return home dir None => { - let mut node_path = match dirs::home_dir() { - Some(p) => p, - None => PathBuf::new(), - }; + let mut node_path = dirs::home_dir().unwrap_or_else(|| PathBuf::new()); node_path.push(GRIN_HOME); node_path.push(chain_type.shortname()); Ok(node_path) @@ -187,8 +296,11 @@ fn check_api_secret_file( } /// Initial wallet setup does the following -/// 1) Load wallet config if run without 'init' 2) create wallet if run with 'init'' -/// Try in thiss order a) current dir as template, b) in top path, or c) .grin home +/// 1) Load wallet config if run without 'init' 2) create wallet if run with 'init' +/// Try in this order: +/// a) current dir as template, +/// b) in top path, or +/// c) .grin home /// - load default config values /// - update the wallet and node dir to the correct paths /// - if grin-wallet.toml exists, but the wallet data dir does not, load config and continue wallet generation @@ -214,8 +326,7 @@ pub fn initial_setup_wallet( } else { env::current_dir()?.join(&fixed_path).canonicalize()? }; - let absolute_path = - std::path::PathBuf::from(absolute_path.to_str().unwrap().replace(r"\\?\", "")); + let absolute_path = PathBuf::from(absolute_path.to_str().unwrap().replace(r"\\?\", "")); data_path = Some(absolute_path); // Store the updated path } } @@ -234,12 +345,11 @@ pub fn initial_setup_wallet( config_path.push(WALLET_CONFIG_FILE_NAME); let mut data_dir = wallet_path.clone(); data_dir.push(GRIN_WALLET_DIR); - // Check if a config exists in theworking dir, if so load it + // Check if a config exists in the working dir, if so load it let (path, config) = match config_path.clone().exists() { // If the config does not exist, load default and updated node and wallet dir false => { - let mut default_config = GlobalWalletConfig::for_chain(chain_type); - default_config.config_file_path = Some(config_path.clone()); + let mut default_config = GlobalWalletConfig::for_chain(chain_type, &config_path); default_config.update_paths(&wallet_path, &node_path); // Write config file @@ -260,7 +370,7 @@ pub fn initial_setup_wallet( // Return config if not run with init true => { - // If run with init and seed does not yet exists, continue, else throw error + // If run with init and seed do not yet exists, continue, else throw error if data_dir.exists() && create_path == true { let msg = format!( "{} already exists in the target directory ({}). Please remove it first", @@ -269,12 +379,15 @@ pub fn initial_setup_wallet( ); return Err(ConfigError::SerializationError(msg)); } else { - let config = GlobalWalletConfig::new(config_path.to_str().unwrap())?; + let config = GlobalWalletConfig::new(config_path)?; (wallet_path, config) } } }; + // Set global config instance. + set_global_config(config.clone()); + // Check API secrets, if ok, return config check_api_secret_file(chain_type, Some(path.clone()), OWNER_API_SECRET_FILE_NAME)?; check_api_secret_file(chain_type, Some(path), API_SECRET_FILE_NAME)?; @@ -293,21 +406,15 @@ impl Default for GlobalWalletConfigMembers { } } -impl Default for GlobalWalletConfig { - fn default() -> GlobalWalletConfig { - GlobalWalletConfig { - config_file_path: None, - members: Some(GlobalWalletConfigMembers::default()), - } - } -} - impl GlobalWalletConfig { /// Same as GlobalConfig::default() but further tweaks parameters to /// apply defaults for each chain type - pub fn for_chain(chain_type: &global::ChainTypes) -> GlobalWalletConfig { - let mut defaults_conf = GlobalWalletConfig::default(); - let defaults = &mut defaults_conf.members.as_mut().unwrap().wallet; + pub fn for_chain(chain_type: &global::ChainTypes, file_path: &PathBuf) -> GlobalWalletConfig { + let mut defaults_conf = GlobalWalletConfig { + config_file_path: file_path.clone(), + members: GlobalWalletConfigMembers::default(), + }; + let defaults = &mut defaults_conf.members.wallet; defaults.chain_type = Some(*chain_type); match *chain_type { @@ -324,17 +431,29 @@ impl GlobalWalletConfig { } defaults_conf } + + /// Return the configured Tor settings, resolving the legacy default when the + /// config file does not yet contain a `[tor]` section. + pub fn tor_config(&self) -> TorConfig { + self.members.tor.clone().unwrap_or_else(|| TorConfig { + send_config_dir: self.members.wallet.data_file_dir.clone(), + ..TorConfig::default() + }) + } + /// Requires the path to a config file - pub fn new(file_path: &str) -> Result { - let mut return_value = GlobalWalletConfig::default(); - return_value.config_file_path = Some(PathBuf::from(&file_path)); + pub fn new(config_file_path: PathBuf) -> Result { + let return_value = GlobalWalletConfig { + config_file_path, + members: GlobalWalletConfigMembers::default(), + }; // Config file path is given but not valid - let config_file = return_value.config_file_path.clone().unwrap(); + let config_file = &return_value.config_file_path; if !config_file.exists() { - return Err(ConfigError::FileNotFoundError(String::from( - config_file.to_str().unwrap(), - ))); + return Err(ConfigError::FileNotFoundError( + config_file.display().to_string(), + )); } // Try to parse the config file if it exists, explode if it does exist but @@ -344,7 +463,7 @@ impl GlobalWalletConfig { /// Read config fn read_config(mut self) -> Result { - let config_file_path = self.config_file_path.as_mut().unwrap(); + let config_file_path = &self.config_file_path; let contents = fs::read_to_string(config_file_path.clone())?; let migrated = GlobalWalletConfig::migrate_config_file_version_none_to_2( contents, @@ -354,11 +473,11 @@ impl GlobalWalletConfig { let decoded: Result = toml::from_str(&fixed); match decoded { Ok(gc) => { - self.members = Some(gc); + self.members = gc; Ok(self) } Err(e) => Err(ConfigError::ParseError( - String::from(self.config_file_path.as_mut().unwrap().to_str().unwrap()), + self.config_file_path.display().to_string(), format!("{}", e), )), } @@ -375,32 +494,18 @@ impl GlobalWalletConfig { data_file_dir.push(GRIN_WALLET_DIR); secret_path.push(OWNER_API_SECRET_FILE_NAME); log_path.push(WALLET_LOG_FILE_NAME); - self.members.as_mut().unwrap().wallet.data_file_dir = - data_file_dir.to_str().unwrap().to_owned(); - self.members.as_mut().unwrap().wallet.node_api_secret_path = + self.members.wallet.data_file_dir = data_file_dir.to_str().unwrap().to_owned(); + self.members.wallet.node_api_secret_path = Some(node_secret_path.to_str().unwrap().to_owned()); - self.members.as_mut().unwrap().wallet.api_secret_path = - Some(secret_path.to_str().unwrap().to_owned()); - self.members - .as_mut() - .unwrap() - .logging - .as_mut() - .unwrap() - .log_file_path = log_path.to_str().unwrap().to_owned(); - self.members - .as_mut() - .unwrap() - .tor - .as_mut() - .unwrap() - .send_config_dir = tor_path.to_str().unwrap().to_owned(); + self.members.wallet.api_secret_path = Some(secret_path.to_str().unwrap().to_owned()); + self.members.logging.as_mut().unwrap().log_file_path = + log_path.to_str().unwrap().to_owned(); + self.members.tor.as_mut().unwrap().send_config_dir = tor_path.to_str().unwrap().to_owned(); } /// Serialize config pub fn ser_config(&mut self) -> Result { - let encoded: Result = - toml::to_string(self.members.as_mut().unwrap()); + let encoded: Result = toml::to_string(&self.members); match encoded { Ok(enc) => Ok(enc), Err(e) => Err(ConfigError::SerializationError(format!("{}", e))), @@ -415,17 +520,111 @@ impl GlobalWalletConfig { old_config: Option, old_version: Option, ) -> Result<(), ConfigError> { - let conf_out = self.ser_config()?; + self.write_to_path(Path::new(name), migration, old_config, old_version) + } + + fn write_to_path( + &mut self, + name: &Path, + migration: bool, + old_config: Option, + old_version: Option, + ) -> Result<(), ConfigError> { + let conf_out = GlobalWalletConfig::fix_log_level(self.ser_config()?); let commented_config = if migration { - migrate_comments(old_config.unwrap(), conf_out, old_version) + let old_config = old_config.unwrap(); + let new_config = insert_comments(conf_out); + GlobalWalletConfig::merge_config(&old_config, &new_config, old_version)? } else { - let fixed_config = GlobalWalletConfig::fix_log_level(conf_out); - insert_comments(fixed_config) + insert_comments(conf_out) }; let mut file = File::create(name)?; file.write_all(commented_config.as_bytes())?; Ok(()) } + + fn merge_config( + old_config: &str, + new_config: &str, + old_version: Option, + ) -> Result { + fn update( + current: &mut Table, + new: &Table, + known: Option<&Table>, + path: &str, + replace_logging_comments: bool, + ) { + if let Some(known) = known { + let removed = known + .iter() + .filter(|(key, _)| !new.contains_key(key)) + .map(|(key, _)| key.to_owned()) + .collect::>(); + for key in removed { + current.remove(&key); + } + } + + for (key, new_item) in new { + let item_path = if path.is_empty() { + key.to_owned() + } else { + format!("{}.{}", path, key) + }; + if let (Some(current_table), Some(new_table)) = ( + current.get_mut(key).and_then(|item| item.as_table_mut()), + new_item.as_table(), + ) { + if replace_logging_comments && item_path == "logging" { + *current_table.decor_mut() = new_table.decor().clone(); + } + update( + current_table, + new_table, + known + .and_then(|table| table.get(key)) + .and_then(|item| item.as_table()), + &item_path, + replace_logging_comments, + ); + } else if let Some(current_item) = current.get_mut(key) { + let mut replacement = new_item.clone(); + if let (Some(current_value), Some(new_value)) = + (current_item.as_value(), replacement.as_value_mut()) + { + *new_value.decor_mut() = current_value.decor().clone(); + } + *current_item = replacement; + } else { + current.insert_formatted(new.key(key).unwrap(), new_item.clone()); + } + } + } + + let mut current = old_config + .parse::() + .map_err(|e| ConfigError::SerializationError(format!("{}", e)))?; + let new = new_config + .parse::() + .map_err(|e| ConfigError::SerializationError(format!("{}", e)))?; + let known_members: GlobalWalletConfigMembers = toml::from_str( + &GlobalWalletConfig::fix_warning_level(old_config.to_owned()), + ) + .map_err(|e| ConfigError::SerializationError(format!("{}", e)))?; + let known = toml::to_string(&known_members) + .map_err(|e| ConfigError::SerializationError(format!("{}", e)))? + .parse::() + .map_err(|e| ConfigError::SerializationError(format!("{}", e)))?; + update( + current.as_table_mut(), + new.as_table(), + Some(known.as_table()), + "", + old_version.is_none(), + ); + Ok(current.to_string()) + } /// This migration does the following: /// - Adds "config_file_version = 2" /// - Introduce new key config_file_version, [tor.bridge] and [tor.proxy] @@ -449,31 +648,265 @@ impl GlobalWalletConfig { ..config }; let mut gc = GlobalWalletConfig { - members: Some(adjusted_config), - config_file_path: Some(config_file_path.clone()), + members: adjusted_config, + config_file_path: config_file_path.clone(), }; - let str_path = config_file_path.into_os_string().into_string().unwrap(); - gc.write_to_file( - &str_path, + gc.write_to_path( + &config_file_path, true, Some(config_str), config.config_file_version, )?; - let adjusted_config_str = fs::read_to_string(str_path.clone())?; + let adjusted_config_str = fs::read_to_string(config_file_path)?; Ok(adjusted_config_str) } // For forwards compatibility old config needs `Warning` log level changed to standard log::Level `WARN` fn fix_warning_level(conf: String) -> String { - conf.replace("Warning", "WARN") + GlobalWalletConfig::replace_log_levels(conf, &[("Warning", "WARN")]) } // For backwards compatibility only first letter of log level should be capitalised. fn fix_log_level(conf: String) -> String { - conf.replace("TRACE", "Trace") - .replace("DEBUG", "Debug") - .replace("INFO", "Info") - .replace("WARN", "Warning") - .replace("ERROR", "Error") + GlobalWalletConfig::replace_log_levels( + conf, + &[ + ("TRACE", "Trace"), + ("DEBUG", "Debug"), + ("INFO", "Info"), + ("WARN", "Warning"), + ("ERROR", "Error"), + ], + ) + } + + fn replace_log_levels(conf: String, replacements: &[(&str, &str)]) -> String { + conf.split_inclusive('\n') + .map(|line| { + let trimmed = line.trim_start(); + if trimmed.starts_with("stdout_log_level =") + || trimmed.starts_with("file_log_level =") + { + replacements + .iter() + .fold(line.to_owned(), |line, (from, to)| line.replace(from, to)) + } else { + line.to_owned() + } + }) + .collect() + } + + /// Save config to file and update global state after editing. + pub fn save(&mut self) -> Result<(), ConfigError> { + let _save_lock = CONFIG_SAVE_LOCK.lock(); + self.save_locked() + } + + fn save_locked(&mut self) -> Result<(), ConfigError> { + let path = self.config_file_path.clone(); + let mut tmp_name = path.as_os_str().to_os_string(); + tmp_name.push(format!("-{}.tmp", thread_rng().gen::())); + let tmp_path = PathBuf::from(tmp_name); + let contents = fs::read_to_string(&path)?; + let permissions = fs::metadata(&path)?.permissions(); + + let save_result = (|| { + OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path)?; + fs::set_permissions(&tmp_path, permissions)?; + self.write_to_path( + &tmp_path, + true, + Some(contents), + self.members.config_file_version, + )?; + fs::rename(&tmp_path, &path)?; + Ok::<(), ConfigError>(()) + })(); + if save_result.is_err() { + let _ = fs::remove_file(&tmp_path); + } + save_result?; + + set_global_config(self.clone()); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::global::ChainTypes; + use std::sync::{Arc, Barrier}; + use std::thread; + use tempfile::tempdir; + + #[test] + fn save_roundtrip() { + let dir = tempdir().unwrap(); + let path = dir.path().join(WALLET_CONFIG_FILE_NAME); + let mut config = GlobalWalletConfig::for_chain(&ChainTypes::AutomatedTesting, &path); + config.members.tor.as_mut().unwrap().proxy.password = Some("secretERROR#[value]".into()); + config.write_to_path(&path, false, None, None).unwrap(); + + let contents = fs::read_to_string(&path) + .unwrap() + .replace( + "api_listen_port = 3415", + "api_listen_port = 3415\n# wallet future\nfuture_setting = \"wallet\"\n# future list\nfuture_values = [\n 1,\n 2,\n]", + ) + .replace( + "use_tor_listener = true", + "# custom key comment\nuse_tor_listener = true # custom inline comment\n# tor future\nfuture_setting = \"tor\"", + ); + fs::write(&path, format!("{contents}\n# custom trailing comment\n")).unwrap(); + let before = fs::read_to_string(&path).unwrap(); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + } + + config.members.tor.as_mut().unwrap().use_tor_listener = false; + config.members.tor.as_mut().unwrap().proxy.password = Some("secretERROR#value".into()); + config.save().unwrap(); + + let contents = fs::read_to_string(&path).unwrap(); + assert_eq!( + contents, + before + .replace("use_tor_listener = true", "use_tor_listener = false") + .replace("secretERROR#[value]", "secretERROR#value") + ); + assert!(contents.contains("# custom trailing comment")); + assert!(contents.contains("# custom key comment")); + assert!(contents.contains("use_tor_listener = false # custom inline comment")); + let stored = GlobalWalletConfig::new(path.clone()).unwrap().tor_config(); + assert!(!stored.use_tor_listener); + assert_eq!(stored.proxy.password.as_deref(), Some("secretERROR#value")); + + config.members.tor.as_mut().unwrap().proxy.transport = Some("socks5".into()); + config.members.tor.as_mut().unwrap().bridge.client_option = Some("option [value]".into()); + config.save().unwrap(); + let stored = GlobalWalletConfig::new(path.clone()).unwrap().tor_config(); + assert_eq!(stored.proxy.transport.as_deref(), Some("socks5")); + assert_eq!( + stored.bridge.client_option.as_deref(), + Some("option [value]") + ); + + config.members.tor.as_mut().unwrap().proxy.transport = None; + config.members.tor.as_mut().unwrap().bridge.client_option = None; + config.save().unwrap(); + let stored = GlobalWalletConfig::new(path.clone()).unwrap().tor_config(); + assert_eq!(stored.proxy.transport, None); + assert_eq!(stored.bridge.client_option, None); + + let legacy = + fs::read_to_string(&path) + .unwrap() + .replacen("config_file_version = 2\n", "", 1); + let mut legacy = legacy.parse::().unwrap(); + let tor = legacy["tor"].as_table_mut().unwrap(); + tor.remove("bridge"); + tor.remove("proxy"); + fs::write(&path, legacy.to_string()).unwrap(); + let migrated = GlobalWalletConfig::new(path.clone()).unwrap(); + assert_eq!(migrated.members.config_file_version, Some(2)); + let migrated = fs::read_to_string(&path).unwrap(); + assert!(migrated.contains("# future list\nfuture_values = [\n 1,\n 2,\n]")); + assert!(migrated.contains("### TOR BRIDGE")); + assert!(migrated.contains("### TOR PROXY")); + assert!(fs::read_dir(dir.path()).unwrap().all(|entry| { + !entry + .unwrap() + .file_name() + .to_string_lossy() + .ends_with(".tmp") + })); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + } + + #[test] + fn legacy_tor() { + let path = PathBuf::from("legacy-wallet.toml"); + let mut config = GlobalWalletConfig::for_chain(&ChainTypes::AutomatedTesting, &path); + config.members.wallet.data_file_dir = "legacy-wallet-data".into(); + config.members.tor = None; + + let resolved = config.tor_config(); + assert_eq!(resolved.send_config_dir, "legacy-wallet-data"); + assert!(resolved.use_tor_listener); + + let disabled = TorConfig { + use_tor_listener: false, + skip_send_attempt: Some(true), + ..TorConfig::default() + }; + config.members.tor = Some(disabled.clone()); + assert_eq!(config.tor_config(), disabled); + } + + #[test] + fn cached_config_wins() { + let path = PathBuf::from("concurrent-wallet.toml"); + let mut cached = GlobalWalletConfig::for_chain(&ChainTypes::AutomatedTesting, &path); + cached.members.tor.as_mut().unwrap().use_tor_listener = false; + let loaded = GlobalWalletConfig::for_chain(&ChainTypes::AutomatedTesting, &path); + let mut configs = HashMap::new(); + configs.insert(path.clone(), (cached.clone(), HashMap::new())); + + let returned = cache_loaded_config(&mut configs, &path, loaded); + + assert_eq!(returned, cached); + assert_eq!(configs.get(&path).unwrap().0, cached); + } + + #[test] + fn concurrent_update() { + let dir = tempdir().unwrap(); + let path = dir.path().join(WALLET_CONFIG_FILE_NAME); + let mut config = GlobalWalletConfig::for_chain(&ChainTypes::AutomatedTesting, &path); + config.write_to_path(&path, false, None, None).unwrap(); + let barrier = Arc::new(Barrier::new(2)); + + let handles = [false, true].map(|update_tor| { + let path = path.clone(); + let barrier = barrier.clone(); + thread::spawn(move || { + barrier.wait(); + update_global_config(&path, |config| { + if update_tor { + config.members.tor.as_mut().unwrap().socks_proxy_addr = + "127.0.0.1:59051".into(); + } else { + config.members.wallet.api_listen_port = 3416; + } + Ok(()) + }) + .unwrap(); + }) + }); + for handle in handles { + handle.join().unwrap(); + } + + let stored = GlobalWalletConfig::new(path.clone()).unwrap(); + let cached = get_global_config(&path).unwrap(); + assert_eq!(cached, stored); + assert_eq!(stored.members.wallet.api_listen_port, 3416); + assert_eq!(stored.tor_config().socks_proxy_addr, "127.0.0.1:59051"); } } diff --git a/config/src/types.rs b/config/src/types.rs index f7266f0..aff6687 100644 --- a/config/src/types.rs +++ b/config/src/types.rs @@ -14,12 +14,12 @@ //! Public types for config modules +use crate::core::global::ChainTypes; +use crate::util::logger::LoggingConfig; use std::fmt; use std::io; use std::path::PathBuf; - -use crate::core::global::ChainTypes; -use crate::util::logger::LoggingConfig; +use std::time::Duration; /// Command-line wallet configuration #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -40,6 +40,8 @@ pub struct WalletConfig { /// The api address of a running server node against which transaction inputs /// will be checked during send pub check_node_api_http_addr: String, + /// Request timeout for requests to node API. + pub node_api_request_timeout_secs: Option, /// Whether to include foreign API endpoints on the Owner API pub owner_api_include_foreign: Option, /// The directory in which wallet files are stored @@ -69,6 +71,7 @@ impl Default for WalletConfig { api_secret_path: Some(".owner_api_secret".to_string()), node_api_secret_path: Some(".foreign_api_secret".to_string()), check_node_api_http_addr: "http://127.0.0.1:3413".to_string(), + node_api_request_timeout_secs: Some(Self::NODE_API_REQUEST_TIMEOUT_SECS), owner_api_include_foreign: Some(false), data_file_dir: ".".to_string(), no_commit_cache: Some(false), @@ -81,6 +84,9 @@ impl Default for WalletConfig { } impl WalletConfig { + /// Default Node API request timeout in seconds. + pub const NODE_API_REQUEST_TIMEOUT_SECS: u64 = 60; + /// API Listen address pub fn api_listen_addr(&self) -> String { format!("127.0.0.1:{}", self.api_listen_port) @@ -128,6 +134,15 @@ impl WalletConfig { self.accept_fee_base .unwrap_or_else(|| WalletConfig::default_accept_fee_base()) } + + /// Node API requests timeout. + pub fn api_request_timeout(&self) -> Duration { + Duration::from_secs( + self.node_api_request_timeout_secs + .filter(|s| *s > 0) + .unwrap_or(Self::NODE_API_REQUEST_TIMEOUT_SECS), + ) + } } /// Error type wrapping config errors. #[derive(Debug)] @@ -182,18 +197,24 @@ impl From for ConfigError { /// Tor configuration #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct TorConfig { - /// whether to skip any attempts to send via TOR + /// whether to use integrated Tor library + pub use_integrated: Option, + /// whether to skip any attempts to send via Tor pub skip_send_attempt: Option, - /// Whether to start tor listener on listener startup (default true) + /// Whether to start Tor listener on listener startup (default true) pub use_tor_listener: bool, /// Just the address of the socks proxy for now pub socks_proxy_addr: String, /// Send configuration directory pub send_config_dir: String, - /// tor bridge config + /// Total timeout for request in seconds. + pub request_timeout_secs: Option, + /// Timeout for bootstrap in seconds. + pub bootstrap_timeout_secs: Option, + /// Tor bridge config #[serde(default)] pub bridge: TorBridgeConfig, - /// tor proxy config + /// Tor proxy config #[serde(default)] pub proxy: TorProxyConfig, } @@ -201,19 +222,57 @@ pub struct TorConfig { impl Default for TorConfig { fn default() -> TorConfig { TorConfig { + use_integrated: Some(true), skip_send_attempt: Some(false), use_tor_listener: true, socks_proxy_addr: "127.0.0.1:59050".to_owned(), send_config_dir: ".".into(), + request_timeout_secs: Some(Self::REQUEST_TIMEOUT_SECS), + bootstrap_timeout_secs: Some(Self::BOOTSTRAP_TIMEOUT_SECS), bridge: TorBridgeConfig::default(), proxy: TorProxyConfig::default(), } } } +impl TorConfig { + /// Tor request timeout in seconds. + const REQUEST_TIMEOUT_SECS: u64 = 60; + /// Tor bootstrap timeout in seconds. + const BOOTSTRAP_TIMEOUT_SECS: u64 = 60; + + /// Check if attempt to send over Tor is needed using provided possible argument at priority. + pub fn send_tor(&self, skip_arg: Option) -> bool { + if let Some(skip_tor) = skip_arg { + return !skip_tor; + } + !self.skip_send_attempt.unwrap_or(false) + } + + /// Request timeout. + pub fn request_timeout(&self) -> Duration { + Duration::from_secs( + self.request_timeout_secs + .filter(|s| *s > 0) + .unwrap_or(Self::REQUEST_TIMEOUT_SECS), + ) + } + + /// Bootstrap timeout. + pub fn bootstrap_timeout(&self) -> Duration { + Duration::from_secs( + self.bootstrap_timeout_secs + .filter(|s| *s > 0) + .unwrap_or(Self::BOOTSTRAP_TIMEOUT_SECS), + ) + } +} + /// Tor Bridge Config #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct TorBridgeConfig { + /// Path to bridge binary to use with integrated Tor library + pub bridge_bin_path: Option, /// Bridge Line pub bridge_line: Option, /// Client Option @@ -223,6 +282,7 @@ pub struct TorBridgeConfig { impl Default for TorBridgeConfig { fn default() -> TorBridgeConfig { TorBridgeConfig { + bridge_bin_path: None, bridge_line: None, client_option: None, } @@ -272,9 +332,9 @@ impl fmt::Display for TorProxyConfig { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct GlobalWalletConfig { /// Keep track of the file we've read - pub config_file_path: Option, + pub config_file_path: PathBuf, /// Wallet members - pub members: Option, + pub members: GlobalWalletConfigMembers, } /// Wallet internal members diff --git a/controller/Cargo.toml b/controller/Cargo.toml index 3425119..32e03bc 100644 --- a/controller/Cargo.toml +++ b/controller/Cargo.toml @@ -1,74 +1,45 @@ [package] name = "grin_wallet_controller" -version = "5.4.0-alpha.1" +version = "5.4.1" authors = ["Grin Developers "] description = "Controllers for grin wallet instantiation" license = "Apache-2.0" repository = "https://github.com/mimblewimble/grin-wallet" keywords = [ "crypto", "grin", "mimblewimble" ] exclude = ["**/*.grin", "**/*.grin2"] -#build = "src/build/build.rs" edition = "2021" [dependencies] -futures = "0.3" -hyper = "0.14" +tokio = { version = "1", features = ["sync"] } +hyper = { version = "1.10.1", features = ["full"] } +http-body-util = "0.1.3" rand = "0.7" serde = "1" -serde_derive = "1" serde_json = "1" log = "0.4" prettytable-rs = "0.10" -ring = "0.16" term = "0.6" -tokio = { version = "0.2", features = ["full"] } -uuid = { version = "0.8", features = ["serde", "v4"] } -url = "2.1" -chrono = { version = "0.4.11", features = ["serde"] } +uuid = { version = "1.23.4", features = ["serde", "v4"] } easy-jsonrpc-mw = "0.5.4" lazy_static = "1" thiserror = "1" qr_code = "1.1.0" -grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" } -grin_wallet_api = { path = "../api", version = "5.4.0-alpha.1" } -grin_wallet_impls = { path = "../impls", version = "5.4.0-alpha.1" } -grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-alpha.1" } -grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" } +grin_wallet_util = { path = "../util", version = "5.4.1" } +grin_wallet_api = { path = "../api", version = "5.4.1" } +grin_wallet_impls = { path = "../impls", version = "5.4.1" } +grin_wallet_libwallet = { path = "../libwallet", version = "5.4.1" } +grin_wallet_config = { path = "../config", version = "5.4.1" } ##### Grin Imports -# For Release -#grin_core = "5.4.0" -#grin_keychain = "5.4.0" -#grin_util = "5.4.0" -#grin_api = "5.4.0" -#grin_chain = "5.4.0" - -# For beta release - -# grin_core = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3"} -# grin_keychain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_api = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_chain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } - -# For bleeding edge -grin_core = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_keychain = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_util = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_api = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_chain = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } - -# For local testing -# grin_core = { path = "../../grin/core"} -# grin_keychain = { path = "../../grin/keychain"} -# grin_util = { path = "../../grin/util"} -# grin_api = { path = "../../grin/api"} -# grin_chain = { path = "../../grin/chain"} +grin_core = { path = "../grin/core"} +grin_keychain = { path = "../grin/keychain"} +grin_util = { path = "../grin/util"} +grin_api = { path = "../grin/api"} +grin_chain = { path = "../grin/chain"} ##### [dev-dependencies] -ed25519-dalek = "1.0.0-pre.4" -remove_dir_all = "0.7" +ed25519-dalek = "2" \ No newline at end of file diff --git a/controller/src/command.rs b/controller/src/command.rs index 8fb4541..8da1a8f 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -22,18 +22,19 @@ use crate::impls::PathToSlatepack; use crate::impls::SlateGetter as _; use crate::keychain; use crate::libwallet::api_impl::owner; +use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::contract::can_finalize; use crate::libwallet::contract::types::{ ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI, OutputSelectionArgs, }; use crate::libwallet::{ - self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateState, Slatepack, + self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateState, SlatepackAddress, Slatepacker, SlatepackerArgs, WalletLCProvider, }; use crate::util::secp::key::SecretKey; use crate::util::{Mutex, ZeroingString}; use crate::{controller, display}; -use ::core::time; + use qr_code::QrCode; use serde::{Deserialize, Serialize}; use serde_json as json; @@ -135,15 +136,12 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let rewind_hash = api.get_rewind_hash(m)?; - println!(); - println!("Wallet Rewind Hash"); - println!("-------------------------------------"); - println!("{}", rewind_hash); - println!(); - Ok(()) - })?; + let rewind_hash = owner_api.get_rewind_hash(keychain_mask)?; + println!(); + println!("Wallet Rewind Hash"); + println!("-------------------------------------"); + println!("{}", rewind_hash); + println!(); Ok(()) } @@ -164,50 +162,41 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - controller::owner_single_use(None, None, Some(owner_api), |api, m| { - let rewind_hash = args.rewind_hash; - let tip_height = api.node_height(m)?.height; - let start_height = match args.backwards_from_tip { - Some(b) => tip_height.saturating_sub(b), - None => match args.start_height { - Some(s) => s, - None => 1, - }, - }; - warn!( - "Starting view wallet output scan from height {} ...", - start_height - ); - let result = api.scan_rewind_hash(rewind_hash, Some(start_height)); - let deci_sec = time::Duration::from_millis(100); - thread::sleep(deci_sec); - match result { - Ok(res) => { - warn!("View wallet check complete"); - if res.total_balance != 0 { - display::view_wallet_output(res.clone(), tip_height, dark_scheme)?; - } - display::view_wallet_balance(res.clone(), tip_height, dark_scheme); - Ok(()) - } - Err(e) => { - error!("View wallet check failed: {}", e); - Err(e) + let rewind_hash = args.rewind_hash; + let tip_height = owner_api.node_height(None)?.height; + let start_height = match args.backwards_from_tip { + Some(b) => tip_height.saturating_sub(b), + None => args.start_height.unwrap_or_else(|| 1), + }; + warn!( + "Starting view wallet output scan from height {} ...", + start_height + ); + let result = owner_api.scan_rewind_hash(rewind_hash, Some(start_height)); + let deci_sec = Duration::from_millis(100); + thread::sleep(deci_sec); + match result { + Ok(res) => { + warn!("View wallet check complete"); + if res.total_balance != 0 { + display::view_wallet_output(res.clone(), tip_height, dark_scheme)?; } + display::view_wallet_balance(res.clone(), tip_height, dark_scheme); + Ok(()) } - })?; - Ok(()) + Err(e) => { + error!("View wallet check failed: {}", e); + Err(Error::from(e)) + } + } } -/// Arguments for listen command -pub struct ListenArgs {} - pub fn listen( owner_api: &mut Owner, keychain_mask: Arc>>, - config: &WalletConfig, - tor_config: &TorConfig, - _args: &ListenArgs, + config: WalletConfig, + bridge: Option, + use_tor: Option, g_args: &GlobalArgs, cli_mode: bool, test_mode: bool, @@ -218,20 +207,20 @@ where K: keychain::Keychain + 'static, { let wallet_inst = owner_api.wallet_inst.clone(); - let config = config.clone(); - let tor_config = tor_config.clone(); + let config_path = owner_api.config_path(); let g_args = g_args.clone(); let api_thread = thread::Builder::new() .name("wallet-http-listener".to_string()) .spawn(move || { let res = controller::foreign_listener( wallet_inst, + config_path, + bridge, + use_tor, keychain_mask, &config.api_listen_addr(), g_args.tls_conf.clone(), - tor_config.use_tor_listener, test_mode, - Some(tor_config.clone()), ); if let Err(e) = res { error!("Error starting listener: {}", e); @@ -253,7 +242,6 @@ pub fn owner_api( owner_api: &mut Owner, keychain_mask: Option, config: &WalletConfig, - tor_config: &TorConfig, g_args: &GlobalArgs, test_mode: bool, ) -> Result<(), Error> @@ -266,13 +254,12 @@ where // also being run at the same time let km = Arc::new(Mutex::new(keychain_mask)); let res = controller::owner_listener( - owner_api.wallet_inst.clone(), + owner_api, km, config.owner_api_listen_addr().as_str(), g_args.api_secret.clone(), g_args.tls_conf.clone(), config.owner_api_include_foreign, - Some(tor_config.clone()), test_mode, ); if let Err(e) = res { @@ -297,25 +284,25 @@ where K: keychain::Keychain + 'static, { if args.create.is_none() { - let res = controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let acct_mappings = api.accounts(m)?; + let res = { + let acct_mappings = owner_api.accounts(keychain_mask)?; // give logging thread a moment to catch up thread::sleep(Duration::from_millis(200)); display::accounts(acct_mappings); Ok(()) - }); + }; if let Err(e) = res { error!("Error listing accounts: {}", e); return Err(Error::LibWallet(e)); } } else { let label = args.create.unwrap(); - let res = controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - api.create_account_path(m, &label)?; + let res = { + owner_api.create_account_path(keychain_mask, &label)?; thread::sleep(Duration::from_millis(200)); info!("Account: '{}' Created!", label); Ok(()) - }); + }; if let Err(e) = res { thread::sleep(Duration::from_millis(200)); error!("Error creating account '{}': {}", label, e); @@ -342,7 +329,7 @@ pub struct SendArgs { pub target_slate_version: Option, pub payment_proof_address: Option, pub ttl_blocks: Option, - pub skip_tor: bool, + pub skip_tor: Option, pub outfile: Option, pub bridge: Option, pub slatepack_qr: bool, @@ -351,8 +338,8 @@ pub struct SendArgs { pub fn send( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, - tor_config: Option, args: SendArgs, + mut tor_config: TorConfig, dark_scheme: bool, test_mode: bool, ) -> Result<(), Error> @@ -364,119 +351,111 @@ where let mut slate = Slate::blank(2, false); let mut amount = args.amount; if args.use_max_amount { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let (_, wallet_info) = - api.retrieve_summary_info(m, true, args.minimum_confirmations)?; - amount = wallet_info.amount_currently_spendable; - Ok(()) - })?; - }; - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - if args.estimate_selection_strategies { - let strategies = vec!["smallest", "all"] - .into_iter() - .map(|strategy| { - let init_args = InitTxArgs { - src_acct_name: None, - amount: amount, - amount_includes_fee: Some(args.amount_includes_fee), - minimum_confirmations: args.minimum_confirmations, - max_outputs: args.max_outputs as u32, - num_change_outputs: args.change_outputs as u32, - selection_strategy_is_use_all: strategy == "all", - estimate_only: Some(true), - ..Default::default() - }; - let slate = api.init_send_tx(m, init_args)?; - Ok((strategy, slate.amount, slate.fee_fields)) - }) - .collect::, grin_wallet_libwallet::Error>>()?; - display::estimate(amount, strategies, dark_scheme); - return Ok(()); - } else { - let init_args = InitTxArgs { - src_acct_name: None, - amount: amount, - amount_includes_fee: Some(args.amount_includes_fee), - minimum_confirmations: args.minimum_confirmations, - max_outputs: args.max_outputs as u32, - num_change_outputs: args.change_outputs as u32, - selection_strategy_is_use_all: args.selection_strategy == "all", - target_slate_version: args.target_slate_version, - payment_proof_recipient_address: args.payment_proof_address.clone(), - ttl_blocks: args.ttl_blocks, - send_args: None, - late_lock: Some(args.late_lock), - ..Default::default() - }; - let result = api.init_send_tx(m, init_args); - slate = match result { - Ok(s) => { - info!( - "Tx created: {} grin to {} (strategy '{}')", - core::amount_to_hr_string(amount, false), - args.dest, - args.selection_strategy, - ); - s - } - Err(e) => { - info!("Tx not created: {}", e); - return Err(e); - } - }; - } - Ok(()) - })?; + let (_, wallet_info) = + owner_api.retrieve_summary_info(keychain_mask, true, args.minimum_confirmations)?; + amount = wallet_info.amount_currently_spendable; + } + if args.estimate_selection_strategies { + let strategies = vec!["smallest", "all"] + .into_iter() + .map(|strategy| { + let init_args = InitTxArgs { + src_acct_name: None, + amount, + amount_includes_fee: Some(args.amount_includes_fee), + minimum_confirmations: args.minimum_confirmations, + max_outputs: args.max_outputs as u32, + num_change_outputs: args.change_outputs as u32, + selection_strategy_is_use_all: strategy == "all", + estimate_only: Some(true), + ..Default::default() + }; + let slate = owner_api.init_send_tx(keychain_mask, init_args)?; + Ok((strategy, slate.amount, slate.fee_fields)) + }) + .collect::, grin_wallet_libwallet::Error>>()?; + display::estimate(amount, strategies, dark_scheme); + } else { + let init_args = InitTxArgs { + src_acct_name: None, + amount, + amount_includes_fee: Some(args.amount_includes_fee), + minimum_confirmations: args.minimum_confirmations, + max_outputs: args.max_outputs as u32, + num_change_outputs: args.change_outputs as u32, + selection_strategy_is_use_all: args.selection_strategy == "all", + target_slate_version: args.target_slate_version, + payment_proof_recipient_address: args.payment_proof_address.clone(), + ttl_blocks: args.ttl_blocks, + send_args: None, + late_lock: Some(args.late_lock), + ..Default::default() + }; + let result = owner_api.init_send_tx(keychain_mask, init_args); + slate = match result { + Ok(s) => { + info!( + "Tx created: {} grin to {} (strategy '{}')", + core::amount_to_hr_string(amount, false), + args.dest, + args.selection_strategy, + ); + s + } + Err(e) => { + info!("Tx not created: {}", e); + return Err(Error::from(e)); + } + }; + } if args.estimate_selection_strategies { return Ok(()); } - let tor_config = match tor_config { - Some(mut c) => { - if let Some(b) = args.bridge.clone() { - c.bridge.bridge_line = Some(b); - } - c.skip_send_attempt = Some(args.skip_tor); - Some(c) - } - None => None, + if let Some(b) = args.bridge.clone() { + tor_config.bridge.bridge_line = Some(b); + } + + let output_sp = || -> Result<(), Error> { + Ok(output_slatepack( + owner_api, + keychain_mask, + &slate, + args.dest.as_str(), + args.outfile, + true, + false, + args.slatepack_qr, + )?) }; - let res = try_slatepack_sync_workflow(&slate, &args.dest, tor_config, None, false, test_mode); + let can_send = tor_config.send_tor(args.skip_tor); + if test_mode || !can_send { + return output_sp(); + } + + let res = try_slatepack_sync_workflow(&slate, &args.dest, Some(tor_config), None, false); match res { - Ok(Some(s)) => { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - api.tx_lock_outputs(m, &s)?; - let ret_slate = api.finalize_tx(m, &s)?; - let result = api.post_tx(m, &ret_slate, args.fluff); - match result { - Ok(_) => { - println!("Tx sent successfully",); - Ok(()) - } - Err(e) => { - error!("Tx sent fail: {}", e); - Err(e.into()) - } + Ok(s) => { + owner_api.tx_lock_outputs(keychain_mask, &s)?; + let ret_slate = owner_api.finalize_tx(keychain_mask, &s)?; + let result = owner_api.post_tx(keychain_mask, &ret_slate, args.fluff); + match result { + Ok(_) => { + println!("Tx sent successfully",); } - })?; + Err(e) => { + error!("Tx sent fail: {}", e); + return Err(e.into()); + } + } } - Ok(None) => { - output_slatepack( - owner_api, - keychain_mask, - &slate, - args.dest.as_str(), - args.outfile, - true, - false, - args.slatepack_qr, - )?; + Err(e) => { + error!("Error sending slate sync: {}", e); + output_sp()?; } - Err(e) => return Err(e.into()), } Ok(()) } @@ -497,23 +476,17 @@ where K: keychain::Keychain + 'static, { // Output the slatepack file to stdout and to a file - let mut message = String::from(""); - let mut address = None; - let mut tld = String::from(""); - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - address = match SlatepackAddress::try_from(dest) { - Ok(a) => Some(a), - Err(_) => None, - }; - // encrypt for recipient by default - let recipients = match address.clone() { - Some(a) => vec![a], - None => vec![], - }; - message = api.create_slatepack_message(m, &slate, Some(0), recipients)?; - tld = api.get_top_level_directory()?; - Ok(()) - })?; + let address = match SlatepackAddress::try_from(dest) { + Ok(a) => Some(a), + Err(_) => None, + }; + // encrypt for recipient by default + let recipients = match address.clone() { + Some(a) => vec![a], + None => vec![], + }; + let message = owner_api.create_slatepack_message(keychain_mask, &slate, Some(0), recipients)?; + let tld = owner_api.get_top_level_directory()?; // create a directory to which files will be output let slate_dir = format!("{}/{}", tld, "slatepack"); @@ -524,10 +497,7 @@ where }; if lock { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + owner_api.tx_lock_outputs(keychain_mask, &slate)?; } println!("{}", out_file_name); @@ -650,7 +620,9 @@ where let mut message = String::from(""); let mut address = None; let mut tld = String::from(""); - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { + let wallet_inst = owner_api.wallet_inst.clone(); + let config_path = owner_api.config_path(); + controller::owner_single_use(wallet_inst, keychain_mask, config_path, |api, m| { address = match SlatepackAddress::try_from(dest) { Ok(a) => Some(a), Err(_) => None, @@ -716,19 +688,15 @@ where let slate = match filename { Some(f) => { // otherwise, get slate from slatepack - let mut sl = None; - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let dec_key = api.get_slatepack_secret_key(m, 0)?; - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: Some(&dec_key), - }); - let pts = PathToSlatepack::new(f.into(), &packer, true); - sl = Some(pts.get_tx()?.0); - ret_address = pts.get_slatepack(true)?.sender; - Ok(()) - })?; + let dec_key = owner_api.get_slatepack_secret_key(keychain_mask, 0)?; + let packer = Slatepacker::new(SlatepackerArgs { + sender: None, + recipients: vec![], + dec_key: Some(&dec_key), + }); + let pts = PathToSlatepack::new(f.into(), &packer, true); + let sl = Some(pts.get_tx()?.0); + ret_address = pts.get_slatepack(true)?.sender; sl } None => None, @@ -738,29 +706,26 @@ where Some(s) => s, None => { // try and parse directly from input_slatepack_message - let mut slate = Slate::blank(2, false); match message { Some(message) => { - controller::owner_single_use( - None, + let slate = owner_api.slate_from_slatepack_message( keychain_mask, - Some(owner_api), - |api, m| { - slate = - api.slate_from_slatepack_message(m, message.clone(), vec![0])?; - let slatepack = - api.decode_slatepack_message(m, message.clone(), vec![0])?; - ret_address = slatepack.sender; - Ok(()) - }, + message.clone(), + vec![0], )?; + let slatepack = owner_api.decode_slatepack_message( + keychain_mask, + message.clone(), + vec![0], + )?; + ret_address = slatepack.sender; + slate } None => { let msg = "No slate provided via file or direct input"; return Err(Error::GenericError(msg.into()).into()); } } - slate } }; Ok((slate, ret_address)) @@ -771,7 +736,7 @@ where pub struct ReceiveArgs { pub input_file: Option, pub input_slatepack_message: Option, - pub skip_tor: bool, + pub skip_tor: Option, pub outfile: Option, pub bridge: Option, pub slatepack_qr: bool, @@ -782,7 +747,7 @@ pub fn receive( keychain_mask: Option<&SecretKey>, g_args: &GlobalArgs, args: ReceiveArgs, - tor_config: Option, + mut tor_config: TorConfig, test_mode: bool, ) -> Result<(), Error> where @@ -802,54 +767,70 @@ where Some(&m) => Some(m.to_owned()), }; - let tor_config = match tor_config { - Some(mut c) => { - if let Some(b) = args.bridge { - c.bridge.bridge_line = Some(b); - } - c.skip_send_attempt = Some(args.skip_tor); - Some(c) - } - None => None, - }; + if let Some(b) = args.bridge { + tor_config.bridge.bridge_line = Some(b); + } - controller::foreign_single_use(owner_api.wallet_inst.clone(), km, |api| { - slate = api.receive_tx(&slate, Some(&g_args.account), None)?; - Ok(()) - })?; + controller::foreign_single_use( + owner_api.wallet_inst.clone(), + owner_api.config_path(), + km, + |api| { + slate = api.receive_tx(&slate, Some(&g_args.account), None)?; + Ok(()) + }, + )?; let dest = match ret_address { - Some(a) => String::try_from(&a).unwrap(), + Some(a) => String::try_from(&a)?, None => String::from(""), }; - let res = try_slatepack_sync_workflow(&slate, &dest, tor_config, None, true, test_mode); + let output_sp = || -> Result<(), Error> { + Ok(output_slatepack( + owner_api, + keychain_mask, + &slate, + &dest, + args.outfile, + false, + false, + args.slatepack_qr, + )?) + }; + + let can_send = tor_config.send_tor(args.skip_tor); + if test_mode || !can_send { + return output_sp(); + } + + let res = try_slatepack_sync_workflow(&slate, &dest, Some(tor_config), None, true); match res { - Ok(Some(_)) => { + Ok(s) => { + // Update slate state. + { + let mut w_lock = owner_api.wallet_inst.lock(); + let w = w_lock.lc_provider()?.wallet_inst()?; + let parent_key_id = w.parent_key_id(); + match update_tx_slate_state(w, keychain_mask, &parent_key_id, &s) { + Ok(_) => {} + Err(e) => error!("Error on updating slate state: {}", e), + } + } println!(); println!( - "Transaction recieved and sent back to sender at {} for finalization.", + "Transaction received and sent back to sender at {} for finalization.", dest ); println!(); - Ok(()) } - Ok(None) => { - output_slatepack( - owner_api, - keychain_mask, - &slate, - &dest, - args.outfile, - false, - false, - args.slatepack_qr, - )?; - Ok(()) + Err(e) => { + error!("Error sending slate sync: {}", e); + output_sp()?; } - Err(e) => Err(e.into()), } + Ok(()) } pub fn unpack( @@ -872,14 +853,7 @@ where PathToSlatepack::new(f.into(), &packer, true).get_slatepack(false)? } None => match args.input_slatepack_message { - Some(mes) => { - let mut sp = Slatepack::default(); - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - sp = api.decode_slatepack_message(m, mes, vec![])?; - Ok(()) - })?; - sp - } + Some(mes) => owner_api.decode_slatepack_message(keychain_mask, mes, vec![])?, None => { return Err(Error::ArgumentError("Invalid Slatepack Input".into()).into()); } @@ -898,27 +872,24 @@ where }); if slatepack.mode == 1 { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let dec_key = api.get_slatepack_secret_key(m, 0)?; - match slatepack.try_decrypt_payload(Some(&dec_key)) { - Ok(_) => { - println!("Slatepack is encrypted for this wallet"); - println!(); - println!("DECRYPTED SLATEPACK"); - println!("-------------------"); - println!("{}", slatepack); - let slate = packer.get_slate(&slatepack)?; - println!(); - println!("DECRYPTED SLATE"); - println!("---------------"); - println!("{}", slate); - } - Err(_) => { - println!("Slatepack payload cannot be decrypted by this wallet"); - } + let dec_key = owner_api.get_slatepack_secret_key(keychain_mask, 0)?; + match slatepack.try_decrypt_payload(Some(&dec_key)) { + Ok(_) => { + println!("Slatepack is encrypted for this wallet"); + println!(); + println!("DECRYPTED SLATEPACK"); + println!("-------------------"); + println!("{}", slatepack); + let slate = packer.get_slate(&slatepack)?; + println!(); + println!("DECRYPTED SLATE"); + println!("---------------"); + println!("{}", slate); } - Ok(()) - })?; + Err(_) => { + println!("Slatepack payload cannot be decrypted by this wallet"); + } + } } else { let slate = packer.get_slate(&slatepack)?; println!("Slatepack is not encrypted"); @@ -968,34 +939,31 @@ where None => None, Some(&m) => Some(m.to_owned()), }; - controller::foreign_single_use(owner_api.wallet_inst.clone(), km, |api| { - slate = api.finalize_tx(&slate, false)?; - Ok(()) - })?; + controller::foreign_single_use( + owner_api.wallet_inst.clone(), + owner_api.config_path(), + km, + |api| { + slate = api.finalize_tx(&slate, false)?; + Ok(()) + }, + )?; } else { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - slate = api.finalize_tx(m, &slate)?; - Ok(()) - })?; + slate = owner_api.finalize_tx(keychain_mask, &slate)? } if !&args.nopost { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let result = api.post_tx(m, &slate, args.fluff); - match result { - Ok(_) => { - info!( - "Transaction sent successfully, check the wallet again for confirmation." - ); - println!("Transaction posted"); - Ok(()) - } - Err(e) => { - error!("Tx not sent: {}", e); - Err(e) - } + let result = owner_api.post_tx(keychain_mask, &slate, args.fluff); + match result { + Ok(_) => { + info!("Transaction sent successfully, check the wallet again for confirmation."); + println!("Transaction posted"); } - })?; + Err(e) => { + error!("Tx not sent: {}", e); + return Err(Error::from(e)); + } + } } println!("Transaction finalized successfully"); @@ -1038,11 +1006,7 @@ where { let issue_args = args.issue_args.clone(); - let mut slate = Slate::blank(2, false); - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - slate = api.issue_invoice_tx(m, issue_args)?; - Ok(()) - })?; + let slate = owner_api.issue_invoice_tx(keychain_mask, issue_args)?; output_slatepack( owner_api, @@ -1066,7 +1030,7 @@ pub struct ProcessInvoiceArgs { pub slate: Slate, pub estimate_selection_strategies: bool, pub ttl_blocks: Option, - pub skip_tor: bool, + pub skip_tor: Option, pub outfile: Option, pub bridge: Option, pub slatepack_qr: bool, @@ -1076,7 +1040,7 @@ pub struct ProcessInvoiceArgs { pub fn process_invoice( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, - tor_config: Option, + mut tor_config: TorConfig, args: ProcessInvoiceArgs, dark_scheme: bool, test_mode: bool, @@ -1088,100 +1052,107 @@ where { let mut slate = args.slate.clone(); let dest = match args.ret_address.clone() { - Some(a) => String::try_from(&a).unwrap(), + Some(a) => String::try_from(&a)?, None => String::from(""), }; - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - if args.estimate_selection_strategies { - let strategies = vec!["smallest", "all"] - .into_iter() - .map(|strategy| { - let init_args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: args.minimum_confirmations, - max_outputs: args.max_outputs as u32, - num_change_outputs: 1u32, - selection_strategy_is_use_all: strategy == "all", - estimate_only: Some(true), - ..Default::default() - }; - let slate = api.init_send_tx(m, init_args).unwrap(); - (strategy, slate.amount, slate.fee_fields) - }) - .collect(); - display::estimate(slate.amount, strategies, dark_scheme); - return Ok(()); - } else { - let init_args = InitTxArgs { - src_acct_name: None, - amount: 0, - minimum_confirmations: args.minimum_confirmations, - max_outputs: args.max_outputs as u32, - num_change_outputs: 1u32, - selection_strategy_is_use_all: args.selection_strategy == "all", - ttl_blocks: args.ttl_blocks, - send_args: None, - ..Default::default() - }; - let result = api.process_invoice_tx(m, &slate, init_args); - slate = match result { - Ok(s) => { - info!( - "Invoice processed: {} grin (strategy '{}')", - core::amount_to_hr_string(slate.amount, false), - args.selection_strategy, - ); - s - } - Err(e) => { - info!("Tx not created: {}", e); - return Err(e); - } - }; - } - Ok(()) - })?; - - let tor_config = match tor_config { - Some(mut c) => { - if let Some(b) = args.bridge { - c.bridge.bridge_line = Some(b); + if args.estimate_selection_strategies { + let strategies = vec!["smallest", "all"] + .into_iter() + .map(|strategy| { + let init_args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: args.minimum_confirmations, + max_outputs: args.max_outputs as u32, + num_change_outputs: 1u32, + selection_strategy_is_use_all: strategy == "all", + estimate_only: Some(true), + ..Default::default() + }; + let slate = owner_api.init_send_tx(keychain_mask, init_args).unwrap(); + (strategy, slate.amount, slate.fee_fields) + }) + .collect(); + display::estimate(slate.amount, strategies, dark_scheme); + } else { + let init_args = InitTxArgs { + src_acct_name: None, + amount: 0, + minimum_confirmations: args.minimum_confirmations, + max_outputs: args.max_outputs as u32, + num_change_outputs: 1u32, + selection_strategy_is_use_all: args.selection_strategy == "all", + ttl_blocks: args.ttl_blocks, + send_args: None, + ..Default::default() + }; + let result = owner_api.process_invoice_tx(keychain_mask, &slate, init_args); + slate = match result { + Ok(s) => { + info!( + "Invoice processed: {} grin (strategy '{}')", + core::amount_to_hr_string(slate.amount, false), + args.selection_strategy, + ); + s } - c.skip_send_attempt = Some(args.skip_tor); - Some(c) - } - None => None, + Err(e) => { + info!("Tx not created: {}", e); + return Err(Error::from(e)); + } + }; + } + + if let Some(b) = args.bridge { + tor_config.bridge.bridge_line = Some(b); + } + + let output_sp = || -> Result<(), Error> { + Ok(output_slatepack( + owner_api, + keychain_mask, + &slate, + &dest, + args.outfile, + true, + false, + args.slatepack_qr, + )?) }; - let res = try_slatepack_sync_workflow(&slate, &dest, tor_config, None, true, test_mode); + let can_send = tor_config.send_tor(args.skip_tor); + if test_mode || !can_send { + return output_sp(); + } + + let res = try_slatepack_sync_workflow(&slate, &dest, Some(tor_config), None, true); match res { - Ok(Some(_)) => { + Ok(s) => { + // Update slate state. + { + let mut w_lock = owner_api.wallet_inst.lock(); + let w = w_lock.lc_provider()?.wallet_inst()?; + let parent_key_id = w.parent_key_id(); + match update_tx_slate_state(w, keychain_mask, &parent_key_id, &s) { + Ok(_) => {} + Err(e) => error!("Error on updating slate state: {}", e), + } + } println!(); println!( "Transaction paid and sent back to initiator at {} for finalization.", dest ); println!(); - Ok(()) } - Ok(None) => { - output_slatepack( - owner_api, - keychain_mask, - &slate, - &dest, - args.outfile, - true, - false, - args.slatepack_qr, - )?; - Ok(()) + Err(e) => { + error!("Error sending slate sync: {}", e); + output_sp()?; } - Err(e) => Err(e.into()), } + Ok(()) } /// Info command args @@ -1202,17 +1173,14 @@ where K: keychain::Keychain + 'static, { let updater_running = owner_api.updater_running.load(Ordering::Relaxed); - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let (validated, wallet_info) = - api.retrieve_summary_info(m, true, args.minimum_confirmations)?; - display::info( - &g_args.account, - &wallet_info, - validated || updater_running, - dark_scheme, - ); - Ok(()) - })?; + let (validated, wallet_info) = + owner_api.retrieve_summary_info(keychain_mask, true, args.minimum_confirmations)?; + display::info( + &g_args.account, + &wallet_info, + validated || updater_running, + dark_scheme, + ); Ok(()) } @@ -1228,18 +1196,16 @@ where K: keychain::Keychain + 'static, { let updater_running = owner_api.updater_running.load(Ordering::Relaxed); - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let res = api.node_height(m)?; - let (validated, outputs) = api.retrieve_outputs(m, g_args.show_spent, true, None)?; - display::outputs( - &g_args.account, - res.height, - validated || updater_running, - outputs, - dark_scheme, - )?; - Ok(()) - })?; + let res = owner_api.node_height(keychain_mask)?; + let (validated, outputs) = + owner_api.retrieve_outputs(keychain_mask, g_args.show_spent, true, None)?; + display::outputs( + &g_args.account, + res.height, + validated || updater_running, + outputs, + dark_scheme, + )?; Ok(()) } @@ -1263,56 +1229,53 @@ where K: keychain::Keychain + 'static, { let updater_running = owner_api.updater_running.load(Ordering::Relaxed); - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let res = api.node_height(m)?; - // Note advanced query args not currently supported by command line client - let (validated, txs) = api.retrieve_txs(m, true, args.id, args.tx_slate_id, None)?; - let include_status = !args.id.is_some() && !args.tx_slate_id.is_some(); - // If view count is specified, restrict the TX list to `txs.len() - count` - let first_tx = args - .count - .map_or(0, |c| txs.len().saturating_sub(c as usize)); - display::txs( + let res = owner_api.node_height(keychain_mask)?; + // Note advanced query args not currently supported by command line client + let (validated, txs) = + owner_api.retrieve_txs(keychain_mask, true, args.id, args.tx_slate_id, None)?; + let include_status = !args.id.is_some() && !args.tx_slate_id.is_some(); + // If view count is specified, restrict the TX list to `txs.len() - count` + let first_tx = args + .count + .map_or(0, |c| txs.len().saturating_sub(c as usize)); + display::txs( + &g_args.account, + res.height, + validated || updater_running, + &txs[first_tx..], + include_status, + dark_scheme, + )?; + + // if given a particular transaction id or uuid, also get and display associated + // inputs/outputs and messages + let id = if args.id.is_some() { + args.id + } else if args.tx_slate_id.is_some() { + if let Some(tx) = txs.iter().find(|t| t.tx_slate_id == args.tx_slate_id) { + Some(tx.id) + } else { + println!("Could not find a transaction matching given txid.\n"); + None + } + } else { + None + }; + + if id.is_some() { + let (_, outputs) = owner_api.retrieve_outputs(keychain_mask, true, false, id)?; + display::outputs( &g_args.account, res.height, validated || updater_running, - &txs[first_tx..], - include_status, + outputs, dark_scheme, )?; - - // if given a particular transaction id or uuid, also get and display associated - // inputs/outputs and messages - let id = if args.id.is_some() { - args.id - } else if args.tx_slate_id.is_some() { - if let Some(tx) = txs.iter().find(|t| t.tx_slate_id == args.tx_slate_id) { - Some(tx.id) - } else { - println!("Could not find a transaction matching given txid.\n"); - None - } - } else { - None - }; - - if id.is_some() { - let (_, outputs) = api.retrieve_outputs(m, true, false, id)?; - display::outputs( - &g_args.account, - res.height, - validated || updater_running, - outputs, - dark_scheme, - )?; - // should only be one here, but just in case - for tx in txs { - display::payment_proof(&tx)?; - } + // should only be one here, but just in case + for tx in txs { + display::payment_proof(&tx)?; } - - Ok(()) - })?; + } Ok(()) } @@ -1342,11 +1305,8 @@ where )?; let fluff = args.fluff; - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - api.post_tx(m, &slate, fluff)?; - info!("Posted transaction"); - return Ok(()); - })?; + owner_api.post_tx(keychain_mask, &slate, fluff)?; + info!("Posted transaction"); Ok(()) } @@ -1367,53 +1327,55 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let stored_tx_slate = match api.get_stored_tx(m, Some(args.id), None)? { - None => { + let stored_tx_slate = match owner_api.get_stored_tx(keychain_mask, Some(args.id), None)? { + None => { + error!( + "Transaction with id {} does not have transaction data. Not reposting.", + args.id + ); + return Ok(()); + } + Some(s) => s, + }; + let (_, txs) = owner_api.retrieve_txs(keychain_mask, true, Some(args.id), None, None)?; + match args.dump_file { + None => { + if txs[0].confirmed { error!( - "Transaction with id {} does not have transaction data. Not reposting.", + "Transaction with id {} is confirmed. Not reposting.", args.id ); return Ok(()); } - Some(s) => s, - }; - let (_, txs) = api.retrieve_txs(m, true, Some(args.id), None, None)?; - match args.dump_file { - None => { - if txs[0].confirmed { - error!( - "Transaction with id {} is confirmed. Not reposting.", - args.id - ); - return Ok(()); - } - if libwallet::sig_is_blank( - &stored_tx_slate.tx.as_ref().unwrap().kernels()[0].excess_sig, - ) { - error!("Transaction at {} has not been finalized.", args.id); - return Ok(()); - } - - match api.post_tx(m, &stored_tx_slate, args.fluff) { - Ok(_) => info!("Reposted transaction at {}", args.id), - Err(e) => error!("Could not repost transaction at {}. Reason: {}", args.id, e), - } + if libwallet::sig_is_blank( + &stored_tx_slate.tx.as_ref().unwrap().kernels()[0].excess_sig, + ) { + error!("Transaction at {} has not been finalized.", args.id); return Ok(()); } - Some(f) => { - let mut tx_file = File::create(f.clone())?; - tx_file.write_all( + + match owner_api.post_tx(keychain_mask, &stored_tx_slate, args.fluff) { + Ok(_) => info!("Reposted transaction at {}", args.id), + Err(e) => error!("Could not repost transaction at {}. Reason: {}", args.id, e), + } + return Ok(()); + } + Some(f) => { + let mut tx_file = + File::create(f.clone()).map_err(|e| Error::GenericError(format!("{}", e)))?; + tx_file + .write_all( json::to_string(&stored_tx_slate.tx.unwrap()) .unwrap() .as_bytes(), - )?; - tx_file.sync_all()?; - info!("Dumped transaction data for tx {} to {}", args.id, f); - return Ok(()); - } + ) + .map_err(|e| Error::GenericError(format!("{}", e)))?; + tx_file + .sync_all() + .map_err(|e| Error::GenericError(format!("{}", e)))?; + info!("Dumped transaction data for tx {} to {}", args.id, f); } - })?; + } Ok(()) } @@ -1434,20 +1396,17 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let result = api.cancel_tx(m, args.tx_id, args.tx_slate_id); - match result { - Ok(_) => { - info!("Transaction {} Cancelled", args.tx_id_string); - Ok(()) - } - Err(e) => { - error!("TX Cancellation failed: {}", e); - Err(e) - } + let result = owner_api.cancel_tx(keychain_mask, args.tx_id, args.tx_slate_id); + match result { + Ok(_) => { + info!("Transaction {} Cancelled", args.tx_id_string); + Ok(()) } - })?; - Ok(()) + Err(e) => { + error!("TX Cancellation failed: {}", e); + Err(Error::from(e)) + } + } } /// wallet check @@ -1467,29 +1426,23 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let tip_height = api.node_height(m)?.height; - let start_height = match args.backwards_from_tip { - Some(b) => tip_height.saturating_sub(b), - None => match args.start_height { - Some(s) => s, - None => 1, - }, - }; - warn!("Starting output scan from height {} ...", start_height); - let result = api.scan(m, Some(start_height), args.delete_unconfirmed); - match result { - Ok(_) => { - warn!("Wallet check complete",); - Ok(()) - } - Err(e) => { - error!("Wallet check failed: {}", e); - Err(e) - } + let tip_height = owner_api.node_height(keychain_mask)?.height; + let start_height = match args.backwards_from_tip { + Some(b) => tip_height.saturating_sub(b), + None => args.start_height.unwrap_or_else(|| 1), + }; + warn!("Starting output scan from height {} ...", start_height); + let result = owner_api.scan(keychain_mask, Some(start_height), args.delete_unconfirmed); + match result { + Ok(_) => { + warn!("Wallet check complete",); + Ok(()) } - })?; - Ok(()) + Err(e) => { + error!("Wallet check failed: {}", e); + Err(Error::from(e)) + } + } } /// Payment Proof Address @@ -1503,16 +1456,13 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - // Just address at derivation index 0 for now - let address = api.get_slatepack_address(m, 0)?; - println!(); - println!("Address for account - {}", g_args.account); - println!("-------------------------------------"); - println!("{}", address); - println!(); - Ok(()) - })?; + // Just address at derivation index 0 for now + let address = owner_api.get_slatepack_address(keychain_mask, 0)?; + println!(); + println!("Address for account - {}", g_args.account); + println!("-------------------------------------"); + println!("{}", address); + println!(); Ok(()) } @@ -1533,24 +1483,26 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let result = api.retrieve_payment_proof(m, true, args.id, args.tx_slate_id); - match result { - Ok(p) => { - // actually export proof - let mut proof_file = File::create(args.output_file.clone())?; - proof_file.write_all(json::to_string_pretty(&p).unwrap().as_bytes())?; - proof_file.sync_all()?; - warn!("Payment proof exported to {}", args.output_file); - Ok(()) - } - Err(e) => { - error!("Proof export failed: {}", e); - Err(e) - } + let result = owner_api.retrieve_payment_proof(keychain_mask, true, args.id, args.tx_slate_id); + match result { + Ok(p) => { + // actually export proof + let mut proof_file = File::create(args.output_file.clone()) + .map_err(|e| Error::GenericError(format!("{}", e)))?; + proof_file + .write_all(json::to_string_pretty(&p).unwrap().as_bytes()) + .map_err(|e| Error::GenericError(format!("{}", e)))?; + proof_file + .sync_all() + .map_err(|e| Error::GenericError(format!("{}", e)))?; + warn!("Payment proof exported to {}", args.output_file); + Ok(()) } - })?; - Ok(()) + Err(e) => { + error!("Proof export failed: {}", e); + Err(Error::from(e)) + } + } } /// Proof Verify Args @@ -1568,53 +1520,52 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { - let mut proof_f = match File::open(&args.input_file) { - Ok(p) => p, - Err(e) => { - let msg = format!("{}", e); - error!( - "Unable to open payment proof file at {}: {}", - args.input_file, e - ); - return Err(libwallet::Error::PaymentProofParsing(msg)); - } - }; - let mut proof = String::new(); - proof_f.read_to_string(&mut proof)?; - // read - let proof: PaymentProof = match json::from_str(&proof) { - Ok(p) => p, - Err(e) => { - let msg = format!("{}", e); - error!("Unable to parse payment proof file: {}", e); - return Err(libwallet::Error::PaymentProofParsing(msg)); - } - }; - let result = api.verify_payment_proof(m, &proof); - match result { - Ok((iam_sender, iam_recipient)) => { - println!("Payment proof's signatures are valid."); - if iam_sender { - println!("The proof's sender address belongs to this wallet."); - } - if iam_recipient { - println!("The proof's recipient address belongs to this wallet."); - } - if !iam_recipient && !iam_sender { - println!( - "Neither the proof's sender nor recipient address belongs to this wallet." - ); - } - Ok(()) - } - Err(e) => { - error!("Proof not valid: {}", e); - Err(e) - } + let mut proof_f = match File::open(&args.input_file) { + Ok(p) => p, + Err(e) => { + let msg = format!("{}", e); + error!( + "Unable to open payment proof file at {}: {}", + args.input_file, e + ); + return Err(Error::from(libwallet::Error::PaymentProofParsing(msg))); } - })?; - Ok(()) + }; + let mut proof = String::new(); + proof_f + .read_to_string(&mut proof) + .map_err(|e| Error::GenericError(format!("{}", e)))?; + // read + let proof: PaymentProof = match json::from_str(&proof) { + Ok(p) => p, + Err(e) => { + let msg = format!("{}", e); + error!("Unable to parse payment proof file: {}", e); + return Err(Error::from(libwallet::Error::PaymentProofParsing(msg))); + } + }; + let result = owner_api.verify_payment_proof(keychain_mask, &proof); + match result { + Ok((iam_sender, iam_recipient)) => { + println!("Payment proof's signatures are valid."); + if iam_sender { + println!("The proof's sender address belongs to this wallet."); + } + if iam_recipient { + println!("The proof's recipient address belongs to this wallet."); + } + if !iam_recipient && !iam_sender { + println!( + "Neither the proof's sender nor recipient address belongs to this wallet." + ); + } + Ok(()) + } + Err(e) => { + error!("Proof not valid: {}", e); + Err(Error::from(e)) + } + } } /// Create new contract command arguments @@ -1655,7 +1606,9 @@ impl ContractNewArgs { }; match self.receive { None => match self.send { - None => Err(Error::ArgumentError("Send or receive not specified.".into())), + None => Err(Error::ArgumentError( + "Send or receive not specified.".into(), + )), Some(v) => Ok(-to_i64(v)?), // negative net change on send }, Some(v) => to_i64(v), // positive net change on receive @@ -1700,7 +1653,9 @@ where K: keychain::Keychain + 'static, { let contract_new_args = args.to_api_args()?; - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { + let wallet_inst = owner_api.wallet_inst.clone(); + let config_path = owner_api.config_path(); + controller::owner_single_use(wallet_inst, keychain_mask, config_path, |api, m| { let slate = api.contract_new(m, &contract_new_args)?; print_slatepack( @@ -1797,7 +1752,9 @@ where { // Args for signing are just setup args let contract_sign_args = args.to_api_args()?; - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { + let wallet_inst = owner_api.wallet_inst.clone(); + let config_path = owner_api.config_path(); + controller::owner_single_use(wallet_inst, keychain_mask, config_path, |api, m| { // Read the slatepack from stdin println!("Paste slatepack:"); let mut slatepack_msg = String::new(); @@ -1871,7 +1828,9 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { + let wallet_inst = owner_api.wallet_inst.clone(); + let config_path = owner_api.config_path(); + controller::owner_single_use(wallet_inst, keychain_mask, config_path, |api, m| { let slate_opt = api.contract_revoke(m, &ContractRevokeArgsAPI { tx_id: args.tx_id })?; // TODO: replace dest="nope" with our own address and add --as-json support if slate_opt.is_some() { diff --git a/controller/src/controller.rs b/controller/src/controller.rs index 388c4a0..c2f2c4e 100644 --- a/controller/src/controller.rs +++ b/controller/src/controller.rs @@ -12,10 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Controller for wallet.. instantiates and handles listeners (or single-run +//! Controller for wallet, instantiates and handles listeners (or single-run //! invocations) as needed. use crate::api::{self, ApiServer, BasicAuthMiddleware, ResponseFuture, Router, TLSConfig}; use crate::config::TorConfig; +use crate::impls::tor::config as tor_config; +use crate::impls::tor::process as tor_process; +use crate::impls::tor::{bridge as tor_bridge, proxy as tor_proxy}; use crate::keychain::Keychain; use crate::libwallet::{ address, Error, NodeClient, NodeVersionInfo, Slate, SlatepackAddress, WalletInst, @@ -23,31 +26,38 @@ use crate::libwallet::{ }; use crate::util::secp::key::SecretKey; use crate::util::{from_hex, static_secp_instance, to_base64, Mutex}; -use futures::channel::oneshot; use grin_wallet_api::JsonId; -use grin_wallet_config::types::{TorBridgeConfig, TorProxyConfig}; use grin_wallet_util::OnionV3Address; -use hyper::body; + use hyper::header::HeaderValue; -use hyper::{Body, Request, Response, StatusCode}; +use hyper::{Request, Response, StatusCode}; use qr_code::QrCode; use serde::{Deserialize, Serialize}; use serde_json; use std::collections::HashMap; use std::convert::TryFrom; +use std::io::Cursor; use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; - -use crate::impls::tor::config as tor_config; -use crate::impls::tor::process as tor_process; -use crate::impls::tor::{bridge as tor_bridge, proxy as tor_proxy}; +use std::thread; use crate::apiwallet::{ - EncryptedRequest, EncryptedResponse, EncryptionErrorResponse, Foreign, + ConfigPath, EncryptedRequest, EncryptedResponse, EncryptionErrorResponse, Foreign, ForeignCheckMiddlewareFn, ForeignRpc, Owner, OwnerRpc, }; use easy_jsonrpc_mw; use easy_jsonrpc_mw::{Handler, MaybeReply}; +use grin_api::ApiBody; +use grin_wallet_config::config::{ + add_global_config_listener, get_global_config, remove_global_config_listener, +}; +use grin_wallet_impls::tor::arti::{start_tor_service, stop_tor_service}; +use grin_wallet_impls::tor::process::TorProcess; +use http_body_util::{BodyExt, Full}; +use hyper::body::Incoming; +use tokio::sync::mpsc; lazy_static! { pub static ref GRIN_OWNER_BASIC_REALM: HeaderValue = @@ -82,38 +92,20 @@ fn check_middleware( } /// initiate the tor listener -fn init_tor_listener( - wallet: Arc + 'static>>>, - keychain_mask: Arc>>, +fn init_tor_listener( + sec_key: SecretKey, + tor_dir: String, addr: &str, - bridge: TorBridgeConfig, - tor_proxy: TorProxyConfig, -) -> Result<(tor_process::TorProcess, SlatepackAddress), Error> -where - L: WalletLCProvider<'static, C, K> + 'static, - C: NodeClient + 'static, - K: Keychain + 'static, -{ + tor_config: TorConfig, +) -> Result { + info!("Starting external Tor Process listener."); + let mut process = tor_process::TorProcess::new(); - let mask = keychain_mask.lock(); - // eventually want to read a list of service config keys - let mut w_lock = wallet.lock(); - let lc = w_lock.lc_provider()?; - let w_inst = lc.wallet_inst()?; - let k = w_inst.keychain((&mask).as_ref())?; - let parent_key_id = w_inst.parent_key_id(); - let tor_dir = format!("{}/tor/listener", lc.get_top_level_directory()?); - let sec_key = address::address_from_derivation_path(&k, &parent_key_id, 0) - .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; - let onion_address = OnionV3Address::from_private(&sec_key.0) - .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; - let sp_address = SlatepackAddress::try_from(onion_address.clone())?; + let tor_timeout = tor_config.bootstrap_timeout().as_secs(); let mut hm_tor_bridge: HashMap = HashMap::new(); - let mut tor_timeout = 20; - if bridge.bridge_line.is_some() { - tor_timeout = 40; - let bridge_config = tor_bridge::TorBridge::try_from(bridge) + if tor_config.bridge.bridge_line.is_some() { + let bridge_config = tor_bridge::TorBridge::try_from(tor_config.bridge) .map_err(|e| Error::TorConfig(format!("{}", e).into()))?; hm_tor_bridge = bridge_config .to_hashmap() @@ -121,18 +113,14 @@ where } let mut hm_tor_poxy: HashMap = HashMap::new(); - if tor_proxy.transport.is_some() || tor_proxy.allowed_port.is_some() { - let proxy_config = tor_proxy::TorProxy::try_from(tor_proxy) + if tor_config.proxy.transport.is_some() || tor_config.proxy.allowed_port.is_some() { + let proxy_config = tor_proxy::TorProxy::try_from(tor_config.proxy) .map_err(|e| Error::TorConfig(format!("{}", e).into()))?; hm_tor_poxy = proxy_config .to_hashmap() .map_err(|e| Error::TorConfig(format!("{}", e).into()))?; } - warn!( - "Starting Tor Hidden Service for API listener at address {}, binding to {}", - onion_address, addr - ); tor_config::output_tor_listener_config( &tor_dir, addr, @@ -149,15 +137,15 @@ where .completion_percent(100) .launch() .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; - Ok((process, sp_address)) + Ok(process) } /// Instantiate wallet Owner API for a single-use (command line) call /// Return a function containing a loaded API context to call pub fn owner_single_use( - wallet: Option>>>>, + wallet: Arc>>>, keychain_mask: Option<&SecretKey>, - api_context: Option<&mut Owner>, + config_path: PathBuf, f: F, ) -> Result<(), Error> where @@ -166,27 +154,14 @@ where C: NodeClient + 'static, K: Keychain + 'static, { - match api_context { - Some(c) => f(c, keychain_mask)?, - None => { - let wallet = match wallet { - Some(w) => w, - None => { - return Err(Error::GenericError(format!( - "Instantiated wallet or Owner API context must be provided" - ))) - } - }; - f(&mut Owner::new(wallet, None), keychain_mask)? - } - } - Ok(()) + f(&mut Owner::new(wallet, None, config_path), keychain_mask) } /// Instantiate wallet Foreign API for a single-use (command line) call /// Return a function containing a loaded API context to call pub fn foreign_single_use<'a, L, F, C, K>( wallet: Arc>>>, + config_path: PathBuf, keychain_mask: Option, f: F, ) -> Result<(), Error> @@ -198,6 +173,7 @@ where { f(&mut Foreign::new( wallet, + config_path, keychain_mask, Some(check_middleware), false, @@ -210,13 +186,12 @@ where /// Note keychain mask is only provided here in case the foreign listener is also being used /// in the same wallet instance pub fn owner_listener( - wallet: Arc + 'static>>>, + owner_api: &mut Owner, keychain_mask: Arc>>, addr: &str, api_secret: Option, tls_config: Option, owner_api_include_foreign: Option, - tor_config: Option, test_mode: bool, ) -> Result<(), Error> where @@ -240,12 +215,8 @@ where running_foreign = true; } - let api_handler_v3 = OwnerAPIHandlerV3::new( - wallet.clone(), - keychain_mask.clone(), - tor_config.clone(), - running_foreign, - ); + let wallet = owner_api.wallet_inst.clone(); + let api_handler_v3 = OwnerAPIHandlerV3::new(owner_api, keychain_mask.clone(), running_foreign); router .add_route("/v3/owner", Arc::new(api_handler_v3)) @@ -254,15 +225,18 @@ where // If so configured, add the foreign API to the same port if running_foreign { warn!("Starting HTTP Foreign API on Owner server at {}.", addr); - let foreign_api_handler_v2 = - ForeignAPIHandlerV2::new(wallet, keychain_mask, test_mode, Mutex::new(tor_config)); + let foreign_api_handler_v2 = ForeignAPIHandlerV2::new( + wallet, + owner_api.shared_config_path(), + keychain_mask, + test_mode, + ); router .add_route("/v2/foreign", Arc::new(foreign_api_handler_v2)) .map_err(|_| Error::GenericError("Router failed to add route".to_string()))?; } - let api_chan: &'static mut (oneshot::Sender<()>, oneshot::Receiver<()>) = - Box::leak(Box::new(oneshot::channel::<()>())); + let api_chan: (mpsc::Sender<()>, mpsc::Receiver<()>) = mpsc::channel::<()>(1); let mut apis = ApiServer::new(); warn!("Starting HTTP Owner API server at {}.", addr); @@ -280,82 +254,162 @@ where /// port and wrapping the calls pub fn foreign_listener( wallet: Arc + 'static>>>, + config_path: PathBuf, + bridge: Option, + use_tor: Option, keychain_mask: Arc>>, addr: &str, tls_config: Option, - use_tor: bool, test_mode: bool, - tor_config: Option, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: Keychain + 'static, { - // Check if wallet has been opened first - { - let mut w_lock = wallet.lock(); - let lc = w_lock.lc_provider()?; - let _ = lc.wallet_inst()?; - } + loop { + let (restart_tx, restart_rx) = std::sync::mpsc::channel::<()>(); + register_config_listener(&config_path, "foreign_listener", restart_tx)?; - let (tor_bridge, tor_proxy) = match tor_config.clone() { - Some(s) => (s.bridge, s.proxy), - None => (TorBridgeConfig::default(), TorProxyConfig::default()), - }; + let tor_config = listener_tor_config(&config_path, bridge.clone(), use_tor)?; - // need to keep in scope while the main listener is running - let (_tor_process, address) = match use_tor { - true => { - match init_tor_listener( - wallet.clone(), - keychain_mask.clone(), - addr, - tor_bridge, - tor_proxy, - ) { - Ok((tp, addr)) => (Some(tp), Some(addr)), + // Check if wallet has been opened first + let (sec_key, tor_dir, onion_address) = { + let mask = keychain_mask.lock(); + let mut w_lock = wallet.lock(); + let lc = w_lock.lc_provider()?; + let w_inst = lc.wallet_inst()?; + let k = w_inst.keychain((&mask).as_ref())?; + let parent_key_id = w_inst.parent_key_id(); + let sec_key = address::address_from_derivation_path(&k, &parent_key_id, 0) + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + let tor_dir = format!("{}/tor/listener", lc.get_top_level_directory()?); + let onion_address = OnionV3Address::from_private(&sec_key.0) + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + (sec_key, tor_dir, onion_address) + }; + + let api_handler_v2 = ForeignAPIHandlerV2::new( + wallet.clone(), + config_path.clone().into(), + keychain_mask.clone(), + test_mode, + ); + let mut router = Router::new(); + + router + .add_route("/v2/foreign", Arc::new(api_handler_v2)) + .map_err(|_| Error::GenericError("Router failed to add route".to_string()))?; + + let api_chan: (mpsc::Sender<()>, mpsc::Receiver<()>) = mpsc::channel::<()>(1); + let stop_tx = api_chan.0.clone(); + + let mut apis = ApiServer::new(); + warn!("Starting HTTP Foreign listener API server at {}.", addr); + let socket_addr: SocketAddr = addr.parse().expect("unable to parse socket address"); + let api_thread = apis + .start(socket_addr, router, tls_config.clone(), api_chan) + .map_err(|_| Error::GenericError("API thread failed to start".to_string()))?; + warn!("HTTP Foreign listener started."); + + // Need to keep external process in scope while the listener is running. + let _tor_service = if tor_config.use_tor_listener { + let use_integrated = tor_config.use_integrated.unwrap_or(false); + + let res: Result, Error> = if use_integrated { + match start_tor_service(sec_key, addr, &tor_config.clone()) { + Ok(_) => Ok(None), + Err(e) => { + error!("Error starting integrated Tor service: {}", e); + Err(e) + } + } + } else { + match init_tor_listener(sec_key, tor_dir, addr, tor_config.clone()) { + Ok(p) => Ok(Some(p)), + Err(e) => { + error!("Error starting external Tor listener: {}", e); + Err(e) + } + } + }; + match res { + Ok(service) => { + warn!( + "Starting Tor Hidden Service for API listener at address {}, binding to {}", + onion_address, addr + ); + let sp_address = SlatepackAddress::try_from(onion_address.clone())?; + let qr_string = match QrCode::new(sp_address.to_string()) { + Ok(qr) => qr.to_string(false, 3), + Err(_) => "Failed to generate QR code!".to_string(), + }; + warn!("Slatepack Address is: {}\n{}", sp_address, qr_string); + Ok(service) + } Err(e) => { - warn!("Unable to start TOR listener; Check that TOR executable is installed and on your path"); + warn!("Unable to start TOR listener"); error!("Tor Error: {}", e); - warn!("Listener will be available via HTTP only"); - (None, None) + warn!("Listener is available on {}", addr); + Err(e) } } - } - false => (None, None), - }; - - let api_handler_v2 = - ForeignAPIHandlerV2::new(wallet, keychain_mask, test_mode, Mutex::new(tor_config)); - let mut router = Router::new(); - - router - .add_route("/v2/foreign", Arc::new(api_handler_v2)) - .map_err(|_| Error::GenericError("Router failed to add route".to_string()))?; - - let api_chan: &'static mut (oneshot::Sender<()>, oneshot::Receiver<()>) = - Box::leak(Box::new(oneshot::channel::<()>())); - - let mut apis = ApiServer::new(); - warn!("Starting HTTP Foreign listener API server at {}.", addr); - let socket_addr: SocketAddr = addr.parse().expect("unable to parse socket address"); - let api_thread = apis - .start(socket_addr, router, tls_config, api_chan) - .map_err(|_| Error::GenericError("API thread failed to start".to_string()))?; - - warn!("HTTP Foreign listener started."); - if let Some(a) = address { - let qr_string = match QrCode::new(a.to_string()) { - Ok(qr) => qr.to_string(false, 3), - Err(_) => "Failed to generate QR code!".to_string(), + } else { + warn!("Listener is available on {}", addr); + Ok(None) }; - warn!("Slatepack Address is: {}\n{}", a, qr_string); - } - api_thread - .join() - .map_err(|e| Error::GenericError(format!("API thread panicked :{:?}", e))) + // Start thread to check if restart is needed. + let restart_needed = Arc::new(AtomicBool::new(false)); + let t_restart_needed = restart_needed.clone(); + thread::spawn(move || { + if restart_rx.recv().is_ok() { + t_restart_needed.store(true, Ordering::SeqCst); + let _ = stop_tx.try_send(()); + } + }); + + let res = api_thread + .join() + .map_err(|e| Error::GenericError(format!("API thread panicked :{:?}", e))); + + if tor_config.use_tor_listener && tor_config.use_integrated.unwrap_or(false) { + stop_tor_service(onion_address.to_string())?; + } + + if restart_needed.load(Ordering::Relaxed) { + continue; + } + + remove_global_config_listener(&config_path, "foreign_listener"); + + return res; + } +} + +fn register_config_listener( + config_path: &PathBuf, + listener_id: &str, + tx: std::sync::mpsc::Sender<()>, +) -> Result<(), Error> { + get_global_config(config_path)?; + add_global_config_listener(config_path, listener_id, tx); + Ok(()) +} + +fn listener_tor_config( + config_path: &Path, + bridge: Option, + use_tor: Option, +) -> Result { + let mut tor_config = get_global_config(config_path)?.tor_config(); + if let Some(bridge) = bridge { + tor_config.bridge.bridge_line = Some(bridge); + } + if let Some(use_tor) = use_tor { + tor_config.use_tor_listener = use_tor; + } + Ok(tor_config) } /// V3 API Handler/Wrapper for owner functions, which include a secure @@ -551,19 +605,17 @@ impl OwnerV3Helpers { None }; match err_string { - Some(s) => { - return ( - true, - serde_json::json!({ - "jsonrpc": "2.0", - "id": val["id"], - "error": { - "message": s, - "code": -32099 - } - }), - ) - } + Some(s) => ( + true, + serde_json::json!({ + "jsonrpc": "2.0", + "id": val["id"], + "error": { + "message": s, + "code": -32099 + } + }), + ), None => (false, val.clone()), } } @@ -577,25 +629,24 @@ where { /// Create a new owner API handler for GET methods pub fn new( - wallet: Arc + 'static>>>, + owner_api: &Owner, keychain_mask: Arc>>, - tor_config: Option, running_foreign: bool, ) -> OwnerAPIHandlerV3 { - let owner_api = Owner::new(wallet.clone(), None); - owner_api.set_tor_config(tor_config); - let owner_api = Arc::new(owner_api); + let wallet = owner_api.wallet_inst.clone(); + let config_path = owner_api.shared_config_path(); + let owner_api = Owner::new(wallet.clone(), None, config_path); OwnerAPIHandlerV3 { wallet, - owner_api, + owner_api: Arc::new(owner_api), shared_key: Arc::new(Mutex::new(None)), - keychain_mask: keychain_mask, + keychain_mask, running_foreign, } } async fn call_api( - req: Request, + req: Request, key: Arc>>, mask: Arc>>, running_foreign: bool, @@ -661,12 +712,12 @@ where } async fn handle_post_request( - req: Request, + req: Request, key: Arc>>, mask: Arc>>, running_foreign: bool, api: Arc>, - ) -> Result, Error> { + ) -> Result, Error> { let res = Self::call_api(req, key, mask, running_foreign, api).await?; Ok(json_response_pretty(&res)) } @@ -678,7 +729,7 @@ where C: NodeClient + 'static, K: Keychain + 'static, { - fn post(&self, req: Request) -> ResponseFuture { + fn post(&self, req: Request) -> ResponseFuture { let key = self.shared_key.clone(); let mask = self.keychain_mask.clone(); let running_foreign = self.running_foreign; @@ -695,7 +746,7 @@ where }) } - fn options(&self, _req: Request) -> ResponseFuture { + fn options(&self, _req: Request) -> ResponseFuture { Box::pin(async { Ok(create_ok_response("{}")) }) } } @@ -706,14 +757,14 @@ where C: NodeClient + 'static, K: Keychain + 'static, { - /// Wallet instance + /// Wallet instance. pub wallet: Arc + 'static>>>, + /// Wallet configuration path. + pub config_path: ConfigPath, /// Keychain mask pub keychain_mask: Arc>>, /// run in doctest mode pub test_mode: bool, - /// tor config - pub tor_config: Mutex>, } impl ForeignAPIHandlerV2 @@ -725,20 +776,20 @@ where /// Create a new foreign API handler for GET methods pub fn new( wallet: Arc + 'static>>>, + config_path: ConfigPath, keychain_mask: Arc>>, test_mode: bool, - tor_config: Mutex>, ) -> ForeignAPIHandlerV2 { ForeignAPIHandlerV2 { wallet, + config_path, keychain_mask, test_mode, - tor_config, } } async fn call_api( - req: Request, + req: Request, api: Foreign<'static, L, C, K>, ) -> Result { let val: serde_json::Value = parse_body(req).await?; @@ -753,14 +804,13 @@ where } async fn handle_post_request( - req: Request, + req: Request, mask: Option, wallet: Arc + 'static>>>, + config_path: ConfigPath, test_mode: bool, - tor_config: Option, - ) -> Result, Error> { - let api = Foreign::new(wallet, mask, Some(check_middleware), test_mode); - api.set_tor_config(tor_config); + ) -> Result, Error> { + let api = Foreign::new(wallet, config_path, mask, Some(check_middleware), test_mode); let res = Self::call_api(req, api).await?; Ok(json_response_pretty(&res)) } @@ -772,14 +822,14 @@ where C: NodeClient + 'static, K: Keychain + 'static, { - fn post(&self, req: Request) -> ResponseFuture { + fn post(&self, req: Request) -> ResponseFuture { let mask = self.keychain_mask.lock().clone(); let wallet = self.wallet.clone(); let test_mode = self.test_mode; - let tor_config = self.tor_config.lock().clone(); + let config_path = self.config_path.clone(); Box::pin(async move { - match Self::handle_post_request(req, mask, wallet, test_mode, tor_config).await { + match Self::handle_post_request(req, mask, wallet, config_path, test_mode).await { Ok(v) => Ok(v), Err(e) => { error!("Request Error: {:?}", e); @@ -789,35 +839,24 @@ where }) } - fn options(&self, _req: Request) -> ResponseFuture { + fn options(&self, _req: Request) -> ResponseFuture { Box::pin(async { Ok(create_ok_response("{}")) }) } } -// Utility to serialize a struct into JSON and produce a sensible Response -// out of it. -fn _json_response(s: &T) -> Response -where - T: Serialize, -{ - match serde_json::to_string(s) { - Ok(json) => response(StatusCode::OK, json), - Err(_) => response(StatusCode::INTERNAL_SERVER_ERROR, ""), - } -} - -// pretty-printed version of above -fn json_response_pretty(s: &T) -> Response +/// Utility to serialize a struct into JSON and produce a sensible Response +/// out of it. +fn json_response_pretty(s: &T) -> Response where T: Serialize, { match serde_json::to_string_pretty(s) { - Ok(json) => response(StatusCode::OK, json), - Err(_) => response(StatusCode::INTERNAL_SERVER_ERROR, ""), + Ok(json) => response(StatusCode::OK, Full::from(json).boxed()), + Err(_) => response(StatusCode::INTERNAL_SERVER_ERROR, Full::from("").boxed()), } } -fn create_error_response(e: Error) -> Response { +fn create_error_response(e: Error) -> Response { Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) .header("access-control-allow-origin", "*") @@ -825,11 +864,11 @@ fn create_error_response(e: Error) -> Response { "access-control-allow-headers", "Content-Type, Authorization", ) - .body(format!("{}", e).into()) + .body(Full::from(format!("{}", e)).boxed()) .unwrap() } -fn create_ok_response(json: &str) -> Response { +fn create_ok_response(json: &str) -> Response { Response::builder() .status(StatusCode::OK) .header("access-control-allow-origin", "*") @@ -838,7 +877,7 @@ fn create_ok_response(json: &str) -> Response { "Content-Type, Authorization", ) .header(hyper::header::CONTENT_TYPE, "application/json") - .body(json.to_string().into()) + .body(Full::from(json.to_string()).boxed()) .unwrap() } @@ -846,7 +885,7 @@ fn create_ok_response(json: &str) -> Response { /// /// Whenever the status code is `StatusCode::OK` the text parameter should be /// valid JSON as the content type header will be set to `application/json' -fn response>(status: StatusCode, text: T) -> Response { +fn response>(status: StatusCode, text: T) -> Response { let mut builder = Response::builder() .status(status) .header("access-control-allow-origin", "*") @@ -862,14 +901,63 @@ fn response>(status: StatusCode, text: T) -> Response { builder.body(text.into()).unwrap() } -async fn parse_body(req: Request) -> Result +async fn parse_body(req: Request) -> Result where for<'de> T: Deserialize<'de> + Send + 'static, { - let body = body::to_bytes(req.into_body()) + let body_req = req + .into_body() + .collect() .await - .map_err(|_| Error::GenericError("Failed to read request".to_string()))?; + .map_err(|e| Error::GenericError(format!("Failed to read request: {}", e)))?; + let raw = body_req.to_bytes(); - serde_json::from_reader(&body[..]) + let cursor = Cursor::new(raw); + serde_json::from_reader(cursor) .map_err(|e| Error::GenericError(format!("Invalid request body: {}", e))) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::global::ChainTypes; + use grin_wallet_config::config::update_global_config; + use grin_wallet_config::GlobalWalletConfig; + use std::fs; + use std::sync::mpsc::channel; + use std::time::Duration; + use uuid::Uuid; + + #[test] + fn listener_reload() { + let dir = std::env::temp_dir().join(format!("grin-wallet-listener-{}", Uuid::new_v4())); + fs::create_dir(&dir).unwrap(); + let path = dir.join("grin-wallet.toml"); + let mut config = GlobalWalletConfig::for_chain(&ChainTypes::AutomatedTesting, &path); + config + .write_to_file(path.to_str().unwrap(), false, None, None) + .unwrap(); + + let (restart_tx, restart_rx) = channel(); + register_config_listener(&path, "test_listener", restart_tx).unwrap(); + + update_global_config(&path, |config| { + config.members.tor.as_mut().unwrap().socks_proxy_addr = "127.0.0.1:59051".into(); + Ok(()) + }) + .unwrap(); + restart_rx.recv_timeout(Duration::from_secs(1)).unwrap(); + + let tor_config = + listener_tor_config(&path, Some("obfs4 test-bridge".into()), Some(false)).unwrap(); + assert_eq!(tor_config.socks_proxy_addr, "127.0.0.1:59051"); + assert_eq!( + tor_config.bridge.bridge_line.as_deref(), + Some("obfs4 test-bridge") + ); + assert!(!tor_config.use_tor_listener); + + remove_global_config_listener(&path, "test_listener"); + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/controller/tests/accounts.rs b/controller/tests/accounts.rs index 744a5e1..35413bd 100644 --- a/controller/tests/accounts.rs +++ b/controller/tests/accounts.rs @@ -19,6 +19,7 @@ extern crate grin_wallet_impls as impls; use grin_core as core; use grin_keychain as keychain; +use std::path::PathBuf; use self::core::global; use self::keychain::{ExtKeychain, Keychain}; @@ -78,33 +79,48 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let cm = global::coinbase_maturity(); // assume all testing precedes soft fork height // test default accounts exist - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let accounts = api.accounts(m)?; - assert_eq!(accounts[0].label, "default"); - assert_eq!(accounts[0].path, ExtKeychain::derive_key_id(2, 0, 0, 0, 0)); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let accounts = api.accounts(m)?; + assert_eq!(accounts[0].label, "default"); + assert_eq!(accounts[0].path, ExtKeychain::derive_key_id(2, 0, 0, 0, 0)); + Ok(()) + }, + )?; // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let new_path = api.create_account_path(m, "account1").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); - let new_path = api.create_account_path(m, "account2").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); - let new_path = api.create_account_path(m, "account3").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 3, 0, 0, 0)); - // trying to add same label again should fail - let res = api.create_account_path(m, "account1"); - assert!(res.is_err()); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let new_path = api.create_account_path(m, "account1").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); + let new_path = api.create_account_path(m, "account2").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); + let new_path = api.create_account_path(m, "account3").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 3, 0, 0, 0)); + // trying to add same label again should fail + let res = api.create_account_path(m, "account1"); + assert!(res.is_err()); + Ok(()) + }, + )?; // add account to wallet 2 - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let new_path = api.create_account_path(m, "listener_account").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let new_path = api.create_account_path(m, "listener_account").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); + Ok(()) + }, + )?; // Default wallet 2 to listen on that account { @@ -128,17 +144,22 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 5 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, (5 - cm) * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 5); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 5 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, (5 - cm) * reward); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 5); + Ok(()) + }, + )?; // now check second account { @@ -149,115 +170,150 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // check last confirmed height on this account is different from above (should be 0) - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 0); - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 7 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, 7 * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 7); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // check last confirmed height on this account is different from above (should be 0) + let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 7 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, 7 * reward); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 7); + Ok(()) + }, + )?; // should be nothing in default account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("default")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 0); - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 0,); - assert_eq!(wallet1_info.amount_currently_spendable, 0,); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 0,); + assert_eq!(wallet1_info.amount_currently_spendable, 0,); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 0); + Ok(()) + }, + )?; // Send a tx to another wallet { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate)?; - api.tx_lock_outputs(m, &slate)?; - slate = api.finalize_tx(m, &slate)?; - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = InitTxArgs { + src_acct_name: None, + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api.init_send_tx(m, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate)?; + api.tx_lock_outputs(m, &slate)?; + slate = api.finalize_tx(m, &slate)?; + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 9); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 9); + Ok(()) + }, + )?; // other account should be untouched { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account2")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 12); - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - println!("{:?}", txs); - assert_eq!(txs.len(), 5); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 12); + let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + println!("{:?}", txs); + assert_eq!(txs.len(), 5); + Ok(()) + }, + )?; // wallet 2 should only have this tx on the listener account - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 13); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 1); + Ok(()) + }, + )?; // Default account on wallet 2 should be untouched { wallet_inst!(wallet2, w); w.set_parent_key_id_by_name("default")?; } - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (_, wallet2_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet2_info.last_confirmed_height, 0); - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, 13); - assert_eq!(wallet2_info.total, 0,); - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet2_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet2_info.last_confirmed_height, 0); + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 13); + assert_eq!(wallet2_info.total, 0,); + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 0); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/build_chain.rs b/controller/tests/build_chain.rs index cd9a2d8..7120e44 100644 --- a/controller/tests/build_chain.rs +++ b/controller/tests/build_chain.rs @@ -21,6 +21,7 @@ extern crate grin_wallet_impls as impls; extern crate grin_wallet_libwallet as libwallet; use grin_core as core; +use std::path::PathBuf; use self::libwallet::{InitTxArgs, Slate}; use impls::test_framework::{self, LocalWalletClient}; @@ -73,15 +74,25 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal // Stop the scanning updater threads because it extends the time needed to build the chain // exponentially - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, _m| { - api.stop_updater()?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, _m| { + api.stop_updater()?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, _m| { - api.stop_updater()?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, _m| { + api.stop_updater()?; + Ok(()) + }, + )?; // few values to keep things shorter let reward = core::consensus::REWARD; @@ -94,17 +105,22 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal let mut wallet_1_has_funds = false; // Check wallet 1 contents - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 spendable - {}", - wallet1_info.amount_currently_spendable - ); - if wallet1_info.amount_currently_spendable > reward { - wallet_1_has_funds = true; - } - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + debug!( + "Wallet 1 spendable - {}", + wallet1_info.amount_currently_spendable + ); + if wallet1_info.amount_currently_spendable > reward { + wallet_1_has_funds = true; + } + Ok(()) + }, + )?; // let's say 1 in every 3 blocks has a transaction (i.e. random 0 here and wallet1 has funds) let transact = rng.gen_range(0, 2) == 0; @@ -121,14 +137,14 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal let mut slate = Slate::blank(1, false); debug!("Creating TX for {}", amount); wallet::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |sender_api, m| { // note this will increment the block count as part of the transaction "Posting" let args = InitTxArgs { src_acct_name: None, - amount: amount, + amount, minimum_confirmations: 1, max_outputs: 500, num_change_outputs: 1, diff --git a/controller/tests/build_output.rs b/controller/tests/build_output.rs index 7f05a2a..491e916 100644 --- a/controller/tests/build_output.rs +++ b/controller/tests/build_output.rs @@ -25,6 +25,7 @@ use grin_util::{secp, ZeroingString}; use grin_wallet_libwallet as libwallet; use impls::test_framework::LocalWalletClient; use rand::{thread_rng, Rng}; +use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -66,23 +67,28 @@ fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error let secp = secp::Secp256k1::with_caps(secp::ContextFlag::Commit); let features = OutputFeatures::Plain; let amount = 60_000_000_000; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - let built_output = sender_api.build_output(m, features, amount)?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + let built_output = sender_api.build_output(m, features, amount)?; - let key_id = built_output.key_id; - assert_eq!(key_id.to_path(), ExtKeychainPath::new(3, 0, 0, 0, 0)); + let key_id = built_output.key_id; + assert_eq!(key_id.to_path(), ExtKeychainPath::new(3, 0, 0, 0, 0)); - let blind = built_output.blind; - let key = keychain.derive_key(amount, &key_id, SwitchCommitmentType::Regular)?; - assert_eq!(blind, BlindingFactor::from_secret_key(key.clone())); + let blind = built_output.blind; + let key = keychain.derive_key(amount, &key_id, SwitchCommitmentType::Regular)?; + assert_eq!(blind, BlindingFactor::from_secret_key(key.clone())); - let output = built_output.output; - assert_eq!(output.features(), features); - assert_eq!(output.commitment(), secp.commit(amount, key)?); - output.verify_proof()?; + let output = built_output.output; + assert_eq!(output.features(), features); + assert_eq!(output.commitment(), secp.commit(amount, key)?); + output.verify_proof()?; - Ok(()) - })?; + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/check.rs b/controller/tests/check.rs index c9c5990..d526335 100644 --- a/controller/tests/check.rs +++ b/controller/tests/check.rs @@ -27,6 +27,7 @@ use impls::test_framework::{self, LocalWalletClient}; use impls::{PathToSlate, SlatePutter as _}; use libwallet::{InitTxArgs, NodeClient}; use std::cmp; +use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -92,20 +93,30 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let cm = global::coinbase_maturity() as u64; // assume all testing precedes soft fork height // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.create_account_path(m, "named_account_1")?; - api.create_account_path(m, "account_2")?; - api.create_account_path(m, "account_3")?; - api.set_active_account(m, "named_account_1")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "named_account_1")?; + api.create_account_path(m, "account_2")?; + api.create_account_path(m, "account_3")?; + api.set_active_account(m, "named_account_1")?; + Ok(()) + }, + )?; // add account to wallet 2 - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "account_1")?; + api.set_active_account(m, "account_1")?; + Ok(()) + }, + )?; // Do some mining let bh = 20u64; @@ -113,26 +124,36 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Sanity check contents - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); - assert_eq!(wallet1_info.total, c); - assert_eq!(txs.len(), bh as usize); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_eq!(wallet1_info.total, c); + assert_eq!(txs.len(), bh as usize); + Ok(()) + }, + )?; // Accidentally delete some outputs let mut w1_outputs_commits = vec![]; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - w1_outputs_commits = api.retrieve_outputs(m, false, true, None)?.1; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + w1_outputs_commits = api.retrieve_outputs(m, false, true, None)?.1; + Ok(()) + }, + )?; let w1_outputs: Vec = w1_outputs_commits.into_iter().map(|m| m.output).collect(); { @@ -149,73 +170,108 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { } // check we have a problem now - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); - assert!(wallet1_info.total != c); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_ne!(wallet1_info.total, c); + Ok(()) + }, + )?; // this should restore our missing outputs - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.scan(m, None, true)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.scan(m, None, true)?; + Ok(()) + }, + )?; // check our outputs match again - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.total, bh * reward); - // And check account names haven't been splatted - let accounts = api.accounts(m)?; - assert_eq!(accounts.len(), 4); - assert!(api.set_active_account(m, "account_1").is_err()); - assert!(api.set_active_account(m, "named_account_1").is_ok()); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.total, bh * reward); + // And check account names haven't been splatted + let accounts = api.accounts(m)?; + assert_eq!(accounts.len(), 4); + assert!(api.set_active_account(m, "account_1").is_err()); + assert!(api.set_active_account(m, "named_account_1").is_ok()); + Ok(()) + }, + )?; // perform a transaction, but don't let it finish - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: None, - amount: reward * 2, - minimum_confirmations: cm, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - let send_file = format!("{}/part_tx_1.tx", test_dir); - PathToSlate(send_file.into()).put_tx(&slate, false)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // send to send + let args = InitTxArgs { + src_acct_name: None, + amount: reward * 2, + minimum_confirmations: cm, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api.init_send_tx(m, args)?; + // output tx file + let send_file = format!("{}/part_tx_1.tx", test_dir); + PathToSlate(send_file.into()).put_tx(&slate, false)?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; // check we're all locked - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert!(wallet1_info.amount_currently_spendable == 0); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.amount_currently_spendable, 0); + Ok(()) + }, + )?; // unlock/restore - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.scan(m, None, true)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.scan(m, None, true)?; + Ok(()) + }, + )?; // check spendable amount again - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); @@ -412,13 +468,18 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; // 0) Check repair when all is okay should leave wallet contents alone - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.scan(m, None, true)?; - let info = wallet_info!(wallet1.clone(), m)?; - assert_eq!(info.amount_currently_spendable, base_amount * 6); - assert_eq!(info.total, base_amount * 6); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.scan(m, None, true)?; + let info = wallet_info!(wallet1.clone(), m)?; + assert_eq!(info.amount_currently_spendable, base_amount * 6); + assert_eq!(info.total, base_amount * 6); + Ok(()) + }, + )?; // send some funds to wallet 2 send_to_dest!( @@ -462,33 +523,53 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er // seed + BIP32 path. // 1) a full restore should recover all of them: - wallet::controller::owner_single_use(Some(wallet3.clone()), mask3, None, |api, m| { - api.scan(m, None, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet3.clone(), + mask3, + PathBuf::from(test_dir), + |api, m| { + api.scan(m, None, false)?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet3.clone()), mask3, None, |api, m| { - let info = wallet_info!(wallet3.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); - assert_eq!(info.total, base_amount * 21); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet3.clone(), + mask3, + PathBuf::from(test_dir), + |api, m| { + let info = wallet_info!(wallet3.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); + assert_eq!(info.total, base_amount * 21); + Ok(()) + }, + )?; // 2) scan should recover them into a single wallet - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.scan(m, None, true)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.scan(m, None, true)?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let info = wallet_info!(wallet1.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let info = wallet_info!(wallet1.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); + Ok(()) + }, + )?; // 3) If I recover from seed and start using the wallet without restoring, // scan should restore the older outputs @@ -520,26 +601,41 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); bh += cm as u64; - wallet::controller::owner_single_use(Some(wallet4.clone()), mask4, None, |api, m| { - let info = wallet_info!(wallet4.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 9); - assert_eq!(info.amount_currently_spendable, base_amount * 45); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet4.clone(), + mask4, + PathBuf::from(test_dir), + |api, m| { + let info = wallet_info!(wallet4.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 9); + assert_eq!(info.amount_currently_spendable, base_amount * 45); + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet5.clone()), mask5, None, |api, m| { - api.scan(m, None, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet5.clone(), + mask5, + PathBuf::from(test_dir), + |api, m| { + api.scan(m, None, false)?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet5.clone()), mask5, None, |api, m| { - let info = wallet_info!(wallet5.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 9); - assert_eq!(info.amount_currently_spendable, base_amount * (45)); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet5.clone(), + mask5, + PathBuf::from(test_dir), + |api, m| { + let info = wallet_info!(wallet5.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 9); + assert_eq!(info.amount_currently_spendable, base_amount * (45)); + Ok(()) + }, + )?; // 4) If I recover from seed and start using the wallet without restoring, // scan should restore the older outputs @@ -575,26 +671,41 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er ); bh += cm as u64; - wallet::controller::owner_single_use(Some(wallet6.clone()), mask6, None, |api, m| { - let info = wallet_info!(wallet6.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 12); - assert_eq!(info.amount_currently_spendable, base_amount * 78); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet6.clone(), + mask6, + PathBuf::from(test_dir), + |api, m| { + let info = wallet_info!(wallet6.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 12); + assert_eq!(info.amount_currently_spendable, base_amount * 78); + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet6.clone()), mask6, None, |api, m| { - api.scan(m, None, true)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet6.clone(), + mask6, + PathBuf::from(test_dir), + |api, m| { + api.scan(m, None, true)?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet6.clone()), mask6, None, |api, m| { - let info = wallet_info!(wallet6.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 12); - assert_eq!(info.amount_currently_spendable, base_amount * (78)); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet6.clone(), + mask6, + PathBuf::from(test_dir), + |api, m| { + let info = wallet_info!(wallet6.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 12); + assert_eq!(info.amount_currently_spendable, base_amount * (78)); + Ok(()) + }, + )?; // 5) Start using same seed with a different account, amounts should // be distinct and restore should return funds from other account @@ -623,11 +734,16 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; // mix it up a bit - wallet::controller::owner_single_use(Some(wallet7.clone()), mask7, None, |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet7.clone(), + mask7, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "account_1")?; + api.set_active_account(m, "account_1")?; + Ok(()) + }, + )?; send_to_dest!( miner.clone(), @@ -656,42 +772,57 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); bh += cm as u64; - wallet::controller::owner_single_use(Some(wallet7.clone()), mask7, None, |api, m| { - let info = wallet_info!(wallet7.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 3); - assert_eq!(info.amount_currently_spendable, base_amount * 6); - api.set_active_account(m, "default")?; - let info = wallet_info!(wallet7.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet7.clone(), + mask7, + PathBuf::from(test_dir), + |api, m| { + let info = wallet_info!(wallet7.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 3); + assert_eq!(info.amount_currently_spendable, base_amount * 6); + api.set_active_account(m, "default")?; + let info = wallet_info!(wallet7.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet8.clone()), mask8, None, |api, m| { - api.scan(m, None, false)?; - let info = wallet_info!(wallet8.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - api.set_active_account(m, "account_1")?; - let info = wallet_info!(wallet8.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 3); - assert_eq!(info.amount_currently_spendable, base_amount * 6); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet8.clone(), + mask8, + PathBuf::from(test_dir), + |api, m| { + api.scan(m, None, false)?; + let info = wallet_info!(wallet8.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); + api.set_active_account(m, "account_1")?; + let info = wallet_info!(wallet8.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 3); + assert_eq!(info.amount_currently_spendable, base_amount * 6); + Ok(()) + }, + )?; // 6) Start using same seed with a different account, now overwriting // ids on account 2 as well, scan should get all outputs created // to now into 2 accounts - wallet::controller::owner_single_use(Some(wallet9.clone()), mask9, None, |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet9.clone(), + mask9, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "account_1")?; + api.set_active_account(m, "account_1")?; + Ok(()) + }, + )?; send_to_dest!( miner.clone(), @@ -717,43 +848,53 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; let _bh = bh; - wallet::controller::owner_single_use(Some(wallet9.clone()), mask9, None, |api, m| { - let info = wallet_info!(wallet9.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); - api.scan(m, None, true)?; - let info = wallet_info!(wallet9.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); + wallet::controller::owner_single_use( + wallet9.clone(), + mask9, + PathBuf::from(test_dir), + |api, m| { + let info = wallet_info!(wallet9.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); + api.scan(m, None, true)?; + let info = wallet_info!(wallet9.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); - api.set_active_account(m, "default")?; - let info = wallet_info!(wallet9.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - Ok(()) - })?; + api.set_active_account(m, "default")?; + let info = wallet_info!(wallet9.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); + Ok(()) + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); // 7) Ensure scan creates missing accounts - wallet::controller::owner_single_use(Some(wallet10.clone()), mask10, None, |api, m| { - api.scan(m, None, true)?; - api.set_active_account(m, "account_1")?; - let info = wallet_info!(wallet10.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); + wallet::controller::owner_single_use( + wallet10.clone(), + mask10, + PathBuf::from(test_dir), + |api, m| { + api.scan(m, None, true)?; + api.set_active_account(m, "account_1")?; + let info = wallet_info!(wallet10.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); - api.set_active_account(m, "default")?; - let info = wallet_info!(wallet10.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - Ok(()) - })?; + api.set_active_account(m, "default")?; + let info = wallet_info!(wallet10.clone(), m)?; + let outputs = api.retrieve_outputs(m, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); @@ -877,13 +1018,18 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); let mut output_commits = vec![]; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, bh * reward); - output_commits = api.retrieve_outputs(m, false, true, None)?.1; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, info) = api.retrieve_summary_info(m, true, 1)?; + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, bh * reward); + output_commits = api.retrieve_outputs(m, false, true, None)?.1; + Ok(()) + }, + )?; { wallet_inst!(wallet1, w); @@ -930,13 +1076,18 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } assert!(batches > 1); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, restored_outputs) = api.retrieve_outputs(m, false, true, None)?; - let (_, info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(info.total, bh * reward); - assert_eq!(restored_outputs.len(), bh as usize); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, restored_outputs) = api.retrieve_outputs(m, false, true, None)?; + let (_, info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(info.total, bh * reward); + assert_eq!(restored_outputs.len(), bh as usize); + Ok(()) + }, + )?; stopper.store(false, Ordering::Relaxed); thread::sleep(Duration::from_millis(200)); @@ -974,12 +1125,17 @@ fn restore_corrupted_outputs_across_batches_impl( test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); let mut output_commits = vec![]; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(info.total, bh * reward); - output_commits = api.retrieve_outputs(m, false, true, None)?.1; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, info) = api.retrieve_summary_info(m, true, 1)?; + assert_eq!(info.total, bh * reward); + output_commits = api.retrieve_outputs(m, false, true, None)?.1; + Ok(()) + }, + )?; { wallet_inst!(wallet1, w); @@ -1017,25 +1173,30 @@ fn restore_corrupted_outputs_across_batches_impl( assert_eq!(last_scanned.hash, ""); } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, outputs_after_first_batch) = api.retrieve_outputs(m, false, false, None)?; - assert_eq!(outputs_after_first_batch.len(), (bh - 1) as usize); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, outputs_after_first_batch) = api.retrieve_outputs(m, false, false, None)?; + assert_eq!(outputs_after_first_batch.len(), (bh - 1) as usize); - let (_, info) = api.retrieve_summary_info(m, true, 1)?; - let (_, restored_outputs) = api.retrieve_outputs(m, false, true, None)?; - let unique_keys = restored_outputs - .iter() - .map(|o| o.output.key_id.clone()) - .collect::>(); + let (_, info) = api.retrieve_summary_info(m, true, 1)?; + let (_, restored_outputs) = api.retrieve_outputs(m, false, true, None)?; + let unique_keys = restored_outputs + .iter() + .map(|o| o.output.key_id.clone()) + .collect::>(); - assert_eq!(info.total, bh * reward); - assert_eq!(restored_outputs.len(), bh as usize); - assert_eq!(unique_keys.len(), bh as usize); - assert!(restored_outputs - .iter() - .all(|o| o.output.status == libwallet::OutputStatus::Unspent)); - Ok(()) - })?; + assert_eq!(info.total, bh * reward); + assert_eq!(restored_outputs.len(), bh as usize); + assert_eq!(unique_keys.len(), bh as usize); + assert!(restored_outputs + .iter() + .all(|o| o.output.status == libwallet::OutputStatus::Unspent)); + Ok(()) + }, + )?; stopper.store(false, Ordering::Relaxed); thread::sleep(Duration::from_millis(200)); diff --git a/controller/tests/common/mod.rs b/controller/tests/common/mod.rs index 431a3cc..f9b7141 100644 --- a/controller/tests/common/mod.rs +++ b/controller/tests/common/mod.rs @@ -30,6 +30,7 @@ use chain::Chain; use grin_wallet_controller::Error; use impls::test_framework::{self, LocalWalletClient, WalletProxy}; use impls::{DefaultLCProvider, DefaultWalletImpl}; +use std::path::PathBuf; use std::sync::atomic::AtomicBool; use std::sync::Arc; use std::thread; @@ -82,7 +83,7 @@ macro_rules! open_wallet_and_add { pub fn clean_output_dir(test_dir: &str) { let path = std::path::Path::new(test_dir); if path.is_dir() { - remove_dir_all::remove_dir_all(test_dir).unwrap(); + std::fs::remove_dir_all(test_dir).unwrap(); } } @@ -260,9 +261,9 @@ pub fn create_wallets( // create the account if acc_name.to_string() != "default" { wallet::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |api, m| { let new_path = api.create_account_path(m, acc_name)?; assert_eq!( @@ -292,21 +293,32 @@ pub fn create_wallets( bh += num_mined_blocks; // Sanity check wallet 1 contents - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, num_mined_blocks * reward); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = + api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, num_mined_blocks * reward); + Ok(()) + }, + )?; } // Sanity check the number of accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let accounts = api.accounts(m)?; - assert_eq!(accounts.len(), accs.len()); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let accounts = api.accounts(m)?; + assert_eq!(accounts.len(), accs.len()); + Ok(()) + }, + )?; // Set the account on the wallet to "default" { wallet_inst!(wallet1, w); diff --git a/controller/tests/config_api.rs b/controller/tests/config_api.rs new file mode 100644 index 0000000..fd37e10 --- /dev/null +++ b/controller/tests/config_api.rs @@ -0,0 +1,228 @@ +// Copyright 2026 The Grin Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +extern crate grin_wallet_api as api; +extern crate grin_wallet_config as config; +extern crate grin_wallet_impls as impls; +extern crate grin_wallet_libwallet as libwallet; + +use config::config::{get_global_config, reload_global_config}; +use config::GlobalWalletConfig; +use impls::test_framework::LocalWalletClient; +use libwallet::{InitTxArgs, InitTxSendArgs}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering; + +mod common; +use common::{clean_output_dir, create_wallet_proxy, setup}; + +fn snapshot(path: &Path) -> Vec<(PathBuf, Vec)> { + fn collect(root: &Path, path: &Path, files: &mut Vec<(PathBuf, Vec)>) { + for entry in fs::read_dir(path).unwrap() { + let entry = entry.unwrap(); + let path = entry.path(); + if path.is_dir() { + collect(root, &path, files); + } else if path.file_name().and_then(|name| name.to_str()) != Some("lock.mdb") { + files.push(( + path.strip_prefix(root).unwrap().into(), + fs::read(path).unwrap(), + )); + } + } + } + + let mut files = vec![]; + collect(path, path, &mut files); + files.sort_by(|left, right| left.0.cmp(&right.0)); + files +} + +#[test] +fn tor_disable() { + let test_dir = "test_output/config_api_tor"; + setup(test_dir); + let mut wallet_proxy = create_wallet_proxy(test_dir); + create_wallet_and_add!( + client, + wallet, + mask, + test_dir, + "wallet", + None, + &mut wallet_proxy, + false + ); + let path = PathBuf::from(test_dir).join("grin-wallet.toml"); + let mut config = + GlobalWalletConfig::for_chain(&grin_core::global::ChainTypes::AutomatedTesting, &path); + config + .write_to_file(path.to_str().unwrap(), false, None, None) + .unwrap(); + reload_global_config(&path).unwrap(); + let mut contents = fs::read_to_string(&path).unwrap(); + let tor = contents.find("[tor]").unwrap(); + let logging = contents.find("[logging]").unwrap(); + contents.replace_range(tor..logging, ""); + let contents = contents.replace("api_listen_port = 3415", "api_listen_port = 3416"); + fs::write(&path, contents).unwrap(); + + let owner = api::Owner::new(wallet.clone(), None, path.clone()); + owner.set_tor_config(None).unwrap(); + + let stored_config = GlobalWalletConfig::new(path.clone()).unwrap(); + assert_eq!(stored_config.members.wallet.api_listen_port, 3416); + let stored = stored_config.tor_config(); + let cached = get_global_config(&path).unwrap().tor_config(); + assert!(!stored.use_tor_listener); + assert_eq!(stored.skip_send_attempt, Some(true)); + assert_eq!( + stored.send_config_dir, + stored_config.members.wallet.data_file_dir + ); + assert_eq!(cached, stored); + + drop(owner); + drop(wallet); + drop(wallet_proxy); + clean_output_dir(test_dir); +} + +#[test] +fn send_preflight() { + let test_dir = "test_output/config_api_send"; + setup(test_dir); + let mut wallet_proxy = create_wallet_proxy(test_dir); + create_wallet_and_add!( + client, + wallet, + mask, + test_dir, + "wallet", + None, + &mut wallet_proxy, + false + ); + let owner = api::Owner::new( + wallet.clone(), + None, + PathBuf::from(test_dir).join("missing.toml"), + ); + let mask = mask.as_ref(); + let (_, before_txs) = owner.retrieve_txs(mask, false, None, None, None).unwrap(); + assert!(before_txs.is_empty()); + let wallet_data = PathBuf::from(test_dir).join("wallet/wallet_data"); + let before_data = snapshot(&wallet_data); + assert!(before_data.iter().any(|(path, _)| path.starts_with("db"))); + let args = InitTxArgs { + amount: 1, + send_args: Some(InitTxSendArgs { + dest: "unused".into(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }), + ..Default::default() + }; + + let error = owner.init_send_tx(mask, args).unwrap_err(); + assert!(error.to_string().contains("Configuration file not found")); + + let (_, after_txs) = owner.retrieve_txs(mask, false, None, None, None).unwrap(); + assert!(after_txs.is_empty()); + assert_eq!(snapshot(&wallet_data), before_data); + + drop(owner); + drop(wallet); + drop(wallet_proxy); + clean_output_dir(test_dir); +} + +#[test] +fn directory_change() { + let test_dir = "test_output/config_api_directory"; + setup(test_dir); + let mut wallet_proxy = create_wallet_proxy(test_dir); + create_wallet_and_add!( + client, + wallet, + mask, + test_dir, + "wallet", + None, + &mut wallet_proxy, + false + ); + let old_dir = PathBuf::from(test_dir).join("wallet"); + let old_config = old_dir.join("grin-wallet.toml"); + let new_dir = PathBuf::from(test_dir).join("other"); + let owner = api::Owner::new(wallet.clone(), None, old_config.clone()); + + let error = owner + .set_top_level_directory(new_dir.to_str().unwrap()) + .unwrap_err(); + assert!(error.to_string().contains("Close the wallet")); + assert_eq!(owner.config_path(), old_config); + assert_eq!( + PathBuf::from(owner.get_top_level_directory().unwrap()), + old_dir + ); + + owner.close_wallet(None).unwrap(); + owner.updater_running.store(true, Ordering::Relaxed); + let error = owner + .set_top_level_directory(new_dir.to_str().unwrap()) + .unwrap_err(); + assert!(error.to_string().contains("Stop the updater")); + owner.updater_running.store(false, Ordering::Relaxed); + + fs::create_dir_all(&new_dir).unwrap(); + let new_config = new_dir.join("grin-wallet.toml"); + let mut config = GlobalWalletConfig::for_chain( + &grin_core::global::ChainTypes::AutomatedTesting, + &new_config, + ); + config + .write_to_file(new_config.to_str().unwrap(), false, None, None) + .unwrap(); + reload_global_config(&new_config).unwrap(); + let expected_port = config.members.wallet.api_listen_port + 1; + config.members.wallet.api_listen_port = expected_port; + config + .write_to_file(new_config.to_str().unwrap(), false, None, None) + .unwrap(); + + owner + .set_top_level_directory(new_dir.to_str().unwrap()) + .unwrap(); + assert_eq!(owner.config_path(), new_config); + assert_eq!( + get_global_config(&owner.config_path()) + .unwrap() + .members + .wallet + .api_listen_port, + expected_port + ); + assert_eq!( + PathBuf::from(owner.get_top_level_directory().unwrap()), + new_dir + ); + + drop(owner); + drop(wallet); + drop(wallet_proxy); + clean_output_dir(test_dir); +} diff --git a/controller/tests/contract_accounts.rs b/controller/tests/contract_accounts.rs index c5ec317..fb2fd82 100644 --- a/controller/tests/contract_accounts.rs +++ b/controller/tests/contract_accounts.rs @@ -33,6 +33,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// contract accounts testing (mostly the same as accounts.rs) fn contract_accounts_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -81,17 +82,22 @@ fn contract_accounts_impl(test_dir: &'static str) -> Result<(), libwallet::Error let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 5 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, (5 - cm) * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 5); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 5 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, (5 - cm) * reward); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 5); + Ok(()) + }, + )?; // now check second account { @@ -99,39 +105,49 @@ fn contract_accounts_impl(test_dir: &'static str) -> Result<(), libwallet::Error w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // check last confirmed height on this account is different from above (should be 0) - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 0); - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 7 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, 7 * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 7); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // check last confirmed height on this account is different from above (should be 0) + let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 7 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, 7 * reward); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 7); + Ok(()) + }, + )?; // should be nothing in default account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("default")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 0); - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 0,); - assert_eq!(wallet1_info.amount_currently_spendable, 0,); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 0,); + assert_eq!(wallet1_info.amount_currently_spendable, 0,); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 0); + Ok(()) + }, + )?; // TODO: check what send_tx_slate_direct call does in accounts.rs test // TODO: check that you can't call send on the default account because you have no funds @@ -145,104 +161,144 @@ fn contract_accounts_impl(test_dir: &'static str) -> Result<(), libwallet::Error let mut slate = Slate::blank(0, true); // this gets overriden below let mut sender_address = None; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // Send wallet inititates a standard transaction with --send=5 - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-5_000_000_000), + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // Send wallet inititates a standard transaction with --send=5 + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-5_000_000_000), + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - sender_address = Some(api.get_slatepack_address(mask1, 0)?.pub_key); - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + sender_address = Some(api.get_slatepack_address(mask1, 0)?.pub_key); + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); let mut recipient_address = None; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - // Receive wallet calls --receive=5 - let args = &mut ContractSetupArgsAPI { - net_change: Some(5_000_000_000), - ..Default::default() - }; - // Proofs are opt-in; enable and supply the sender address. - args.proof_args.suppress_proof = false; - args.proof_args.sender_address = sender_address; - slate = api.contract_sign(m, &slate, args)?; - recipient_address = Some(api.get_slatepack_address(mask2, 0)?.pub_key); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + // Receive wallet calls --receive=5 + let args = &mut ContractSetupArgsAPI { + net_change: Some(5_000_000_000), + ..Default::default() + }; + // Proofs are opt-in; enable and supply the sender address. + args.proof_args.suppress_proof = false; + args.proof_args.sender_address = sender_address; + slate = api.contract_sign(m, &slate, args)?; + recipient_address = Some(api.get_slatepack_address(mask2, 0)?.pub_key); + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard2); // Send wallet finalizes and posts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = &ContractSetupArgsAPI { - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractSetupArgsAPI { + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard3); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 9); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 9); + Ok(()) + }, + )?; // other account should be untouched { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account2")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 12); - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - println!("{:?}", txs); - assert_eq!(txs.len(), 5); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 12); + let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + println!("{:?}", txs); + assert_eq!(txs.len(), 5); + Ok(()) + }, + )?; // wallet 2 should only have this tx on the listener account - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 13); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 1); + Ok(()) + }, + )?; // Default account on wallet 2 should be untouched { wallet_inst!(wallet2, w); w.set_parent_key_id_by_name("default")?; } - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (_, wallet2_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet2_info.last_confirmed_height, 0); - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, 13); - assert_eq!(wallet2_info.total, 0,); - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet2_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet2_info.last_confirmed_height, 0); + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 13); + assert_eq!(wallet2_info.total, 0,); + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 0); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); @@ -268,18 +324,23 @@ fn contract_unknown_account_impl(test_dir: &'static str) -> Result<(), libwallet let wallet1 = wallets[0].0.clone(); let mask1 = wallets[0].1.as_ref(); - let res = wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-1_000_000_000), - src_acct_name: Some("does_not_exist".to_string()), + let res = wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-1_000_000_000), + src_acct_name: Some("does_not_exist".to_string()), + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - api.contract_new(m, args)?; - Ok(()) - }); + }; + api.contract_new(m, args)?; + Ok(()) + }, + ); assert!(res.is_err(), "expected an error for an unknown account"); stopper.store(false, Ordering::Relaxed); @@ -304,17 +365,22 @@ fn contract_missing_net_change_impl(test_dir: &'static str) -> Result<(), libwal let wallet1 = wallets[0].0.clone(); let mask1 = wallets[0].1.as_ref(); - let res = wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: None, + let res = wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: None, + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - api.contract_new(m, args)?; - Ok(()) - }); + }; + api.contract_new(m, args)?; + Ok(()) + }, + ); assert!(res.is_err(), "expected an error when net_change is missing"); stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_accounts_switch.rs b/controller/tests/contract_accounts_switch.rs index 7b47dfb..d8fabe3 100644 --- a/controller/tests/contract_accounts_switch.rs +++ b/controller/tests/contract_accounts_switch.rs @@ -29,6 +29,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// contract accounts testing when switching between accounts during transaction building fn contract_accounts_switch_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -53,36 +54,46 @@ fn contract_accounts_switch_impl(test_dir: &'static str) -> Result<(), libwallet wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 10); - assert_eq!(wallet1_info.total, 1 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, 1 * reward); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 10); + assert_eq!(wallet1_info.total, 1 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, 1 * reward); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 1); + Ok(()) + }, + )?; // wallet1::account2 should have 2 in account1 (2 spendable) { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account2")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // check last confirmed height on this account is different from above (should be 0) - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 3); - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 10); - assert_eq!(wallet1_info.total, 2 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, 2 * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 2); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // check last confirmed height on this account is different from above (should be 0) + let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 3); + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 10); + assert_eq!(wallet1_info.total, 2 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, 2 * reward); + // check tx log as well + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 2); + Ok(()) + }, + )?; // Make a transaction by sending 5 coins from wallet1::account1 -> wallet2::account2 { @@ -92,18 +103,23 @@ fn contract_accounts_switch_impl(test_dir: &'static str) -> Result<(), libwallet let mut slate = Slate::blank(0, true); // this gets overriden below - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // Send wallet inititates a standard transaction with --send=5 - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-5_000_000_000), + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // Send wallet inititates a standard transaction with --send=5 + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-5_000_000_000), + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); // Receiver gets their coins on account2 where they can payjoin @@ -111,16 +127,21 @@ fn contract_accounts_switch_impl(test_dir: &'static str) -> Result<(), libwallet wallet_inst!(wallet2, w); w.set_parent_key_id_by_name("account2")?; } - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - // Receive wallet calls --receive=5 - let args = &mut ContractSetupArgsAPI { - net_change: Some(5_000_000_000), - ..Default::default() - }; - args.proof_args.suppress_proof = true; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + // Receive wallet calls --receive=5 + let args = &mut ContractSetupArgsAPI { + net_change: Some(5_000_000_000), + ..Default::default() + }; + args.proof_args.suppress_proof = true; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard2); // Switch account for wallet1 to account2 and finish the transaction (should use account1 to complete) @@ -128,72 +149,97 @@ fn contract_accounts_switch_impl(test_dir: &'static str) -> Result<(), libwallet wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account2")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = &ContractSetupArgsAPI { - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractSetupArgsAPI { + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard3); // post tx and mine a block to wallet1::account2 - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; // The currently set account (account2) should not be affected by this transaction because they weren't a part of it, // but it did mine a block and pick the transaction fees - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 11); - assert_eq!( - wallet1_info.total, - 3 * reward + core::libtx::tx_fee(2, 2, 1) // we have received a block reward and the tx fee (payjoin) - ); - assert_eq!(wallet1_info.amount_currently_spendable, 2 * reward); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 3); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 11); + assert_eq!( + wallet1_info.total, + 3 * reward + core::libtx::tx_fee(2, 2, 1) // we have received a block reward and the tx fee (payjoin) + ); + assert_eq!(wallet1_info.amount_currently_spendable, 2 * reward); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 3); + Ok(()) + }, + )?; // Switch to wallet1::account1 and check that it sent 5 coins { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 11); - assert_eq!( - wallet1_info.total, - 1 * reward - 5_000_000_000 - my_fee_contribution(1, 1, 1, 2)?.fee() // we subtract also our fee contribution - ); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 2); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 11); + assert_eq!( + wallet1_info.total, + 1 * reward - 5_000_000_000 - my_fee_contribution(1, 1, 1, 2)?.fee() // we subtract also our fee contribution + ); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 2); + Ok(()) + }, + )?; // Switch to wallet2::account2 and check that it received 5 coins { wallet_inst!(wallet2, w); w.set_parent_key_id_by_name("account2")?; } - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, 11); - assert_eq!( - wallet2_info.total, - 4 * reward + 5_000_000_000 - my_fee_contribution(1, 1, 1, 2)?.fee() // we subtract also our fee contribution for a payjoin - ); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 5); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 11); + assert_eq!( + wallet2_info.total, + 4 * reward + 5_000_000_000 - my_fee_contribution(1, 1, 1, 2)?.fee() // we subtract also our fee contribution for a payjoin + ); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(txs.len(), 5); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_early_lock.rs b/controller/tests/contract_early_lock.rs index fc6df93..85eb028 100644 --- a/controller/tests/contract_early_lock.rs +++ b/controller/tests/contract_early_lock.rs @@ -30,6 +30,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// contract new with --add-outputs fn contract_early_lock_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -40,51 +41,66 @@ fn contract_early_lock_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: let send_mask = wallets[0].1.as_ref(); // Confirm all our outputs are unspent - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, commits) = api.retrieve_outputs(m, true, false, None)?; - for commit in commits.iter() { - assert_eq!(commit.output.status, OutputStatus::Unspent); - } - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, commits) = api.retrieve_outputs(m, true, false, None)?; + for commit in commits.iter() { + assert_eq!(commit.output.status, OutputStatus::Unspent); + } + Ok(()) + }, + )?; let mut slate = Slate::blank(0, false); // this gets overriden below // Call contract 'new' with --add-outputs - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - // Send wallet inititates a standard transaction with --send=80 - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-80_000_000_000), - num_participants: 2, - add_outputs: true, + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + // Send wallet inititates a standard transaction with --send=80 + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-80_000_000_000), + num_participants: 2, + add_outputs: true, + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); // Assert we locked 2 inputs and prepared an unconfirmed change output - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, commits) = api.retrieve_outputs(m, true, false, None)?; - // we locked the first two coinbase outputs - assert_eq!(commits[0].output.status, OutputStatus::Locked); - assert_eq!(commits[1].output.status, OutputStatus::Locked); - // we added a new unconfirmed change output - let new_output_idx = commits.len() - 1; - assert_eq!( - commits[new_output_idx].output.status, - OutputStatus::Unconfirmed - ); - assert_eq!( - commits[new_output_idx].output.value, - 2 * consensus::REWARD - 80_000_000_000 - my_fee_contribution(2, 1, 1, 2)?.fee() - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, commits) = api.retrieve_outputs(m, true, false, None)?; + // we locked the first two coinbase outputs + assert_eq!(commits[0].output.status, OutputStatus::Locked); + assert_eq!(commits[1].output.status, OutputStatus::Locked); + // we added a new unconfirmed change output + let new_output_idx = commits.len() - 1; + assert_eq!( + commits[new_output_idx].output.status, + OutputStatus::Unconfirmed + ); + assert_eq!( + commits[new_output_idx].output.value, + 2 * consensus::REWARD - 80_000_000_000 - my_fee_contribution(2, 1, 1, 2)?.fee() + ); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_early_proofs_rsr.rs b/controller/tests/contract_early_proofs_rsr.rs index bb353a1..439195d 100644 --- a/controller/tests/contract_early_proofs_rsr.rs +++ b/controller/tests/contract_early_proofs_rsr.rs @@ -35,6 +35,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// Development + Tests of early payment proof functionality - RSR workflow fn contract_early_proofs_rsr_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -50,28 +51,38 @@ fn contract_early_proofs_rsr_test_impl(test_dir: &'static str) -> Result<(), lib let mut sender_address = None; // Get sender address explicitly - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - sender_address = Some(api.get_slatepack_address(send_mask, 0)?.pub_key); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + sender_address = Some(api.get_slatepack_address(send_mask, 0)?.pub_key); + Ok(()) + }, + )?; let mut recipient_address = None; - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - // Receive wallet (invoice) calls --receive=5 - let args = &mut ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(5_000_000_000), + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + // Receive wallet (invoice) calls --receive=5 + let args = &mut ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(5_000_000_000), + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - // Proofs are opt-in; enable and supply the sender address. - args.setup_args.proof_args.suppress_proof = false; - args.setup_args.proof_args.sender_address = sender_address; - slate = api.contract_new(m, args)?; - recipient_address = Some(api.get_slatepack_address(recv_mask, 0)?.pub_key); - Ok(()) - })?; + }; + // Proofs are opt-in; enable and supply the sender address. + args.setup_args.proof_args.suppress_proof = false; + args.setup_args.proof_args.sender_address = sender_address; + slate = api.contract_new(m, args)?; + recipient_address = Some(api.get_slatepack_address(recv_mask, 0)?.pub_key); + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice1); println!("I1 State slate: {}", slate); @@ -89,33 +100,48 @@ fn contract_early_proofs_rsr_test_impl(test_dir: &'static str) -> Result<(), lib let slate_unpacked = slate_packer.get_slate(&slate_packed).unwrap(); println!("I2 Slate unpacked: {}", slate_unpacked); - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - // Sending wallet (invoice) signs - let args = &ContractSetupArgsAPI { - net_change: Some(-5_000_000_000), - ..Default::default() - }; - slate = api.contract_sign(m, &slate_unpacked, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + // Sending wallet (invoice) signs + let args = &ContractSetupArgsAPI { + net_change: Some(-5_000_000_000), + ..Default::default() + }; + slate = api.contract_sign(m, &slate_unpacked, args)?; + Ok(()) + }, + )?; println!("I2 State slate: {}", slate); assert_eq!(slate.state, SlateState::Invoice2); // Send wallet finalizes and posts - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - let args = &ContractSetupArgsAPI { - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractSetupArgsAPI { + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice3); - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; bh += 1; let _ = @@ -123,52 +149,67 @@ fn contract_early_proofs_rsr_test_impl(test_dir: &'static str) -> Result<(), lib bh += 3; // Assert changes in receive wallet - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len(), 5); // 4 mined and 1 received - let tx_log = txs[4].clone(); - assert_eq!(tx_log.tx_type, TxLogEntryType::TxReceived); - assert_eq!(tx_log.amount_credited, 5_000_000_000); - assert_eq!(tx_log.amount_debited, 0); - assert_eq!(tx_log.num_inputs, 1); - assert_eq!(tx_log.num_outputs, 1); - let expected_fees_paid = Some(my_fee_contribution(1, 1, 1, 2)?); - assert_eq!(tx_log.fee, expected_fees_paid); - assert_eq!( - wallet_info.amount_currently_spendable, - 4 * 60_000_000_000 + 5_000_000_000 - expected_fees_paid.unwrap().fee() // we expect the balance of 4 mined blocks + 5 Grin - fees paid - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len(), 5); // 4 mined and 1 received + let tx_log = txs[4].clone(); + assert_eq!(tx_log.tx_type, TxLogEntryType::TxReceived); + assert_eq!(tx_log.amount_credited, 5_000_000_000); + assert_eq!(tx_log.amount_debited, 0); + assert_eq!(tx_log.num_inputs, 1); + assert_eq!(tx_log.num_outputs, 1); + let expected_fees_paid = Some(my_fee_contribution(1, 1, 1, 2)?); + assert_eq!(tx_log.fee, expected_fees_paid); + assert_eq!( + wallet_info.amount_currently_spendable, + 4 * 60_000_000_000 + 5_000_000_000 - expected_fees_paid.unwrap().fee() // we expect the balance of 4 mined blocks + 5 Grin - fees paid + ); + Ok(()) + }, + )?; // Assert changes in send wallet - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len() as u64, bh - 4 + 1); // send wallet didn't mine 4 blocks and made 1 tx - let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? - assert_eq!(tx_log.tx_type, TxLogEntryType::TxSent); - assert_eq!(tx_log.amount_credited, 0); - assert_eq!(tx_log.amount_debited, 5_000_000_000); - assert_eq!(tx_log.num_inputs, 1); - assert_eq!(tx_log.num_outputs, 1); - assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 2)?)); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len() as u64, bh - 4 + 1); // send wallet didn't mine 4 blocks and made 1 tx + let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? + assert_eq!(tx_log.tx_type, TxLogEntryType::TxSent); + assert_eq!(tx_log.amount_credited, 0); + assert_eq!(tx_log.amount_debited, 5_000_000_000); + assert_eq!(tx_log.num_inputs, 1); + assert_eq!(tx_log.num_outputs, 1); + assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 2)?)); + Ok(()) + }, + )?; let mut invoice_proof = None; // Now some time has passed, sender retrieves and verify the payment proof - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, _m| { - // Extract the stored data as an invoice proof - invoice_proof = - Some(api.retrieve_payment_proof_invoice(send_mask, true, None, Some(slate.id))?); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, _m| { + // Extract the stored data as an invoice proof + invoice_proof = + Some(api.retrieve_payment_proof_invoice(send_mask, true, None, Some(slate.id))?); + Ok(()) + }, + )?; let invoice_proof = invoice_proof.unwrap(); let invoice_proof_json = serde_json::to_string(&invoice_proof).unwrap(); @@ -176,15 +217,21 @@ fn contract_early_proofs_rsr_test_impl(test_dir: &'static str) -> Result<(), lib // Should have all proof fields filled out println!("INVOICE PROOF: {}", invoice_proof_json); - wallet::controller::foreign_single_use(recv_wallet.clone(), recv_mask.cloned(), |api| { - let mut proof = serde_json::from_str(&invoice_proof_json).unwrap(); - api.verify_payment_proof_invoice(recipient_address.as_ref().unwrap(), &proof)?; - // tweak something and it shouldn't verify - proof.amount = 400000; - let retval = api.verify_payment_proof_invoice(recipient_address.as_ref().unwrap(), &proof); - assert!(retval.is_err()); - Ok(()) - })?; + wallet::controller::foreign_single_use( + recv_wallet.clone(), + PathBuf::from(test_dir), + recv_mask.cloned(), + |api| { + let mut proof = serde_json::from_str(&invoice_proof_json).unwrap(); + api.verify_payment_proof_invoice(recipient_address.as_ref().unwrap(), &proof)?; + // tweak something and it shouldn't verify + proof.amount = 400000; + let retval = + api.verify_payment_proof_invoice(recipient_address.as_ref().unwrap(), &proof); + assert!(retval.is_err()); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_early_proofs_srs.rs b/controller/tests/contract_early_proofs_srs.rs index c84ad83..37faf0d 100644 --- a/controller/tests/contract_early_proofs_srs.rs +++ b/controller/tests/contract_early_proofs_srs.rs @@ -35,6 +35,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// Development + Tests of early payment proof functionality fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -49,53 +50,73 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib let mut slate = Slate::blank(0, true); // this gets overriden below let mut sender_address = None; - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - // Send wallet inititates a standard transaction with --send=5 - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-5_000_000_000), + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + // Send wallet inititates a standard transaction with --send=5 + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-5_000_000_000), + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - sender_address = Some(api.get_slatepack_address(send_mask, 0)?.pub_key); - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + sender_address = Some(api.get_slatepack_address(send_mask, 0)?.pub_key); + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); let mut recipient_address = None; - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - // Receive wallet calls --receive=5 - let args = &mut ContractSetupArgsAPI { - net_change: Some(5_000_000_000), - ..Default::default() - }; - // Proofs are opt-in; enable and supply the sender address. - args.proof_args.suppress_proof = false; - args.proof_args.sender_address = sender_address; - slate = api.contract_sign(m, &slate, args)?; - recipient_address = Some(api.get_slatepack_address(recv_mask, 0)?.pub_key); - Ok(()) - })?; + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + // Receive wallet calls --receive=5 + let args = &mut ContractSetupArgsAPI { + net_change: Some(5_000_000_000), + ..Default::default() + }; + // Proofs are opt-in; enable and supply the sender address. + args.proof_args.suppress_proof = false; + args.proof_args.sender_address = sender_address; + slate = api.contract_sign(m, &slate, args)?; + recipient_address = Some(api.get_slatepack_address(recv_mask, 0)?.pub_key); + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard2); // Send wallet finalizes and posts //let mut sender_part_sig = None; - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let args = &ContractSetupArgsAPI { - ..Default::default() - }; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractSetupArgsAPI { + ..Default::default() + }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard3); - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; bh += 1; let _ = @@ -103,52 +124,67 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib bh += 3; // Assert changes in receive wallet - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len(), 5); // 4 mined and 1 received - let tx_log = txs[4].clone(); - assert_eq!(tx_log.tx_type, TxLogEntryType::TxReceived); - assert_eq!(tx_log.amount_credited, 5_000_000_000); - assert_eq!(tx_log.amount_debited, 0); - assert_eq!(tx_log.num_inputs, 1); - assert_eq!(tx_log.num_outputs, 1); - let expected_fees_paid = Some(my_fee_contribution(1, 1, 1, 2)?); - assert_eq!(tx_log.fee, expected_fees_paid); - assert_eq!( - wallet_info.amount_currently_spendable, - 4 * 60_000_000_000 + 5_000_000_000 - expected_fees_paid.unwrap().fee() // we expect the balance of 4 mined blocks + 5 Grin - fees paid - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len(), 5); // 4 mined and 1 received + let tx_log = txs[4].clone(); + assert_eq!(tx_log.tx_type, TxLogEntryType::TxReceived); + assert_eq!(tx_log.amount_credited, 5_000_000_000); + assert_eq!(tx_log.amount_debited, 0); + assert_eq!(tx_log.num_inputs, 1); + assert_eq!(tx_log.num_outputs, 1); + let expected_fees_paid = Some(my_fee_contribution(1, 1, 1, 2)?); + assert_eq!(tx_log.fee, expected_fees_paid); + assert_eq!( + wallet_info.amount_currently_spendable, + 4 * 60_000_000_000 + 5_000_000_000 - expected_fees_paid.unwrap().fee() // we expect the balance of 4 mined blocks + 5 Grin - fees paid + ); + Ok(()) + }, + )?; // Assert changes in send wallet - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len() as u64, bh - 4 + 1); // send wallet didn't mine 4 blocks and made 1 tx - let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? - assert_eq!(tx_log.tx_type, TxLogEntryType::TxSent); - assert_eq!(tx_log.amount_credited, 0); - assert_eq!(tx_log.amount_debited, 5_000_000_000); - assert_eq!(tx_log.num_inputs, 1); - assert_eq!(tx_log.num_outputs, 1); - assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 2)?)); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len() as u64, bh - 4 + 1); // send wallet didn't mine 4 blocks and made 1 tx + let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? + assert_eq!(tx_log.tx_type, TxLogEntryType::TxSent); + assert_eq!(tx_log.amount_credited, 0); + assert_eq!(tx_log.amount_debited, 5_000_000_000); + assert_eq!(tx_log.num_inputs, 1); + assert_eq!(tx_log.num_outputs, 1); + assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 2)?)); + Ok(()) + }, + )?; let mut invoice_proof = None; // Now some time has passed, sender retrieves and verify the payment proof - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, _m| { - // Extract the stored data as an invoice proof - invoice_proof = - Some(api.retrieve_payment_proof_invoice(send_mask, true, None, Some(slate.id))?); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, _m| { + // Extract the stored data as an invoice proof + invoice_proof = + Some(api.retrieve_payment_proof_invoice(send_mask, true, None, Some(slate.id))?); + Ok(()) + }, + )?; let invoice_proof = invoice_proof.unwrap(); let invoice_proof_json = serde_json::to_string(&invoice_proof).unwrap(); @@ -156,15 +192,21 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib // Should have all proof fields filled out println!("INVOICE PROOF: {}", invoice_proof_json); - wallet::controller::foreign_single_use(recv_wallet.clone(), recv_mask.cloned(), |api| { - let mut proof = serde_json::from_str(&invoice_proof_json).unwrap(); - api.verify_payment_proof_invoice(recipient_address.as_ref().unwrap(), &proof)?; - // tweak something and it shouldn't verify - proof.amount = 400000; - let retval = api.verify_payment_proof_invoice(recipient_address.as_ref().unwrap(), &proof); - assert!(retval.is_err()); - Ok(()) - })?; + wallet::controller::foreign_single_use( + recv_wallet.clone(), + PathBuf::from(test_dir), + recv_mask.cloned(), + |api| { + let mut proof = serde_json::from_str(&invoice_proof_json).unwrap(); + api.verify_payment_proof_invoice(recipient_address.as_ref().unwrap(), &proof)?; + // tweak something and it shouldn't verify + proof.amount = 400000; + let retval = + api.verify_payment_proof_invoice(recipient_address.as_ref().unwrap(), &proof); + assert!(retval.is_err()); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_revoke.rs b/controller/tests/contract_revoke.rs index b03bfba..f7c151f 100644 --- a/controller/tests/contract_revoke.rs +++ b/controller/tests/contract_revoke.rs @@ -29,16 +29,14 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// Revoke a contract while a different account is active than the one that locked /// the inputs. The cancel + self-spend must still target the inputs' account. fn contract_revoke_other_account_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // One wallet: empty "default" account plus a funded "account1". - let (wallets, _chain, stopper, _bh) = create_wallets( - vec![vec![("default", 0), ("account1", 4)]], - test_dir, - ) - .unwrap(); + let (wallets, _chain, stopper, _bh) = + create_wallets(vec![vec![("default", 0), ("account1", 4)]], test_dir).unwrap(); let wallet1 = wallets[0].0.clone(); let mask1 = wallets[0].1.as_ref(); @@ -48,30 +46,40 @@ fn contract_revoke_other_account_impl(test_dir: &'static str) -> Result<(), libw w.set_parent_key_id_by_name("account1")?; } let mut slate = Slate::blank(0, true); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-1_000_000_000), - num_participants: 2, - add_outputs: true, + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-1_000_000_000), + num_participants: 2, + add_outputs: true, + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); // Grab the tx id and confirm an input is locked under account1. let mut tx_id = 0; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - tx_id = txs.last().unwrap().id; - let (_, outs) = api.retrieve_outputs(m, true, false, None)?; - assert!(outs.iter().any(|o| o.output.status == OutputStatus::Locked)); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + tx_id = txs.last().unwrap().id; + let (_, outs) = api.retrieve_outputs(m, true, false, None)?; + assert!(outs.iter().any(|o| o.output.status == OutputStatus::Locked)); + Ok(()) + }, + )?; // Switch the active account to "default" — different from the inputs' account. { @@ -82,31 +90,44 @@ fn contract_revoke_other_account_impl(test_dir: &'static str) -> Result<(), libw // Revoke. With the active account wrong, this must still cancel + self-spend the // account1 transaction (it derives the account from the locked input). let mut revoked = None; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - revoked = api.contract_revoke(m, &ContractRevokeArgsAPI { tx_id })?; - Ok(()) - })?; - assert!(revoked.is_some(), "revoke should produce a self-spend slate"); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + revoked = api.contract_revoke(m, &ContractRevokeArgsAPI { tx_id })?; + Ok(()) + }, + )?; + assert!( + revoked.is_some(), + "revoke should produce a self-spend slate" + ); // Back on account1: the original tx is cancelled and no input is left locked. { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let query = libwallet::RetrieveTxQueryArgs { - exclude_cancelled: Some(false), - ..Default::default() - }; - let (_, txs) = api.retrieve_txs(m, true, None, None, Some(query))?; - let tx = txs.iter().find(|t| t.id == tx_id).unwrap(); - assert!( - format!("{:?}", tx.tx_type).contains("Cancelled"), - "original tx should be cancelled, was {:?}", - tx.tx_type - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let query = libwallet::RetrieveTxQueryArgs { + exclude_cancelled: Some(false), + ..Default::default() + }; + let (_, txs) = api.retrieve_txs(m, true, None, None, Some(query))?; + let tx = txs.iter().find(|t| t.id == tx_id).unwrap(); + assert!( + format!("{:?}", tx.tx_type).contains("Cancelled"), + "original tx should be cancelled, was {:?}", + tx.tx_type + ); + Ok(()) + }, + )?; stopper.store(false, Ordering::Relaxed); thread::sleep(Duration::from_millis(200)); @@ -134,47 +155,67 @@ fn contract_revoke_resume_impl(test_dir: &'static str) -> Result<(), libwallet:: // Send (with early lock), locking an input under the contract tx. let mut slate = Slate::blank(0, true); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-1_000_000_000), - num_participants: 2, - add_outputs: true, + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-1_000_000_000), + num_participants: 2, + add_outputs: true, + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); let mut tx_id = 0; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - tx_id = txs.last().unwrap().id; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + tx_id = txs.last().unwrap().id; + Ok(()) + }, + )?; // Simulate a revoke that crashed right after cancelling: cancel the tx (inputs become // Unspent, still tagged with tx_id) but do NOT build the self-spend. - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.cancel_tx(m, Some(tx_id), None)?; - let (_, outs) = api.retrieve_outputs(m, true, false, None)?; - assert!( - outs.iter().any(|o| o.output.status == OutputStatus::Unspent - && o.output.tx_log_entry == Some(tx_id)), - "input should be Unspent but still tagged with the cancelled tx" - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.cancel_tx(m, Some(tx_id), None)?; + let (_, outs) = api.retrieve_outputs(m, true, false, None)?; + assert!( + outs.iter().any(|o| o.output.status == OutputStatus::Unspent + && o.output.tx_log_entry == Some(tx_id)), + "input should be Unspent but still tagged with the cancelled tx" + ); + Ok(()) + }, + )?; // Resume: revoke must still produce the self-spend from the now-Unspent input. let mut revoked = None; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - revoked = api.contract_revoke(m, &ContractRevokeArgsAPI { tx_id })?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + revoked = api.contract_revoke(m, &ContractRevokeArgsAPI { tx_id })?; + Ok(()) + }, + )?; assert!( revoked.is_some(), "interrupted revoke should resume and produce a self-spend slate" diff --git a/controller/tests/contract_rsr.rs b/controller/tests/contract_rsr.rs index f41270c..88a9ea5 100644 --- a/controller/tests/contract_rsr.rs +++ b/controller/tests/contract_rsr.rs @@ -30,6 +30,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// contract RSR flow fn contract_rsr_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -43,46 +44,66 @@ fn contract_rsr_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let mut slate = Slate::blank(0, true); // this gets overriden below - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - // Receive wallet inititates an invoice transaction with --receive=5 - let args = &mut ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(5_000_000_000), + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + // Receive wallet inititates an invoice transaction with --receive=5 + let args = &mut ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(5_000_000_000), + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice1); - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - // Send Wallet calls --send=5 - let args = &ContractSetupArgsAPI { - net_change: Some(-5_000_000_000), - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + // Send Wallet calls --send=5 + let args = &ContractSetupArgsAPI { + net_change: Some(-5_000_000_000), + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice2); // Receive wallet finalizes and posts - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - let args = &mut ContractSetupArgsAPI { - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + let args = &mut ContractSetupArgsAPI { + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice3); // Send wallet posts so receive wallet doesn't get the mined amount - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; bh += 1; let _ = @@ -90,48 +111,58 @@ fn contract_rsr_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> bh += 3; // Assert changes in receive wallet - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len(), 5); // 4 mined and 1 received - let tx_log = txs[4].clone(); - assert_eq!(tx_log.tx_type, TxLogEntryType::TxReceived); - assert_eq!(tx_log.amount_credited, 5_000_000_000); - assert_eq!(tx_log.amount_debited, 0); - assert_eq!(tx_log.num_inputs, 1); - assert_eq!(tx_log.num_outputs, 1); - let expected_fees_paid = Some(my_fee_contribution(1, 1, 1, 2)?); - assert_eq!(tx_log.fee, expected_fees_paid); - assert_eq!( - wallet_info.amount_currently_spendable, - 4 * 60_000_000_000 + 5_000_000_000 - expected_fees_paid.unwrap().fee() // we expect the balance of 4 mined blocks + 5 Grin - fees paid - ); - // println!("txlogentry: {:#?}", tx_log); - // println!("wallet info: {:#?}", wallet_info); - // let (validated, commits) = api.retrieve_outputs(m, true, false, Some(tx_log.id))?; - // println!("commits: {:#?}", commits); - // panic!("lala"); - Ok(()) - })?; + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len(), 5); // 4 mined and 1 received + let tx_log = txs[4].clone(); + assert_eq!(tx_log.tx_type, TxLogEntryType::TxReceived); + assert_eq!(tx_log.amount_credited, 5_000_000_000); + assert_eq!(tx_log.amount_debited, 0); + assert_eq!(tx_log.num_inputs, 1); + assert_eq!(tx_log.num_outputs, 1); + let expected_fees_paid = Some(my_fee_contribution(1, 1, 1, 2)?); + assert_eq!(tx_log.fee, expected_fees_paid); + assert_eq!( + wallet_info.amount_currently_spendable, + 4 * 60_000_000_000 + 5_000_000_000 - expected_fees_paid.unwrap().fee() // we expect the balance of 4 mined blocks + 5 Grin - fees paid + ); + // println!("txlogentry: {:#?}", tx_log); + // println!("wallet info: {:#?}", wallet_info); + // let (validated, commits) = api.retrieve_outputs(m, true, false, Some(tx_log.id))?; + // println!("commits: {:#?}", commits); + // panic!("lala"); + Ok(()) + }, + )?; // Assert changes in send wallet - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len() as u64, bh - 4 + 1); // send_wallet didn't mine 4 blocks and made 1 tx - let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? - assert_eq!(tx_log.tx_type, TxLogEntryType::TxSent); - assert_eq!(tx_log.amount_credited, 0); - assert_eq!(tx_log.amount_debited, 5_000_000_000); - assert_eq!(tx_log.num_inputs, 1); - assert_eq!(tx_log.num_outputs, 1); - assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 2)?)); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len() as u64, bh - 4 + 1); // send_wallet didn't mine 4 blocks and made 1 tx + let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? + assert_eq!(tx_log.tx_type, TxLogEntryType::TxSent); + assert_eq!(tx_log.amount_credited, 0); + assert_eq!(tx_log.amount_debited, 5_000_000_000); + assert_eq!(tx_log.num_inputs, 1); + assert_eq!(tx_log.num_outputs, 1); + assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 2)?)); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_self_spend.rs b/controller/tests/contract_self_spend.rs index bb90ce0..2909b6f 100644 --- a/controller/tests/contract_self_spend.rs +++ b/controller/tests/contract_self_spend.rs @@ -30,6 +30,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// contract self-spend flow fn contract_self_spend_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -41,36 +42,51 @@ fn contract_self_spend_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: let mut slate = Slate::blank(0, true); // this gets overriden below - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - // Send wallet inititates a standard transaction with --send=0 - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(0), - num_participants: 1, + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + // Send wallet inititates a standard transaction with --send=0 + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(0), + num_participants: 1, + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); // Send wallet finalizes and posts - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let args = &ContractSetupArgsAPI { - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractSetupArgsAPI { + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; // In the case of a self-spend, we just finish the slate when it's in the Standard2 state assert_eq!(slate.state, SlateState::Standard2); - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; bh += 1; let _ = @@ -78,21 +94,26 @@ fn contract_self_spend_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: bh += 3; // Assert changes in send wallet - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len() as u64, bh + 1); // send wallet didn't mine 4 blocks and made 1 tx - let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? - assert_eq!(tx_log.tx_type, TxLogEntryType::TxSelfSpend); - assert_eq!(tx_log.amount_credited, 0); - assert_eq!(tx_log.amount_debited, 0); - assert_eq!(tx_log.num_inputs, 1); - assert_eq!(tx_log.num_outputs, 1); - assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 1)?)); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len() as u64, bh + 1); // send wallet didn't mine 4 blocks and made 1 tx + let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? + assert_eq!(tx_log.tx_type, TxLogEntryType::TxSelfSpend); + assert_eq!(tx_log.amount_credited, 0); + assert_eq!(tx_log.amount_debited, 0); + assert_eq!(tx_log.num_inputs, 1); + assert_eq!(tx_log.num_outputs, 1); + assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 1)?)); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_self_spend_cancel.rs b/controller/tests/contract_self_spend_cancel.rs index dc242da..47515b0 100644 --- a/controller/tests/contract_self_spend_cancel.rs +++ b/controller/tests/contract_self_spend_cancel.rs @@ -30,6 +30,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// contract self-spend flow fn contract_self_spend_cancel_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -41,40 +42,55 @@ fn contract_self_spend_cancel_impl(test_dir: &'static str) -> Result<(), libwall let mut slate = Slate::blank(0, true); // this gets overriden below - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - // Send wallet initiates a standard transaction with --send=0 - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(0), - num_participants: 1, + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + // Send wallet initiates a standard transaction with --send=0 + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(0), + num_participants: 1, + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); // Send wallet finalizes and posts - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - api.cancel_tx(m, None, Some(slate.id))?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + api.cancel_tx(m, None, Some(slate.id))?; + Ok(()) + }, + )?; // Assert tx log has been cancelled - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let query_args = libwallet::RetrieveTxQueryArgs { - exclude_cancelled: Some(false), - ..Default::default() - }; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, Some(query_args))?; - assert!(refreshed); - assert_eq!(txs.len() as u64, 5); // send wallet didn't mine 4 blocks and made 1 tx - let tx_log = txs[4].clone(); // TODO: why -5 and not -4? - assert_eq!(tx_log.tx_type, TxLogEntryType::TxSelfSpendCancelled); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let query_args = libwallet::RetrieveTxQueryArgs { + exclude_cancelled: Some(false), + ..Default::default() + }; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, Some(query_args))?; + assert!(refreshed); + assert_eq!(txs.len() as u64, 5); // send wallet didn't mine 4 blocks and made 1 tx + let tx_log = txs[4].clone(); // TODO: why -5 and not -4? + assert_eq!(tx_log.tx_type, TxLogEntryType::TxSelfSpendCancelled); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_self_spend_custom.rs b/controller/tests/contract_self_spend_custom.rs index a080089..376911a 100644 --- a/controller/tests/contract_self_spend_custom.rs +++ b/controller/tests/contract_self_spend_custom.rs @@ -31,6 +31,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// contract self-spend flow with custom picked inputs and outputs fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -42,16 +43,21 @@ fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libw let mut use_inputs = String::from(""); - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, commits) = api.retrieve_outputs(m, true, false, None)?; - println!("OOOT: {:?}", commits[0].output); - use_inputs = format!( - "{},{}", - commits[0].output.commit.as_ref().unwrap(), - commits[1].output.commit.as_ref().unwrap() - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, commits) = api.retrieve_outputs(m, true, false, None)?; + println!("OOOT: {:?}", commits[0].output); + use_inputs = format!( + "{},{}", + commits[0].output.commit.as_ref().unwrap(), + commits[1].output.commit.as_ref().unwrap() + ); + Ok(()) + }, + )?; let mut slate = Slate::blank(0, true); // this gets overriden below @@ -67,37 +73,52 @@ fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libw 15 * consensus::GRIN_BASE, ]), }; - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - // Send wallet inititates a standard transaction with --send=0 - let args = &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(0), - num_participants: 1, - selection_args: selection_args.clone(), + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + // Send wallet inititates a standard transaction with --send=0 + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(0), + num_participants: 1, + selection_args: selection_args.clone(), + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); // Send wallet finalizes and posts - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let args = &ContractSetupArgsAPI { - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let args = &ContractSetupArgsAPI { + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; // In the case of a self-spend, we just finish the slate when it's in the Standard2 state assert_eq!(slate.state, SlateState::Standard2); - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; bh += 1; let _ = @@ -105,50 +126,60 @@ fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libw bh += 3; // Assert changes in send wallet - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len() as u64, bh + 1); // send wallet didn't mine 4 blocks and made 1 tx - let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? - assert_eq!(tx_log.tx_type, TxLogEntryType::TxSelfSpend); - assert_eq!(tx_log.amount_credited, 0); - assert_eq!(tx_log.amount_debited, 0); - assert_eq!(tx_log.num_inputs, 3); - assert_eq!(tx_log.num_outputs, 6); - assert_eq!(tx_log.fee, Some(my_fee_contribution(3, 6, 1, 1)?)); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len() as u64, bh + 1); // send wallet didn't mine 4 blocks and made 1 tx + let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? + assert_eq!(tx_log.tx_type, TxLogEntryType::TxSelfSpend); + assert_eq!(tx_log.amount_credited, 0); + assert_eq!(tx_log.amount_debited, 0); + assert_eq!(tx_log.num_inputs, 3); + assert_eq!(tx_log.num_outputs, 6); + assert_eq!(tx_log.fee, Some(my_fee_contribution(3, 6, 1, 1)?)); + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, commits) = api.retrieve_outputs(m, true, false, None)?; - // Assert used inputs are the ones we specified - let used_inputs = use_inputs.split(",").collect::>(); - assert_eq!(commits[0].output.status, OutputStatus::Spent); - assert_eq!(commits[0].output.commit.as_ref().unwrap(), used_inputs[0]); - assert_eq!(commits[1].output.status, OutputStatus::Spent); - assert_eq!(commits[1].output.commit.as_ref().unwrap(), used_inputs[1]); - assert_eq!(commits[2].output.status, OutputStatus::Spent); - // Assert expected outputs were created - // 88, 35, 3, 0.2, 15 and a change output - assert_eq!(commits[10].output.value, 88 * consensus::GRIN_BASE); - assert_eq!(commits[11].output.value, 35 * consensus::GRIN_BASE); - assert_eq!(commits[12].output.value, 3 * consensus::GRIN_BASE); - assert_eq!( - commits[13].output.value, - (0.2 * consensus::GRIN_BASE as f64) as u64 - ); - assert_eq!(commits[14].output.value, 15 * consensus::GRIN_BASE); - // change output is 3*reward - (88-35-3-0.2-15) - my_fees - assert_eq!( - commits[15].output.value, - 3 * consensus::REWARD - - selection_args.sum_output_amounts()? - - my_fee_contribution(3, 6, 1, 1)?.fee() - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, commits) = api.retrieve_outputs(m, true, false, None)?; + // Assert used inputs are the ones we specified + let used_inputs = use_inputs.split(",").collect::>(); + assert_eq!(commits[0].output.status, OutputStatus::Spent); + assert_eq!(commits[0].output.commit.as_ref().unwrap(), used_inputs[0]); + assert_eq!(commits[1].output.status, OutputStatus::Spent); + assert_eq!(commits[1].output.commit.as_ref().unwrap(), used_inputs[1]); + assert_eq!(commits[2].output.status, OutputStatus::Spent); + // Assert expected outputs were created + // 88, 35, 3, 0.2, 15 and a change output + assert_eq!(commits[10].output.value, 88 * consensus::GRIN_BASE); + assert_eq!(commits[11].output.value, 35 * consensus::GRIN_BASE); + assert_eq!(commits[12].output.value, 3 * consensus::GRIN_BASE); + assert_eq!( + commits[13].output.value, + (0.2 * consensus::GRIN_BASE as f64) as u64 + ); + assert_eq!(commits[14].output.value, 15 * consensus::GRIN_BASE); + // change output is 3*reward - (88-35-3-0.2-15) - my_fees + assert_eq!( + commits[15].output.value, + 3 * consensus::REWARD + - selection_args.sum_output_amounts()? + - my_fee_contribution(3, 6, 1, 1)?.fee() + ); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_srs.rs b/controller/tests/contract_srs.rs index a8bff12..51c4d00 100644 --- a/controller/tests/contract_srs.rs +++ b/controller/tests/contract_srs.rs @@ -30,6 +30,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// contract SRS flow fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -43,45 +44,65 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let mut slate = Slate::blank(0, true); // this gets overriden below - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - // Send wallet inititates a standard transaction with --send=5 - let args = &mut ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-5_000_000_000), + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + // Send wallet inititates a standard transaction with --send=5 + let args = &mut ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-5_000_000_000), + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - // Receive wallet calls --receive=5 - let args = &mut ContractSetupArgsAPI { - net_change: Some(5_000_000_000), - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + // Receive wallet calls --receive=5 + let args = &mut ContractSetupArgsAPI { + net_change: Some(5_000_000_000), + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard2); // Send wallet finalizes and posts - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let args = &mut ContractSetupArgsAPI { - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let args = &mut ContractSetupArgsAPI { + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard3); - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; bh += 1; let _ = @@ -89,43 +110,53 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> bh += 3; // Assert changes in receive wallet - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len(), 5); // 4 mined and 1 received - let tx_log = txs[4].clone(); - assert_eq!(tx_log.tx_type, TxLogEntryType::TxReceived); - assert_eq!(tx_log.amount_credited, 5_000_000_000); - assert_eq!(tx_log.amount_debited, 0); - assert_eq!(tx_log.num_inputs, 1); - assert_eq!(tx_log.num_outputs, 1); - let expected_fees_paid = Some(my_fee_contribution(1, 1, 1, 2)?); - assert_eq!(tx_log.fee, expected_fees_paid); - assert_eq!( - wallet_info.amount_currently_spendable, - 4 * 60_000_000_000 + 5_000_000_000 - expected_fees_paid.unwrap().fee() // we expect the balance of 4 mined blocks + 5 Grin - fees paid - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len(), 5); // 4 mined and 1 received + let tx_log = txs[4].clone(); + assert_eq!(tx_log.tx_type, TxLogEntryType::TxReceived); + assert_eq!(tx_log.amount_credited, 5_000_000_000); + assert_eq!(tx_log.amount_debited, 0); + assert_eq!(tx_log.num_inputs, 1); + assert_eq!(tx_log.num_outputs, 1); + let expected_fees_paid = Some(my_fee_contribution(1, 1, 1, 2)?); + assert_eq!(tx_log.fee, expected_fees_paid); + assert_eq!( + wallet_info.amount_currently_spendable, + 4 * 60_000_000_000 + 5_000_000_000 - expected_fees_paid.unwrap().fee() // we expect the balance of 4 mined blocks + 5 Grin - fees paid + ); + Ok(()) + }, + )?; // Assert changes in send wallet - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(wallet_info.last_confirmed_height, bh); - assert!(refreshed); - assert_eq!(txs.len() as u64, bh - 4 + 1); // send wallet didn't mine 4 blocks and made 1 tx - let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? - assert_eq!(tx_log.tx_type, TxLogEntryType::TxSent); - assert_eq!(tx_log.amount_credited, 0); - assert_eq!(tx_log.amount_debited, 5_000_000_000); - assert_eq!(tx_log.num_inputs, 1); - assert_eq!(tx_log.num_outputs, 1); - assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 2)?)); - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert_eq!(wallet_info.last_confirmed_height, bh); + assert!(refreshed); + assert_eq!(txs.len() as u64, bh - 4 + 1); // send wallet didn't mine 4 blocks and made 1 tx + let tx_log = txs[txs.len() - 5].clone(); // TODO: why -5 and not -4? + assert_eq!(tx_log.tx_type, TxLogEntryType::TxSent); + assert_eq!(tx_log.amount_credited, 0); + assert_eq!(tx_log.amount_debited, 5_000_000_000); + assert_eq!(tx_log.num_inputs, 1); + assert_eq!(tx_log.num_outputs, 1); + assert_eq!(tx_log.fee, Some(my_fee_contribution(1, 1, 1, 2)?)); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_srs_mwmixnet.rs b/controller/tests/contract_srs_mwmixnet.rs index 687db00..4b3962e 100644 --- a/controller/tests/contract_srs_mwmixnet.rs +++ b/controller/tests/contract_srs_mwmixnet.rs @@ -32,6 +32,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallets, setup}; +use std::path::PathBuf; /// contract SRS flow - just creating an mwixnet tx at the moment fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -45,47 +46,67 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: let mut slate = Slate::blank(0, true); // this gets overriden below - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - // Send wallet inititates a standard transaction with --send=5 - let args = &mut ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-5_000_000_000), + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + // Send wallet inititates a standard transaction with --send=5 + let args = &mut ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-5_000_000_000), + ..Default::default() + }, ..Default::default() - }, - ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - })?; + }; + slate = api.contract_new(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard1); - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - // Receive wallet calls --receive=5 - let args = &mut ContractSetupArgsAPI { - net_change: Some(5_000_000_000), - ..Default::default() - }; - args.proof_args.suppress_proof = true; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + // Receive wallet calls --receive=5 + let args = &mut ContractSetupArgsAPI { + net_change: Some(5_000_000_000), + ..Default::default() + }; + args.proof_args.suppress_proof = true; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard2); // Send wallet finalizes and posts - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - let args = &mut ContractSetupArgsAPI { - ..Default::default() - }; - args.proof_args.suppress_proof = true; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + let args = &mut ContractSetupArgsAPI { + ..Default::default() + }; + args.proof_args.suppress_proof = true; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Standard3); - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + send_wallet.clone(), + send_mask, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; bh += 1; let _ = @@ -93,44 +114,49 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: bh += 3; // Recipient wallet sends outputs to mwixnet - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { - let secp_locked = static_secp_instance(); - let secp = secp_locked.lock(); - let server_pubkey_str_1 = - "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332"; - let server_pubkey_str_2 = - "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e"; - let server_pubkey_str_3 = - "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; - let server_key_1 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap()) - .unwrap(); - let server_key_2 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap()) - .unwrap(); - let server_key_3 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap()) - .unwrap(); - let params = MixnetReqCreationParams { - server_keys: vec![server_key_1, server_key_2, server_key_3], - fee_per_hop: 50_000_000, - }; - let outputs = api.retrieve_outputs(recv_mask, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); + wallet::controller::owner_single_use( + recv_wallet.clone(), + recv_mask, + PathBuf::from(test_dir), + |api, m| { + let secp_locked = static_secp_instance(); + let secp = secp_locked.lock(); + let server_pubkey_str_1 = + "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332"; + let server_pubkey_str_2 = + "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e"; + let server_pubkey_str_3 = + "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; + let server_key_1 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap()) + .unwrap(); + let server_key_2 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap()) + .unwrap(); + let server_key_3 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap()) + .unwrap(); + let params = MixnetReqCreationParams { + server_keys: vec![server_key_1, server_key_2, server_key_3], + fee_per_hop: 50_000_000, + }; + let outputs = api.retrieve_outputs(recv_mask, false, false, None)?; + // get last output + let last_output = outputs.1[outputs.1.len() - 1].clone(); - let mwixnet_req = api.create_mwixnet_req(m, ¶ms, &last_output.commit, true)?; + let mwixnet_req = api.create_mwixnet_req(m, ¶ms, &last_output.commit, true)?; - println!("MWIXNET REQ: {:?}", mwixnet_req); + println!("MWIXNET REQ: {:?}", mwixnet_req); - // check output we created comsig for is indeed locked - let outputs = api.retrieve_outputs(recv_mask, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); - assert!(last_output.output.status == libwallet::OutputStatus::Locked); + // check output we created comsig for is indeed locked + let outputs = api.retrieve_outputs(recv_mask, false, false, None)?; + // get last output + let last_output = outputs.1[outputs.1.len() - 1].clone(); + assert!(last_output.output.status == libwallet::OutputStatus::Locked); - Ok(()) - })?; + Ok(()) + }, + )?; bh += 1; @@ -140,7 +166,7 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: bh += 3; // Assert changes in receive wallet - wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| { + wallet::controller::owner_single_use(recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), |api, m| { let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; assert_eq!(wallet_info.last_confirmed_height, bh); @@ -162,7 +188,7 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: })?; // Assert changes in send wallet - wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| { + wallet::controller::owner_single_use(send_wallet.clone(), send_mask, PathBuf::from(test_dir), |api, m| { let (_, wallet_info) = api.retrieve_summary_info(m, true, 1)?; let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; assert_eq!(wallet_info.last_confirmed_height, bh); diff --git a/controller/tests/file.rs b/controller/tests/file.rs index c6c4e1a..e313407 100644 --- a/controller/tests/file.rs +++ b/controller/tests/file.rs @@ -19,6 +19,7 @@ extern crate grin_wallet_impls as impls; use grin_core as core; use grin_wallet_libwallet as libwallet; +use std::path::PathBuf; use impls::test_framework::{self, LocalWalletClient}; use impls::{PathToSlate, SlateGetter as _, SlatePutter as _}; @@ -75,18 +76,28 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "mining")?; + api.create_account_path(m, "listener")?; + Ok(()) + }, + )?; // add some accounts - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "account1")?; + api.create_account_path(m, "account2")?; + Ok(()) + }, + )?; // Get some mining done { @@ -111,27 +122,32 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }; // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api.init_send_tx(m, args)?; + // output tx file + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; // Get some mining done { @@ -142,43 +158,63 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), let mut slate = PathToSlate((&send_file).into()).get_tx()?.0; // wallet 2 receives file, completes, sends file back - wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| { - slate = api.receive_tx(&slate, None, None)?; - PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; - Ok(()) - })?; + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + slate = api.receive_tx(&slate, None, None)?; + PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; + Ok(()) + }, + )?; // wallet 1 finalises and posts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let mut slate = PathToSlate(receive_file.into()).get_tx()?.0; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let mut slate = PathToSlate(receive_file.into()).get_tx()?.0; + slate = api.finalize_tx(m, &slate)?; + // Output final file for reference + PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; + api.post_tx(m, &slate, false)?; + bh += 1; + Ok(()) + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); + Ok(()) + }, + )?; // Check total in 'wallet 2' account - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * reward); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * reward); + Ok(()) + }, + )?; // Now other types of exchange, for reference // Invoice transaction @@ -197,43 +233,63 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), let mut slate = Slate::blank(2, true); - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let args = IssueInvoiceTxArgs { - amount: 1000000000, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let args = IssueInvoiceTxArgs { + amount: 1000000000, + ..Default::default() + }; + slate = api.issue_invoice_tx(m, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = PathToSlate((&send_file).into()).get_tx()?.0; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; - Ok(()) - })?; - wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| { - // Wallet 2 receives the invoice transaction - slate = PathToSlate((&receive_file).into()).get_tx()?.0; - slate = api.finalize_tx(&slate, false)?; - PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; - Ok(()) - })?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = PathToSlate((&send_file).into()).get_tx()?.0; + slate = api.process_invoice_tx(m, &slate, args)?; + api.tx_lock_outputs(m, &slate)?; + PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; + Ok(()) + }, + )?; + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + // Wallet 2 receives the invoice transaction + slate = PathToSlate((&receive_file).into()).get_tx()?.0; + slate = api.finalize_tx(&slate, false)?; + PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; + Ok(()) + }, + )?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; // Standard, with payment proof let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); @@ -251,46 +307,66 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }; let mut slate = Slate::blank(2, true); let mut address = None; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + address = Some(api.get_slatepack_address(m, 0)?); + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let slate = api.init_send_tx(m, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; - wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| { - slate = PathToSlate((&send_file).into()).get_tx()?.0; - slate = api.receive_tx(&slate, None, None)?; - PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; - Ok(()) - })?; + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + slate = PathToSlate((&send_file).into()).get_tx()?.0; + slate = api.receive_tx(&slate, None, None)?; + PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; + Ok(()) + }, + )?; // wallet 1 finalises and posts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - slate = PathToSlate(receive_file.into()).get_tx()?.0; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + slate = PathToSlate(receive_file.into()).get_tx()?.0; + slate = api.finalize_tx(m, &slate)?; + // Output final file for reference + PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; + api.post_tx(m, &slate, false)?; + bh += 1; + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index 2fe7d64..7acd8bf 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -19,6 +19,7 @@ extern crate grin_wallet_impls as impls; use grin_core as core; use grin_wallet_libwallet as libwallet; +use std::path::PathBuf; use impls::test_framework::{self, LocalWalletClient}; use libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate, SlateState}; @@ -71,11 +72,16 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "mining")?; + api.create_account_path(m, "listener")?; + Ok(()) + }, + )?; // Get some mining done { @@ -87,122 +93,167 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, _bh as usize, false); // Sanity check wallet 1 contents - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, _bh); - assert_eq!(wallet1_info.total, _bh * reward); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, _bh); + assert_eq!(wallet1_info.total, _bh * reward); + Ok(()) + }, + )?; let mut slate = Slate::blank(2, true); - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + // Wallet 2 inititates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api.issue_invoice_tx(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice1); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = api.process_invoice_tx(m, &slate, args)?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice2); // wallet 2 finalizes and posts - wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| { - // Wallet 2 receives the invoice transaction - slate = api.finalize_tx(&slate, false)?; - Ok(()) - })?; + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + // Wallet 2 receives the invoice transaction + slate = api.finalize_tx(&slate, false)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice3); // wallet 1 posts so wallet 2 doesn't get the mined amount - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; _bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); _bh += 3; // Check transaction log for wallet 2 - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (_, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert!(txs.len() == 1); - println!( - "last confirmed height: {}, bh: {}", - wallet2_info.last_confirmed_height, _bh - ); - assert!(refreshed); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert!(refreshed); + assert!(txs.len() == 1); + println!( + "last confirmed height: {}, bh: {}", + wallet2_info.last_confirmed_height, _bh + ); + assert!(refreshed); + Ok(()) + }, + )?; // Check transaction log for wallet 1, ensure only 1 entry // exists - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len() as u64, _bh + 1); - println!( - "Wallet 1: last confirmed height: {}, bh: {}", - wallet1_info.last_confirmed_height, _bh - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len() as u64, _bh + 1); + println!( + "Wallet 1: last confirmed height: {}, bh: {}", + wallet1_info.last_confirmed_height, _bh + ); + Ok(()) + }, + )?; // Test self-sending - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // Wallet 1 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - println!("Self invoice slate init: {}", slate); - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // Wallet 1 inititates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api.issue_invoice_tx(m, args)?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + println!("Self invoice slate init: {}", slate); + slate = api.process_invoice_tx(m, &slate, args)?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; println!("Self invoice slate after process: {}", slate); // wallet 1 finalizes and posts - wallet::controller::foreign_single_use(wallet1.clone(), mask1_i.clone(), |api| { - // Wallet 2 receives the invoice transaction - slate = api.finalize_tx(&slate, false)?; - Ok(()) - })?; + wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| { + // Wallet 2 receives the invoice transaction + slate = api.finalize_tx(&slate, false)?; + Ok(()) + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); //bh += 3; @@ -210,82 +261,107 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // As above, but use owner API to finalize let mut slate = Slate::blank(2, true); - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + // Wallet 2 inititates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api.issue_invoice_tx(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice1); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = api.process_invoice_tx(m, &slate, args)?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice2); // wallet 2 finalizes via owner API - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - // Wallet 2 receives the invoice transaction - slate = api.finalize_tx(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + // Wallet 2 receives the invoice transaction + slate = api.finalize_tx(m, &slate)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice3); // test that payee can only cancel once let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); _bh += 3; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + // Wallet 2 inititates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api.issue_invoice_tx(m, args)?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice1); let orig_slate = slate.clone(); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args.clone())?; - api.tx_lock_outputs(m, &slate)?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = api.process_invoice_tx(m, &slate, args.clone())?; + api.tx_lock_outputs(m, &slate)?; - // Wallet 1 cancels the invoice transaction - api.cancel_tx(m, None, Some(slate.id))?; + // Wallet 1 cancels the invoice transaction + api.cancel_tx(m, None, Some(slate.id))?; - // Wallet 1 attempts to repay again - let res = api.process_invoice_tx(m, &orig_slate, args); - assert!(res.is_err()); + // Wallet 1 attempts to repay again + let res = api.process_invoice_tx(m, &orig_slate, args); + assert!(res.is_err()); - Ok(()) - })?; + Ok(()) + }, + )?; assert_eq!(slate.state, SlateState::Invoice2); // let logging finish diff --git a/controller/tests/late_lock.rs b/controller/tests/late_lock.rs index b80cc8c..2d1ec29 100644 --- a/controller/tests/late_lock.rs +++ b/controller/tests/late_lock.rs @@ -20,6 +20,7 @@ extern crate grin_wallet_libwallet as libwallet; use self::libwallet::{InitTxArgs, Slate}; use impls::test_framework::{self, LocalWalletClient}; +use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -68,16 +69,26 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { }); // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.create_account_path(m, "mining")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "mining")?; + Ok(()) + }, + )?; // add some accounts - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - api.create_account_path(m, "account1")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "account1")?; + Ok(()) + }, + )?; // Get some mining done { @@ -94,52 +105,67 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let mut slate = Slate::blank(2, false); let amount = 100_000_000_000; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - late_lock: Some(true), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - println!("S1 SLATE: {}", slate_i); - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - println!("S2 SLATE: {}", slate); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + late_lock: Some(true), + ..Default::default() + }; + let slate_i = sender_api.init_send_tx(m, args)?; + println!("S1 SLATE: {}", slate_i); + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + println!("S2 SLATE: {}", slate); - // Note we don't call `tx_lock_outputs` on the sender side here, - // as the outputs will only be locked during finalization + // Note we don't call `tx_lock_outputs` on the sender side here, + // as the outputs will only be locked during finalization - slate = sender_api.finalize_tx(m, &slate)?; - println!("S3 SLATE: {}", slate); + slate = sender_api.finalize_tx(m, &slate)?; + println!("S3 SLATE: {}", slate); - // Now post tx to our node for inclusion in the next block. - sender_api.post_tx(m, &slate, true)?; + // Now post tx to our node for inclusion in the next block. + sender_api.post_tx(m, &slate, true)?; - Ok(()) - })?; + Ok(()) + }, + )?; test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false)?; // update/test contents of both accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - // Reward from mining 11 blocks, minus the amount sent. - // Note: We mined the block containing the tx, so fees are effectively refunded. - assert_eq!(560_000_000_000, wallet_info.amount_currently_spendable); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + // Reward from mining 11 blocks, minus the amount sent. + // Note: We mined the block containing the tx, so fees are effectively refunded. + assert_eq!(560_000_000_000, wallet_info.amount_currently_spendable); + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (wallet2_refreshed, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(amount, wallet_info.amount_currently_spendable); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(amount, wallet_info.amount_currently_spendable); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/mwixnet.rs b/controller/tests/mwixnet.rs index 0db537d..60e4bd8 100644 --- a/controller/tests/mwixnet.rs +++ b/controller/tests/mwixnet.rs @@ -20,6 +20,7 @@ extern crate grin_wallet_impls as impls; use grin_core as core; use grin_util as util; use grin_util::secp::key::SecretKey; +use std::path::PathBuf; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; @@ -64,11 +65,16 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "mining")?; + api.create_account_path(m, "listener")?; + Ok(()) + }, + )?; // Get some mining done { @@ -80,98 +86,123 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - api.tx_lock_outputs(m, &slate)?; - // Send directly to self - wallet::controller::foreign_single_use(wallet1.clone(), mask1_i.clone(), |api| { - slate = api.receive_tx(&slate, Some("listener"), None)?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api.init_send_tx(m, args)?; + api.tx_lock_outputs(m, &slate)?; + // Send directly to self + wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, Some("listener"), None)?; + Ok(()) + }, + )?; + slate = api.finalize_tx(m, &slate)?; + api.post_tx(m, &slate, false)?; // mines a block + bh += 1; Ok(()) - })?; - slate = api.finalize_tx(m, &slate)?; - api.post_tx(m, &slate, false)?; // mines a block - bh += 1; - Ok(()) - })?; + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); + Ok(()) + }, + )?; // Check total in 'listener' account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("listener")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, 2 * reward); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); + Ok(()) + }, + )?; // Recipient wallet creates a mwixnet request from the last output - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let secp_locked = util::static_secp_instance(); - let secp = secp_locked.lock(); - let server_pubkey_str_1 = - "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332"; - let server_pubkey_str_2 = - "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e"; - let server_pubkey_str_3 = - "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; - let server_key_1 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap()) - .unwrap(); - let server_key_2 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap()) - .unwrap(); - let server_key_3 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap()) - .unwrap(); - let params = MixnetReqCreationParams { - server_keys: vec![server_key_1, server_key_2, server_key_3], - fee_per_hop: 50_000_000, - }; - let outputs = api.retrieve_outputs(mask1, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let secp_locked = util::static_secp_instance(); + let secp = secp_locked.lock(); + let server_pubkey_str_1 = + "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332"; + let server_pubkey_str_2 = + "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e"; + let server_pubkey_str_3 = + "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; + let server_key_1 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap()) + .unwrap(); + let server_key_2 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap()) + .unwrap(); + let server_key_3 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap()) + .unwrap(); + let params = MixnetReqCreationParams { + server_keys: vec![server_key_1, server_key_2, server_key_3], + fee_per_hop: 50_000_000, + }; + let outputs = api.retrieve_outputs(mask1, false, false, None)?; + // get last output + let last_output = outputs.1[outputs.1.len() - 1].clone(); - let mwixnet_req = api.create_mwixnet_req(m, ¶ms, &last_output.commit, true)?; + let mwixnet_req = api.create_mwixnet_req(m, ¶ms, &last_output.commit, true)?; - println!("MWIXNET REQ: {:?}", mwixnet_req); + println!("MWIXNET REQ: {:?}", mwixnet_req); - // check output we created comsig for is indeed locked - let outputs = api.retrieve_outputs(mask1, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); - assert!(last_output.output.status == libwallet::OutputStatus::Locked); + // check output we created comsig for is indeed locked + let outputs = api.retrieve_outputs(mask1, false, false, None)?; + // get last output + let last_output = outputs.1[outputs.1.len() - 1].clone(); + assert!(last_output.output.status == libwallet::OutputStatus::Locked); - Ok(()) - })?; + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/no_change.rs b/controller/tests/no_change.rs index cefba91..aa1a56e 100644 --- a/controller/tests/no_change.rs +++ b/controller/tests/no_change.rs @@ -18,6 +18,7 @@ extern crate grin_wallet_controller as wallet; extern crate grin_wallet_impls as impls; use grin_core as core; +use std::path::PathBuf; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; @@ -78,122 +79,167 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // send a single block's worth of transactions with minimal strategy let mut slate = Slate::blank(2, false); let mut stored_excess = None; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: reward - fee, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - slate = api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate)?; - api.tx_lock_outputs(m, &slate)?; - slate = api.finalize_tx(m, &slate)?; - println!("Posted Slate: {:?}", slate); - stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = InitTxArgs { + src_acct_name: None, + amount: reward - fee, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + slate = api.init_send_tx(m, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate)?; + api.tx_lock_outputs(m, &slate)?; + slate = api.finalize_tx(m, &slate)?; + println!("Posted Slate: {:?}", slate); + stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; // ensure stored excess is correct in both wallets // Wallet 1 calculated the excess with the full slate // Wallet 2 only had the excess provided by // wallet 1 // Refresh and check transaction log for wallet 1 - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - let tx = txs[0].clone(); - println!("SIMPLE SEND - SENDING WALLET"); - println!("{:?}", tx); - println!(); - assert!(tx.confirmed); - assert_eq!(stored_excess, tx.kernel_excess); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; + assert!(refreshed); + let tx = txs[0].clone(); + println!("SIMPLE SEND - SENDING WALLET"); + println!("{:?}", tx); + println!(); + assert!(tx.confirmed); + assert_eq!(stored_excess, tx.kernel_excess); + Ok(()) + }, + )?; // Refresh and check transaction log for wallet 2 - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - let tx = txs[0].clone(); - println!("SIMPLE SEND - RECEIVING WALLET"); - println!("{:?}", tx); - println!(); - assert!(tx.confirmed); - assert_eq!(stored_excess, tx.kernel_excess); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; + assert!(refreshed); + let tx = txs[0].clone(); + println!("SIMPLE SEND - RECEIVING WALLET"); + println!("{:?}", tx); + println!(); + assert!(tx.confirmed); + assert_eq!(stored_excess, tx.kernel_excess); + Ok(()) + }, + )?; // ensure invoice TX works as well with no change - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward - fee, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + // Wallet 2 inititates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward - fee, + ..Default::default() + }; + slate = api.issue_invoice_tx(m, args)?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + slate = api.process_invoice_tx(m, &slate, args)?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; // wallet 2 finalizes and posts - wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| { - // Wallet 2 receives the invoice transaction - slate = api.finalize_tx(&slate, false)?; - Ok(()) - })?; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask1, None, |api, m| { - println!("Invoice Posted TX: {}", slate); - stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + // Wallet 2 receives the invoice transaction + slate = api.finalize_tx(&slate, false)?; + Ok(()) + }, + )?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + println!("Invoice Posted TX: {}", slate); + stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; // check wallet 2's version - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - for tx in txs { - stored_excess = tx.kernel_excess; - println!("Wallet 2: {:?}", tx); - println!(); - assert!(tx.confirmed); - assert_eq!(stored_excess, tx.kernel_excess); - } - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; + assert!(refreshed); + for tx in txs { + stored_excess = tx.kernel_excess; + println!("Wallet 2: {:?}", tx); + println!(); + assert!(tx.confirmed); + assert_eq!(stored_excess, tx.kernel_excess); + } + Ok(()) + }, + )?; // Refresh and check transaction log for wallet 1 - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - for tx in txs { - println!("Wallet 1: {:?}", tx); - println!(); - assert_eq!(stored_excess, tx.kernel_excess); - assert!(tx.confirmed); - } - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; + assert!(refreshed); + for tx in txs { + println!("Wallet 1: {:?}", tx); + println!(); + assert_eq!(stored_excess, tx.kernel_excess); + assert!(tx.confirmed); + } + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/payment_proofs.rs b/controller/tests/payment_proofs.rs index edb416f..651e486 100644 --- a/controller/tests/payment_proofs.rs +++ b/controller/tests/payment_proofs.rs @@ -21,6 +21,7 @@ extern crate grin_wallet_util; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; use libwallet::{InitTxArgs, Slate}; +use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -77,83 +78,98 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); let mut address = None; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + address = Some(api.get_slatepack_address(m, 0)?); + Ok(()) + }, + )?; println!("Public address is: {:?}", address); let amount = 60_000_000_000; let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let slate_i = sender_api.init_send_tx(m, args)?; - assert_eq!( - slate_i.payment_proof.as_ref().unwrap().receiver_address, - address.as_ref().unwrap().pub_key, - ); - println!( - "Sender addr: {:?}", - slate_i.payment_proof.as_ref().unwrap().sender_address - ); + assert_eq!( + slate_i.payment_proof.as_ref().unwrap().receiver_address, + address.as_ref().unwrap().pub_key, + ); + println!( + "Sender addr: {:?}", + slate_i.payment_proof.as_ref().unwrap().sender_address + ); - // Check we are creating a tx with kernel features 0 - // We will check this produces a Plain kernel later. - assert_eq!(0, slate.kernel_features); + // Check we are creating a tx with kernel features 0 + // We will check this produces a Plain kernel later. + assert_eq!(0, slate.kernel_features); - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + sender_api.tx_lock_outputs(m, &slate)?; - // Ensure what's stored in TX log for payment proof is correct - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(txs[0].payment_proof.is_some()); - let pp = txs[0].clone().payment_proof.unwrap(); - assert_eq!( - pp.receiver_address, - slate_i.payment_proof.as_ref().unwrap().receiver_address - ); - assert!(pp.receiver_signature.is_some()); - assert_eq!(pp.sender_address_path, 0); - assert_eq!(pp.sender_signature, None); + // Ensure what's stored in TX log for payment proof is correct + let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; + assert!(txs[0].payment_proof.is_some()); + let pp = txs[0].clone().payment_proof.unwrap(); + assert_eq!( + pp.receiver_address, + slate_i.payment_proof.as_ref().unwrap().receiver_address + ); + assert!(pp.receiver_signature.is_some()); + assert_eq!(pp.sender_address_path, 0); + assert_eq!(pp.sender_signature, None); - // check we should get an error at this point since proof is not complete - let pp = sender_api.retrieve_payment_proof(m, true, None, Some(slate.id)); - assert!(pp.is_err()); + // check we should get an error at this point since proof is not complete + let pp = sender_api.retrieve_payment_proof(m, true, None, Some(slate.id)); + assert!(pp.is_err()); - slate = sender_api.finalize_tx(m, &slate)?; - sender_api.post_tx(m, &slate, true)?; - Ok(()) - })?; + slate = sender_api.finalize_tx(m, &slate)?; + sender_api.post_tx(m, &slate, true)?; + Ok(()) + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // Check payment proof here - let mut pp = sender_api.retrieve_payment_proof(m, true, None, Some(slate.id))?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // Check payment proof here + let mut pp = sender_api.retrieve_payment_proof(m, true, None, Some(slate.id))?; - println!("Payment proof: {:?}", pp); + println!("Payment proof: {:?}", pp); - // verify, should be good - let res = sender_api.verify_payment_proof(m, &pp)?; - assert_eq!(res, (true, false)); + // verify, should be good + let res = sender_api.verify_payment_proof(m, &pp)?; + assert_eq!(res, (true, false)); - // Modify values, should not be good - pp.amount = 20; - let res = sender_api.verify_payment_proof(m, &pp); - assert!(res.is_err()); - Ok(()) - })?; + // Modify values, should not be good + pp.amount = 20; + let res = sender_api.verify_payment_proof(m, &pp); + assert!(res.is_err()); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/repost.rs b/controller/tests/repost.rs index 283164c..0718364 100644 --- a/controller/tests/repost.rs +++ b/controller/tests/repost.rs @@ -19,6 +19,7 @@ extern crate grin_wallet_impls as impls; extern crate grin_wallet_libwallet as libwallet; use grin_core as core; +use std::path::PathBuf; use self::libwallet::{InitTxArgs, Slate}; use impls::test_framework::{self, LocalWalletClient}; @@ -74,18 +75,28 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "mining")?; + api.create_account_path(m, "listener")?; + Ok(()) + }, + )?; // add some accounts - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "account1")?; + api.create_account_path(m, "account2")?; + Ok(()) + }, + )?; // Get some mining done { @@ -102,26 +113,31 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let mut slate = Slate::blank(2, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - PathToSlate((&send_file).into()).put_tx(&slate, false)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api.init_send_tx(m, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, false)?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; @@ -132,12 +148,17 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> w.set_parent_key_id_by_name("listener")?; } - wallet::controller::foreign_single_use(wallet1.clone(), mask1_i.clone(), |api| { - slate = PathToSlate((&send_file).into()).get_tx()?.0; - slate = api.receive_tx(&slate, None, None)?; - PathToSlate((&receive_file).into()).put_tx(&slate, false)?; - Ok(()) - })?; + wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| { + slate = PathToSlate((&send_file).into()).get_tx()?.0; + slate = api.receive_tx(&slate, None, None)?; + PathToSlate((&receive_file).into()).put_tx(&slate, false)?; + Ok(()) + }, + )?; // wallet 1 receives file to different account, completes { @@ -146,47 +167,67 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } // wallet 1 finalize - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - slate = PathToSlate((&receive_file).into()).get_tx()?.0; - slate = api.finalize_tx(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + slate = PathToSlate((&receive_file).into()).get_tx()?.0; + slate = api.finalize_tx(m, &slate)?; + Ok(()) + }, + )?; // Now repost from cached - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - println!("TXS[0]: {:?}", txs[0]); - let stored_tx = api.get_stored_tx(m, None, Some(&txs[0].tx_slate_id.unwrap()))?; - println!("Stored tx: {:?}", stored_tx); - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; + println!("TXS[0]: {:?}", txs[0]); + let stored_tx = api.get_stored_tx(m, None, Some(&txs[0].tx_slate_id.unwrap()))?; + println!("Stored tx: {:?}", stored_tx); + api.post_tx(m, &slate, false)?; + bh += 1; + Ok(()) + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // update/test contents of both accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); + Ok(()) + }, + )?; { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("listener")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * reward); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * reward); + Ok(()) + }, + )?; // as above, but syncronously { @@ -201,55 +242,75 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let mut slate = Slate::blank(2, false); let amount = 60_000_000_000; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = sender_api.init_send_tx(m, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + sender_api.tx_lock_outputs(m, &slate)?; + slate = sender_api.finalize_tx(m, &slate)?; + Ok(()) + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Now repost from cached - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let stored_tx_slate = api.get_stored_tx(m, Some(txs[0].id), None)?.unwrap(); - api.post_tx(m, &stored_tx_slate, false)?; - bh += 1; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; + let stored_tx_slate = api.get_stored_tx(m, Some(txs[0].id), None)?.unwrap(); + api.post_tx(m, &stored_tx_slate, false)?; + bh += 1; + Ok(()) + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // // update/test contents of both accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 4); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 4); + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * amount); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * amount); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/revert.rs b/controller/tests/revert.rs index 5286c85..ef5a887 100644 --- a/controller/tests/revert.rs +++ b/controller/tests/revert.rs @@ -31,6 +31,7 @@ use grin_wallet_libwallet as libwallet; use grin_wallet_libwallet::api_impl::types::InitTxArgs; use grin_wallet_libwallet::WalletInst; use log::error; +use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; @@ -104,13 +105,13 @@ fn revert( } }); - owner(Some(wallet1.clone()), mask1, None, |api, m| { + owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { api.create_account_path(m, "a")?; api.set_active_account(m, "a")?; Ok(()) })?; - owner(Some(wallet2.clone()), mask2, None, |api, m| { + owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { api.create_account_path(m, "b")?; api.set_active_account(m, "b")?; Ok(()) @@ -125,7 +126,7 @@ fn revert( award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false)?; // Sanity check contents - owner(Some(wallet1.clone()), mask1, None, |api, m| { + owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; assert!(refreshed); assert_eq!(info.last_confirmed_height, bh); @@ -140,7 +141,7 @@ fn revert( Ok(()) })?; - owner(Some(wallet2.clone()), mask2, None, |api, m| { + owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; assert!(refreshed); assert_eq!(info.last_confirmed_height, bh); @@ -155,7 +156,7 @@ fn revert( // Send some funds let mut tx = None; - owner(Some(wallet1.clone()), mask1, None, |api, m| { + owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { // send to send let args = InitTxArgs { src_acct_name: None, @@ -180,7 +181,7 @@ fn revert( let tx = tx.expect("tx from slate"); // Check funds have been received - owner(Some(wallet2.clone()), mask2, None, |api, m| { + owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; assert!(refreshed); assert_eq!(info.last_confirmed_height, bh); @@ -222,7 +223,7 @@ fn revert( let bh = bh + 1; // Check funds have been confirmed - owner(Some(wallet2.clone()), mask2, None, |api, m| { + owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; assert!(refreshed); assert_eq!(info.last_confirmed_height, bh); @@ -257,7 +258,7 @@ fn revert( let bh = bh + 1; // Check funds have been reverted - owner(Some(wallet2.clone()), mask2, None, |api, m| { + owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { api.scan(m, None, false)?; let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; assert!(refreshed); @@ -292,7 +293,7 @@ fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let bh = bh + 1; // Check funds have been confirmed again - owner(Some(wallet2.clone()), mask2, None, |api, m| { + owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; assert!(refreshed); assert_eq!(info.last_confirmed_height, bh); @@ -320,7 +321,7 @@ fn revert_cancel_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let mask2 = mask2_i.as_ref(); // Cancelling tx - owner(Some(wallet2.clone()), mask2, None, |api, m| { + owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { // Sanity check let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; assert!(refreshed); diff --git a/controller/tests/self_send.rs b/controller/tests/self_send.rs index 5fc6058..6cf572e 100644 --- a/controller/tests/self_send.rs +++ b/controller/tests/self_send.rs @@ -18,6 +18,7 @@ extern crate grin_wallet_controller as wallet; extern crate grin_wallet_impls as impls; use grin_core as core; +use std::path::PathBuf; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; @@ -62,11 +63,16 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "mining")?; + api.create_account_path(m, "listener")?; + Ok(()) + }, + )?; // Get some mining done { @@ -78,58 +84,78 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - api.tx_lock_outputs(m, &slate)?; - // Send directly to self - wallet::controller::foreign_single_use(wallet1.clone(), mask1_i.clone(), |api| { - slate = api.receive_tx(&slate, Some("listener"), None)?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api.init_send_tx(m, args)?; + api.tx_lock_outputs(m, &slate)?; + // Send directly to self + wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, Some("listener"), None)?; + Ok(()) + }, + )?; + slate = api.finalize_tx(m, &slate)?; + api.post_tx(m, &slate, false)?; // mines a block + bh += 1; Ok(()) - })?; - slate = api.finalize_tx(m, &slate)?; - api.post_tx(m, &slate, false)?; // mines a block - bh += 1; - Ok(()) - })?; + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); + Ok(()) + }, + )?; // Check total in 'listener' account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("listener")?; } - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, 2 * reward); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/self_send_cancel.rs b/controller/tests/self_send_cancel.rs index 3947dda..fbb83cf 100644 --- a/controller/tests/self_send_cancel.rs +++ b/controller/tests/self_send_cancel.rs @@ -29,6 +29,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use std::path::PathBuf; /// self send impl fn self_send_cancel_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -66,47 +67,62 @@ fn self_send_cancel_test_impl(test_dir: &'static str) -> Result<(), libwallet::E test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: None, - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - api.tx_lock_outputs(m, &slate)?; - // Send directly to self - wallet::controller::foreign_single_use(wallet1.clone(), mask1_i.clone(), |api| { - slate = api.receive_tx(&slate, None, None)?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: None, + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api.init_send_tx(m, args)?; + api.tx_lock_outputs(m, &slate)?; + // Send directly to self + wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, None, None)?; + Ok(()) + }, + )?; + // Now cancel the transaction + api.cancel_tx(mask1, None, Some(slate.id.clone()))?; + bh += 1; Ok(()) - })?; - // Now cancel the transaction - api.cancel_tx(mask1, None, Some(slate.id.clone()))?; - bh += 1; - Ok(()) - })?; + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let query = RetrieveTxQueryArgs { - include_outstanding_only: Some(true), - exclude_cancelled: Some(true), - ..Default::default() - }; - let txs = api.retrieve_txs(mask1, true, None, None, Some(query))?; - for tx in txs.1.iter() { - println!("Tx: {:?}", tx); - } - assert!(txs.1.is_empty()); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let query = RetrieveTxQueryArgs { + include_outstanding_only: Some(true), + exclude_cancelled: Some(true), + ..Default::default() + }; + let txs = api.retrieve_txs(mask1, true, None, None, Some(query))?; + for tx in txs.1.iter() { + println!("Tx: {:?}", tx); + } + assert!(txs.1.is_empty()); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/slatepack.rs b/controller/tests/slatepack.rs index d65ec53..cf2a7e1 100644 --- a/controller/tests/slatepack.rs +++ b/controller/tests/slatepack.rs @@ -19,6 +19,7 @@ extern crate grin_wallet_impls as impls; use grin_core as core; use grin_wallet_libwallet as libwallet; +use std::path::PathBuf; use impls::test_framework::{self, LocalWalletClient}; use impls::{PathToSlatepack, SlatePutter as _}; @@ -31,8 +32,8 @@ use grin_wallet_libwallet::{ SlatepackerArgs, }; -use ed25519_dalek::PublicKey as edDalekPublicKey; -use ed25519_dalek::SecretKey as edDalekSecretKey; +use ed25519_dalek::SigningKey as edDalekSecretKey; +use ed25519_dalek::VerifyingKey as edDalekPublicKey; #[macro_use] mod common; @@ -124,18 +125,28 @@ fn slatepack_exchange_test_impl( let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "mining")?; + api.create_account_path(m, "listener")?; + Ok(()) + }, + )?; // add some accounts - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "account1")?; + api.create_account_path(m, "account2")?; + Ok(()) + }, + )?; // Get some mining done { @@ -149,13 +160,18 @@ fn slatepack_exchange_test_impl( let (recipients_1, dec_key_1, sender_1) = match use_encryption { true => { let mut rec_address = SlatepackAddress::random(); - let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]).unwrap(); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - sec_key = api.get_slatepack_secret_key(m, 0)?; - let pub_key = edDalekPublicKey::from(&sec_key); - rec_address = SlatepackAddress::new(&pub_key); - Ok(()) - })?; + let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + sec_key = api.get_slatepack_secret_key(m, 0)?; + let pub_key = edDalekPublicKey::from(&sec_key); + rec_address = SlatepackAddress::new(&pub_key); + Ok(()) + }, + )?; ( vec![rec_address.clone()], Some(sec_key), @@ -168,13 +184,18 @@ fn slatepack_exchange_test_impl( let (recipients_2, dec_key_2, sender_2) = match use_encryption { true => { let mut rec_address = SlatepackAddress::random(); - let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]).unwrap(); - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - sec_key = api.get_slatepack_secret_key(m, 0)?; - let pub_key = edDalekPublicKey::from(&sec_key); - rec_address = SlatepackAddress::new(&pub_key); - Ok(()) - })?; + let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]); + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + sec_key = api.get_slatepack_secret_key(m, 0)?; + let pub_key = edDalekPublicKey::from(&sec_key); + rec_address = SlatepackAddress::new(&pub_key); + Ok(()) + }, + )?; ( vec![rec_address.clone()], Some(sec_key), @@ -197,34 +218,39 @@ fn slatepack_exchange_test_impl( ), }; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - output_slatepack( - &slate, - &send_file, - use_armored, - use_bin, - sender_1.clone(), - recipients_2.clone(), - )?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api.init_send_tx(m, args)?; + // output tx file + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_1.clone(), + recipients_2.clone(), + )?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; // Get some mining done { @@ -236,54 +262,75 @@ fn slatepack_exchange_test_impl( slate_from_packed(&send_file, use_armored, (&dec_key_2).as_ref())?; // wallet 2 receives file, completes, sends file back - wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| { - slate = api.receive_tx(&slate, None, None)?; - output_slatepack( - &slate, - &receive_file, - use_armored, - use_bin, - // re-encrypt for sender! - sender_2.clone(), - match slatepack.sender.clone() { - Some(s) => vec![s.clone()], - None => vec![], - }, - )?; - Ok(()) - })?; + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + slate = api.receive_tx(&slate, None, None)?; + output_slatepack( + &slate, + &receive_file, + use_armored, + use_bin, + // re-encrypt for sender! + sender_2.clone(), + match slatepack.sender.clone() { + Some(s) => vec![s.clone()], + None => vec![], + }, + )?; + Ok(()) + }, + )?; - // wallet 1 finalises and posts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, mut slate) = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - })?; + // wallet 1 finalizes and posts + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, mut slate) = + slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; + slate = api.finalize_tx(m, &slate)?; + // Output final file for reference + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + api.post_tx(m, &slate, false)?; + bh += 1; + Ok(()) + }, + )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); + Ok(()) + }, + )?; // Check total in 'wallet 2' account - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * reward); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * reward); + Ok(()) + }, + )?; // Now other types of exchange, for reference // Invoice transaction @@ -302,63 +349,83 @@ fn slatepack_exchange_test_impl( let mut slate = Slate::blank(2, true); - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let args = IssueInvoiceTxArgs { - amount: 1000000000, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - output_slatepack( - &slate, - &send_file, - use_armored, - use_bin, - sender_2.clone(), - recipients_1.clone(), - )?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let args = IssueInvoiceTxArgs { + amount: 1000000000, + ..Default::default() + }; + slate = api.issue_invoice_tx(m, args)?; + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_2.clone(), + recipients_1.clone(), + )?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let res = slate_from_packed(&send_file, use_armored, (&dec_key_1).as_ref())?; - slatepack = res.0; - slate = res.1; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - output_slatepack( - &slate, - &receive_file, - use_armored, - use_bin, - sender_1.clone(), - match slatepack.sender.clone() { - Some(s) => vec![s.clone()], - None => vec![], - }, - )?; - Ok(()) - })?; - wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| { - // Wallet 2 receives the invoice transaction - let res = slate_from_packed(&receive_file, use_armored, (&dec_key_2).as_ref())?; - slate = res.1; - slate = api.finalize_tx(&slate, false)?; - output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; - Ok(()) - })?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let res = slate_from_packed(&send_file, use_armored, (&dec_key_1).as_ref())?; + slatepack = res.0; + slate = res.1; + slate = api.process_invoice_tx(m, &slate, args)?; + api.tx_lock_outputs(m, &slate)?; + output_slatepack( + &slate, + &receive_file, + use_armored, + use_bin, + sender_1.clone(), + match slatepack.sender.clone() { + Some(s) => vec![s.clone()], + None => vec![], + }, + )?; + Ok(()) + }, + )?; + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + // Wallet 2 receives the invoice transaction + let res = slate_from_packed(&receive_file, use_armored, (&dec_key_2).as_ref())?; + slate = res.1; + slate = api.finalize_tx(&slate, false)?; + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + Ok(()) + }, + )?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; // Standard, with payment proof let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); @@ -377,66 +444,86 @@ fn slatepack_exchange_test_impl( let mut slate = Slate::blank(2, true); let mut address = None; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + address = Some(api.get_slatepack_address(m, 0)?); + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - output_slatepack( - &slate, - &send_file, - use_armored, - use_bin, - sender_1, - recipients_2.clone(), - )?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let slate = api.init_send_tx(m, args)?; + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_1, + recipients_2.clone(), + )?; + api.tx_lock_outputs(m, &slate)?; + Ok(()) + }, + )?; - wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| { - let res = slate_from_packed(&send_file, use_armored, (&dec_key_2).as_ref())?; - let slatepack = res.0; - slate = res.1; - slate = api.receive_tx(&slate, None, None)?; - output_slatepack( - &slate, - &receive_file, - use_armored, - use_bin, - sender_2, - match slatepack.sender { - Some(s) => vec![s.clone()], - None => vec![], - }, - )?; - Ok(()) - })?; + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + let res = slate_from_packed(&send_file, use_armored, (&dec_key_2).as_ref())?; + let slatepack = res.0; + slate = res.1; + slate = api.receive_tx(&slate, None, None)?; + output_slatepack( + &slate, + &receive_file, + use_armored, + use_bin, + sender_2, + match slatepack.sender { + Some(s) => vec![s.clone()], + None => vec![], + }, + )?; + Ok(()) + }, + )?; // wallet 1 finalises and posts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let res = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; - slate = res.1; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let res = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; + slate = res.1; + slate = api.finalize_tx(m, &slate)?; + // Output final file for reference + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + api.post_tx(m, &slate, false)?; + bh += 1; + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); @@ -481,27 +568,32 @@ fn slatepack_api_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // create an encrypted slatepack (just encrypted for self) - let enc_addr = api.get_slatepack_address(m, 0)?; - let slatepack = api.create_slatepack_message(m, &slate, Some(0), vec![enc_addr])?; - println!("{}", slatepack); - let slatepack_raw = api.decode_slatepack_message(m, slatepack.clone(), vec![0])?; - println!("{}", slatepack_raw); - let decoded_slate = api.slate_from_slatepack_message(m, slatepack, vec![0])?; - println!("{}", decoded_slate); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api.init_send_tx(m, args)?; + // create an encrypted slatepack (just encrypted for self) + let enc_addr = api.get_slatepack_address(m, 0)?; + let slatepack = api.create_slatepack_message(m, &slate, Some(0), vec![enc_addr])?; + println!("{}", slatepack); + let slatepack_raw = api.decode_slatepack_message(m, slatepack.clone(), vec![0])?; + println!("{}", slatepack_raw); + let decoded_slate = api.slate_from_slatepack_message(m, slatepack, vec![0])?; + println!("{}", decoded_slate); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/transaction.rs b/controller/tests/transaction.rs index 33db4c9..55734dc 100644 --- a/controller/tests/transaction.rs +++ b/controller/tests/transaction.rs @@ -25,6 +25,7 @@ use self::core::global; use self::libwallet::{InitTxArgs, OutputStatus, Slate, SlateState}; use impls::test_framework::{self, LocalWalletClient}; use std::convert::TryInto; +use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -80,320 +81,390 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false); // Check wallet 1 contents are as expected - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", - wallet1_info.last_confirmed_height, wallet1_info - ); - assert!(wallet1_refreshed); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - ); - assert_eq!(wallet1_info.amount_immature, cm * reward); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + debug!( + "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", + wallet1_info.last_confirmed_height, wallet1_info + ); + assert!(wallet1_refreshed); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward + ); + assert_eq!(wallet1_info.amount_immature, cm * reward); + Ok(()) + }, + )?; // assert wallet contents // and a single use api for a send command let amount = 60_000_000_000; let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = sender_api.init_send_tx(m, args)?; - assert_eq!(slate_i.state, SlateState::Standard1); + assert_eq!(slate_i.state, SlateState::Standard1); - // Check we are creating a tx with the expected lock_height of 0. - // We will check this produces a Plain kernel later. - assert_eq!(0, slate.kernel_features); + // Check we are creating a tx with the expected lock_height of 0. + // We will check this produces a Plain kernel later. + assert_eq!(0, slate.kernel_features); - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - assert_eq!(slate.state, SlateState::Standard2); - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - assert_eq!(slate.state, SlateState::Standard3); + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + assert_eq!(slate.state, SlateState::Standard2); + sender_api.tx_lock_outputs(m, &slate)?; + slate = sender_api.finalize_tx(m, &slate)?; + assert_eq!(slate.state, SlateState::Standard3); - // Check we have a single kernel and that it is a Plain kernel (no lock_height). - // fees for 7 inputs, 2 outputs, 1 kernel (weight 52) - assert_eq!(slate.tx_or_err()?.kernels().len(), 1); - assert_eq!( - slate - .tx_or_err()? - .kernels() - .first() - .map(|k| k.features) - .unwrap(), - transaction::KernelFeatures::Plain { - fee: 26_000_000.into() - } - ); + // Check we have a single kernel and that it is a Plain kernel (no lock_height). + // fees for 7 inputs, 2 outputs, 1 kernel (weight 52) + assert_eq!(slate.tx_or_err()?.kernels().len(), 1); + assert_eq!( + slate + .tx_or_err()? + .kernels() + .first() + .map(|k| k.features) + .unwrap(), + transaction::KernelFeatures::Plain { + fee: 26_000_000.into() + } + ); - Ok(()) - })?; + Ok(()) + }, + )?; // Check transaction log for wallet 1 - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let fee = core::libtx::tx_fee( - wallet1_info.last_confirmed_height as usize - cm as usize, - 2, - 1, - ); - // we should have a transaction entry for this slate - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(!tx.confirmed); - assert!(tx.confirmation_ts.is_none()); - assert_eq!(tx.amount_debited - tx.amount_credited, fee + amount); - println!("tx: {:?}", tx); - assert_eq!(Some(fee.try_into().unwrap()), tx.fee); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert!(refreshed); + let fee = core::libtx::tx_fee( + wallet1_info.last_confirmed_height as usize - cm as usize, + 2, + 1, + ); + // we should have a transaction entry for this slate + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(!tx.confirmed); + assert!(tx.confirmation_ts.is_none()); + assert_eq!(tx.amount_debited - tx.amount_credited, fee + amount); + println!("tx: {:?}", tx); + assert_eq!(Some(fee.try_into().unwrap()), tx.fee); + Ok(()) + }, + )?; // Check transaction log for wallet 2 - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - // we should have a transaction entry for this slate - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(!tx.confirmed); - assert!(tx.confirmation_ts.is_none()); - assert_eq!(amount, tx.amount_credited); - assert_eq!(0, tx.amount_debited); - assert_eq!(None, tx.fee); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert!(refreshed); + // we should have a transaction entry for this slate + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(!tx.confirmed); + assert!(tx.confirmation_ts.is_none()); + assert_eq!(amount, tx.amount_credited); + assert_eq!(0, tx.amount_debited); + assert_eq!(None, tx.fee); + Ok(()) + }, + )?; // post transaction - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.post_tx(m, &slate, false)?; + Ok(()) + }, + )?; // Check wallet 1 contents are as expected - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 Info Post Transaction, after {} blocks: {:?}", - wallet1_info.last_confirmed_height, wallet1_info - ); - let fee = core::libtx::tx_fee( - wallet1_info.last_confirmed_height as usize - 1 - cm as usize, - 2, - 1, - ); - assert!(wallet1_refreshed); - // wallet 1 received fees, so amount should be the same - assert_eq!( - wallet1_info.total, - amount * wallet1_info.last_confirmed_height - amount - ); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - amount - fee - ); - assert_eq!(wallet1_info.amount_immature, cm * reward + fee); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + debug!( + "Wallet 1 Info Post Transaction, after {} blocks: {:?}", + wallet1_info.last_confirmed_height, wallet1_info + ); + let fee = core::libtx::tx_fee( + wallet1_info.last_confirmed_height as usize - 1 - cm as usize, + 2, + 1, + ); + assert!(wallet1_refreshed); + // wallet 1 received fees, so amount should be the same + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount + ); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward - amount - fee + ); + assert_eq!(wallet1_info.amount_immature, cm * reward + fee); - // check tx log entry is confirmed - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(tx.confirmed); - assert!(tx.confirmation_ts.is_some()); + // check tx log entry is confirmed + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert!(refreshed); + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(tx.confirmed); + assert!(tx.confirmation_ts.is_some()); - Ok(()) - })?; + Ok(()) + }, + )?; // mine a few more blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); // refresh wallets and retrieve info/tests for each wallet after maturity - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!("Wallet 1 Info: {:?}", wallet1_info); - assert!(wallet1_refreshed); - assert_eq!( - wallet1_info.total, - amount * wallet1_info.last_confirmed_height - amount - ); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm - 1) * reward - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + debug!("Wallet 1 Info: {:?}", wallet1_info); + assert!(wallet1_refreshed); + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount + ); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm - 1) * reward + ); + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.amount_currently_spendable, amount); + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, amount); - // check tx log entry is confirmed - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(tx.confirmed); - assert!(tx.confirmation_ts.is_some()); - Ok(()) - })?; + // check tx log entry is confirmed + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert!(refreshed); + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(tx.confirmed); + assert!(tx.confirmation_ts.is_some()); + Ok(()) + }, + )?; // Estimate fee and locked amount for a transaction - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - let init_args = InitTxArgs { - src_acct_name: None, - amount: amount * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - estimate_only: Some(true), - ..Default::default() - }; - let est = sender_api.init_send_tx(m, init_args)?; - assert_eq!(est.amount, 600_000_000_000); - // fees for 5 inputs, 2 outputs, 1 kernel (weight 50) - assert_eq!(est.fee_fields.fee(), 25_000_000); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + let init_args = InitTxArgs { + src_acct_name: None, + amount: amount * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + estimate_only: Some(true), + ..Default::default() + }; + let est = sender_api.init_send_tx(m, init_args)?; + assert_eq!(est.amount, 600_000_000_000); + // fees for 5 inputs, 2 outputs, 1 kernel (weight 50) + assert_eq!(est.fee_fields.fee(), 25_000_000); - let init_args = InitTxArgs { - src_acct_name: None, - amount: amount * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, //select smallest number - estimate_only: Some(true), - ..Default::default() - }; - let est = sender_api.init_send_tx(m, init_args)?; - assert_eq!(est.amount, 180_000_000_000); - // fees for 3 inputs, 2 outputs, 1 kernel (weight 48) - assert_eq!(est.fee_fields.fee(), 24_000_000); + let init_args = InitTxArgs { + src_acct_name: None, + amount: amount * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, //select smallest number + estimate_only: Some(true), + ..Default::default() + }; + let est = sender_api.init_send_tx(m, init_args)?; + assert_eq!(est.amount, 180_000_000_000); + // fees for 3 inputs, 2 outputs, 1 kernel (weight 48) + assert_eq!(est.fee_fields.fee(), 24_000_000); - Ok(()) - })?; + Ok(()) + }, + )?; // Send another transaction, but don't post to chain immediately and use // the stored transaction instead - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: amount * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = sender_api.init_send_tx(m, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + sender_api.tx_lock_outputs(m, &slate)?; + slate = sender_api.finalize_tx(m, &slate)?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - let (refreshed, _wallet1_info) = sender_api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - let (_, txs) = sender_api.retrieve_txs(m, true, None, None, None)?; - // find the transaction - let tx = txs - .iter() - .find(|t| t.tx_slate_id == Some(slate.id)) - .unwrap(); - let stored_tx_slate = sender_api - .get_stored_tx(m, None, Some(&tx.tx_slate_id.unwrap()))? - .unwrap(); - sender_api.post_tx(m, &stored_tx_slate, false)?; - let (_, wallet1_info) = sender_api.retrieve_summary_info(m, true, 1)?; - // should be mined now - assert_eq!( - wallet1_info.total, - amount * wallet1_info.last_confirmed_height - amount * 3 - ); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + let (refreshed, _wallet1_info) = sender_api.retrieve_summary_info(m, true, 1)?; + assert!(refreshed); + let (_, txs) = sender_api.retrieve_txs(m, true, None, None, None)?; + // find the transaction + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + let stored_tx_slate = sender_api + .get_stored_tx(m, None, Some(&tx.tx_slate_id.unwrap()))? + .unwrap(); + sender_api.post_tx(m, &stored_tx_slate, false)?; + let (_, wallet1_info) = sender_api.retrieve_summary_info(m, true, 1)?; + // should be mined now + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount * 3 + ); + Ok(()) + }, + )?; // mine a few more blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); // check wallet2 has stored transaction - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.amount_currently_spendable, amount * 3); + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, amount * 3); - // check tx log entry is confirmed - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(tx.confirmed); - assert!(tx.confirmation_ts.is_some()); - Ok(()) - })?; + // check tx log entry is confirmed + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert!(refreshed); + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(tx.confirmed); + assert!(tx.confirmation_ts.is_some()); + Ok(()) + }, + )?; // try to send a transaction with amount inclusive of fees, but amount too // small to cover fees. Should fail. - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: 1, - amount_includes_fee: Some(true), - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let res = sender_api.init_send_tx(m, args); - assert!(res.is_err()); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: 1, + amount_includes_fee: Some(true), + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let res = sender_api.init_send_tx(m, args); + assert!(res.is_err()); + Ok(()) + }, + )?; // try to build a transaction with amount inclusive of fees. Confirm that tx // amount + fee is equal to the originally specified amount let amount = 60_000_000_000; - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - amount_includes_fee: Some(true), - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - assert_eq!(slate_i.state, SlateState::Standard1); - let total_spend: u64 = slate_i.amount + slate_i.fee_fields.fee(); - assert_eq!(amount, total_spend); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: amount, + amount_includes_fee: Some(true), + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = sender_api.init_send_tx(m, args)?; + assert_eq!(slate_i.state, SlateState::Standard1); + let total_spend: u64 = slate_i.amount + slate_i.fee_fields.fee(); + assert_eq!(amount, total_spend); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); @@ -447,132 +518,158 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { let amount = 30_000_000_000; let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - })?; + let slate_i = sender_api.init_send_tx(m, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + sender_api.tx_lock_outputs(m, &slate)?; + slate = sender_api.finalize_tx(m, &slate)?; + Ok(()) + }, + )?; // Check transaction log for wallet 1 - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - println!( - "last confirmed height: {}", - wallet1_info.last_confirmed_height - ); - assert!(refreshed); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - // we should have a transaction entry for this slate - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let mut locked_count = 0; - let mut unconfirmed_count = 0; - // get the tx entry, check outputs are as expected - let (_, output_mappings) = api.retrieve_outputs(m, true, false, Some(tx.unwrap().id))?; - for m in output_mappings.clone() { - if m.output.status == OutputStatus::Locked { - locked_count = locked_count + 1; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + println!( + "last confirmed height: {}", + wallet1_info.last_confirmed_height + ); + assert!(refreshed); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + // we should have a transaction entry for this slate + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let mut locked_count = 0; + let mut unconfirmed_count = 0; + // get the tx entry, check outputs are as expected + let (_, output_mappings) = + api.retrieve_outputs(m, true, false, Some(tx.unwrap().id))?; + for m in output_mappings.clone() { + if m.output.status == OutputStatus::Locked { + locked_count = locked_count + 1; + } + if m.output.status == OutputStatus::Unconfirmed { + unconfirmed_count = unconfirmed_count + 1; + } } - if m.output.status == OutputStatus::Unconfirmed { - unconfirmed_count = unconfirmed_count + 1; - } - } - assert_eq!(output_mappings.len(), 3); - assert_eq!(locked_count, 2); - assert_eq!(unconfirmed_count, 1); + assert_eq!(output_mappings.len(), 3); + assert_eq!(locked_count, 2); + assert_eq!(unconfirmed_count, 1); - Ok(()) - })?; + Ok(()) + }, + )?; // Check transaction log for wallet 2 - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let mut unconfirmed_count = 0; - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - // get the tx entry, check outputs are as expected - let (_, outputs) = api.retrieve_outputs(m, true, false, Some(tx.unwrap().id))?; - for m in outputs.clone() { - if m.output.status == OutputStatus::Unconfirmed { - unconfirmed_count = unconfirmed_count + 1; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; + assert!(refreshed); + let mut unconfirmed_count = 0; + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + // get the tx entry, check outputs are as expected + let (_, outputs) = api.retrieve_outputs(m, true, false, Some(tx.unwrap().id))?; + for m in outputs.clone() { + if m.output.status == OutputStatus::Unconfirmed { + unconfirmed_count = unconfirmed_count + 1; + } } - } - assert_eq!(outputs.len(), 1); - assert_eq!(unconfirmed_count, 1); - let (refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - assert_eq!(wallet2_info.amount_awaiting_finalization, amount); - Ok(()) - })?; + assert_eq!(outputs.len(), 1); + assert_eq!(unconfirmed_count, 1); + let (refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + assert_eq!(wallet2_info.amount_awaiting_finalization, amount); + Ok(()) + }, + )?; // wallet 1 is bold and doesn't ever post the transaction // mine a few more blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); // Wallet 1 decides to roll back instead - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - // can't roll back coinbase - let res = api.cancel_tx(m, Some(1), None); - assert!(res.is_err()); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let tx = txs - .iter() - .find(|t| t.tx_slate_id == Some(slate.id)) - .unwrap(); - api.cancel_tx(m, Some(tx.id), None)?; - let (refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - println!( - "last confirmed height: {}", - wallet1_info.last_confirmed_height - ); - // check all eligible inputs should be now be spendable - println!("cm: {}", cm); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - ); - // can't roll back again - let res = api.cancel_tx(m, Some(tx.id), None); - assert!(res.is_err()); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + // can't roll back coinbase + let res = api.cancel_tx(m, Some(1), None); + assert!(res.is_err()); + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + api.cancel_tx(m, Some(tx.id), None)?; + let (refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(refreshed); + println!( + "last confirmed height: {}", + wallet1_info.last_confirmed_height + ); + // check all eligible inputs should be now be spendable + println!("cm: {}", cm); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward + ); + // can't roll back again + let res = api.cancel_tx(m, Some(tx.id), None); + assert!(res.is_err()); - Ok(()) - })?; + Ok(()) + }, + )?; // Wallet 2 rolls back - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let tx = txs - .iter() - .find(|t| t.tx_slate_id == Some(slate.id)) - .unwrap(); - api.cancel_tx(m, Some(tx.id), None)?; - let (refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - // check all eligible inputs should be now be spendable - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - assert_eq!(wallet2_info.total, 0,); - // can't roll back again - let res = api.cancel_tx(m, Some(tx.id), None); - assert!(res.is_err()); + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + api.cancel_tx(m, Some(tx.id), None)?; + let (refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; + assert!(refreshed); + // check all eligible inputs should be now be spendable + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + assert_eq!(wallet2_info.total, 0,); + // can't roll back again + let res = api.cancel_tx(m, Some(tx.id), None); + assert!(res.is_err()); - Ok(()) - })?; + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/ttl_cutoff.rs b/controller/tests/ttl_cutoff.rs index ec4340b..faa3990 100644 --- a/controller/tests/ttl_cutoff.rs +++ b/controller/tests/ttl_cutoff.rs @@ -21,6 +21,7 @@ extern crate grin_wallet_util; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; use libwallet::{InitTxArgs, Slate, TxLogEntryType}; +use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -78,95 +79,125 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let amount = 60_000_000_000; let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ttl_blocks: Some(2), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ttl_blocks: Some(2), + ..Default::default() + }; + let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + sender_api.tx_lock_outputs(m, &slate)?; - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - Ok(()) - })?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); + Ok(()) + }, + )?; // Now mine past the block, and check again. Transaction should be gone. let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - assert!(tx.tx_type == TxLogEntryType::TxSentCancelled); - Ok(()) - })?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); + assert_eq!(tx.tx_type, TxLogEntryType::TxSentCancelled); + Ok(()) + }, + )?; // Should also be gone in wallet 2, and output gone - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |sender_api, m| { - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); - let outputs = sender_api.retrieve_outputs(m, false, true, None)?.1; - assert_eq!(outputs.len(), 0); + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |sender_api, m| { + let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); + let outputs = sender_api.retrieve_outputs(m, false, true, None)?.1; + assert_eq!(outputs.len(), 0); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - assert!(tx.tx_type == TxLogEntryType::TxReceivedCancelled); - Ok(()) - })?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); + assert_eq!(tx.tx_type, TxLogEntryType::TxReceivedCancelled); + Ok(()) + }, + )?; // try again, except try and send off the transaction for completion beyond the expiry let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ttl_blocks: Some(2), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - sender_api.tx_lock_outputs(m, &slate_i)?; - slate = slate_i; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ttl_blocks: Some(2), + ..Default::default() + }; + let slate_i = sender_api.init_send_tx(m, args)?; + sender_api.tx_lock_outputs(m, &slate_i)?; + slate = slate_i; - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(14)); - Ok(()) - })?; + assert_eq!(tx.ttl_cutoff_height, Some(14)); + Ok(()) + }, + )?; // Mine past the ttl block and try to send let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); // Wallet 2 will need to have updated past the TTL - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |sender_api, m| { - let (_, _) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |sender_api, m| { + let (_, _) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; + Ok(()) + }, + )?; // And when wallet 1 sends, should be rejected - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |_sender_api, _m| { - let res = client1.send_tx_slate_direct("wallet2", &slate); - println!("Send after TTL result is: {:?}", res); - assert!(res.is_err()); - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |_sender_api, _m| { + let res = client1.send_tx_slate_direct("wallet2", &slate); + println!("Send after TTL result is: {:?}", res); + assert!(res.is_err()); + Ok(()) + }, + )?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/tx_list_filter.rs b/controller/tests/tx_list_filter.rs index d744694..424db24 100644 --- a/controller/tests/tx_list_filter.rs +++ b/controller/tests/tx_list_filter.rs @@ -23,6 +23,7 @@ use grin_core as core; use grin_keychain as keychain; use grin_util as util; use libwallet::{RetrieveTxQueryArgs, RetrieveTxQuerySortField}; +use std::path::PathBuf; use self::libwallet::{InitTxArgs, Slate}; use impls::test_framework::{self, LocalWalletClient}; @@ -53,154 +54,160 @@ fn test_wallet_tx_filtering( >, >, mask: Option<&SecretKey>, + test_dir: &'static str, ) -> Result<(), libwallet::Error> { - wallet::controller::owner_single_use(Some(wallet.clone()), mask, None, |api, _m| { - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_id = Some(5); + wallet::controller::owner_single_use( + wallet.clone(), + mask, + PathBuf::from(test_dir), + |api, _m| { + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_id = Some(5); - // Min ID - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results[0].id, 5); - assert_eq!(tx_results[tx_results.len() - 1].id, 33); + // Min ID + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results[0].id, 5); + assert_eq!(tx_results[tx_results.len() - 1].id, 33); - // Max ID - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(20); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results[0].id, 5); - assert_eq!(tx_results[tx_results.len() - 1].id, 20); + // Max ID + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(20); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results[0].id, 5); + assert_eq!(tx_results[tx_results.len() - 1].id, 20); - // Exclude 1 cancelled - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 28); + // Exclude 1 cancelled + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 28); - // Exclude 1 cancelled, show confirmed only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(true); - tx_query_args.include_confirmed_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 14); + // Exclude 1 cancelled, show confirmed only + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(true); + tx_query_args.include_confirmed_only = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 14); - // show outstanding only (including cancelled) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(false); - tx_query_args.include_outstanding_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 15); + // show outstanding only (including cancelled) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(false); + tx_query_args.include_outstanding_only = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 15); - // outstanding only and confirmed only should give empty set - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(false); - tx_query_args.include_outstanding_only = Some(true); - tx_query_args.include_confirmed_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 0); + // outstanding only and confirmed only should give empty set + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(false); + tx_query_args.include_outstanding_only = Some(true); + tx_query_args.include_confirmed_only = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // include sent only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_sent_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 15); + // include sent only + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_sent_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 15); - // include received only (none in this set) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_received_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 0); + // include received only (none in this set) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_received_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // include reverted only (none in this set) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_reverted_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 0); + // include reverted only (none in this set) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_reverted_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // include coinbase only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_coinbase_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 19); + // include coinbase only + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_coinbase_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 19); - // Amounts - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 27); + // Amounts + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 27); - // amount, should see as above with coinbases excluded - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); - tx_query_args.max_amount = Some(60_000_000_000 - 1); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 8); + // amount, should see as above with coinbases excluded + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); + tx_query_args.max_amount = Some(60_000_000_000 - 1); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 8); - // Amount - should only see coinbase (incoming) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 19); + // Amount - should only see coinbase (incoming) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_amount = Some(60_000_000_000); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 19); - // sort order - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; + // sort order + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; - assert_eq!(tx_results[0].id, 33); - assert_eq!(tx_results[tx_results.len() - 1].id, 0); + assert_eq!(tx_results[0].id, 33); + assert_eq!(tx_results[tx_results.len() - 1].id, 0); - // change sort field to amount desc, should have coinbases first - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); - tx_query_args.sort_field = Some(RetrieveTxQuerySortField::TotalAmount); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results[0].amount_credited, 60_000_000_000); + // change sort field to amount desc, should have coinbases first + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); + tx_query_args.sort_field = Some(RetrieveTxQuerySortField::TotalAmount); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results[0].amount_credited, 60_000_000_000); - /*for entry in tx_results.iter() { - println!("{:?}", entry); - }*/ + /*for entry in tx_results.iter() { + println!("{:?}", entry); + }*/ - Ok(()) - })?; + Ok(()) + }, + )?; Ok(()) } @@ -248,15 +255,25 @@ fn build_chain_for_tx_filtering( // Stop the scanning updater threads because it extends the time needed to build the chain // exponentially - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, _m| { - api.stop_updater()?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, _m| { + api.stop_updater()?; + Ok(()) + }, + )?; - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, _m| { - api.stop_updater()?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, _m| { + api.stop_updater()?; + Ok(()) + }, + )?; // few values to keep things shorter let reward = core::consensus::REWARD; @@ -268,17 +285,22 @@ fn build_chain_for_tx_filtering( let mut wallet_1_has_funds = false; // Check wallet 1 contents - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 spendable - {}", - wallet1_info.amount_currently_spendable - ); - if wallet1_info.amount_currently_spendable > reward { - wallet_1_has_funds = true; - } - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; + debug!( + "Wallet 1 spendable - {}", + wallet1_info.amount_currently_spendable + ); + if wallet1_info.amount_currently_spendable > reward { + wallet_1_has_funds = true; + } + Ok(()) + }, + )?; if !wallet_1_has_funds { let _ = @@ -293,9 +315,9 @@ fn build_chain_for_tx_filtering( let mut slate = Slate::blank(1, false); debug!("Creating TX for {}", amount); wallet::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |sender_api, m| { // note this will increment the block count as part of the transaction "Posting" let args = InitTxArgs { @@ -321,26 +343,31 @@ fn build_chain_for_tx_filtering( let amount: u64 = 1_000_000; let mut slate = Slate::blank(1, false); debug!("Creating TX for {}", amount); - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 1, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - sender_api.cancel_tx(m, Some(33), None)?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |sender_api, m| { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate_i = sender_api.init_send_tx(m, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + sender_api.tx_lock_outputs(m, &slate)?; + sender_api.cancel_tx(m, Some(33), None)?; + Ok(()) + }, + )?; // Perform actual testing - test_wallet_tx_filtering(wallet1, mask1)?; + test_wallet_tx_filtering(wallet1, mask1, test_dir)?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/updater_thread.rs b/controller/tests/updater_thread.rs index c137b4e..ea8273d 100644 --- a/controller/tests/updater_thread.rs +++ b/controller/tests/updater_thread.rs @@ -23,6 +23,7 @@ extern crate grin_wallet_libwallet as libwallet; // use grin_wallet_util::grin_core as core; use impls::test_framework::{self, LocalWalletClient}; +use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -71,18 +72,28 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err }); // add some accounts - wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "mining")?; + api.create_account_path(m, "listener")?; + Ok(()) + }, + )?; // add some accounts - wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - })?; + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + api.create_account_path(m, "account1")?; + api.create_account_path(m, "account2")?; + Ok(()) + }, + )?; // Get some mining done { @@ -93,7 +104,7 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let owner_api = api::Owner::new(wallet1, None); + let owner_api = api::Owner::new(wallet1, None, PathBuf::from(test_dir)); owner_api.start_updater(mask1, Duration::from_secs(5))?; // let updater thread run a bit diff --git a/doc/samples/v3_api_node/package-lock.json b/doc/samples/v3_api_node/package-lock.json index 4ccbc35..5d6ddb0 100644 --- a/doc/samples/v3_api_node/package-lock.json +++ b/doc/samples/v3_api_node/package-lock.json @@ -1,115 +1,142 @@ { "name": "node-sample", "version": "0.0.1", - "lockfileVersion": 1, + "lockfileVersion": 3, "requires": true, - "dependencies": { - "@types/connect": { + "packages": { + "": { + "name": "node-sample", + "version": "0.0.1", + "license": "ISC", + "dependencies": { + "jayson": "^3.2.0" + } + }, + "node_modules/@types/connect": { "version": "3.4.33", "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.33.tgz", "integrity": "sha512-2+FrkXY4zllzTNfJth7jOqEHC+enpLeGslEhpnTAkg21GkRrWV4SsAtqchtT4YS9/nODBU2/ZfsBY2X4J/dX7A==", - "requires": { + "dependencies": { "@types/node": "*" } }, - "@types/express-serve-static-core": { + "node_modules/@types/express-serve-static-core": { "version": "4.17.2", "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.17.2.tgz", "integrity": "sha512-El9yMpctM6tORDAiBwZVLMcxoTMcqqRO9dVyYcn7ycLWbvR8klrDn8CAOwRfZujZtWD7yS/mshTdz43jMOejbg==", - "requires": { + "dependencies": { "@types/node": "*", "@types/range-parser": "*" } }, - "@types/lodash": { + "node_modules/@types/lodash": { "version": "4.14.149", "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.149.tgz", "integrity": "sha512-ijGqzZt/b7BfzcK9vTrS6MFljQRPn5BFWOx8oE0GYxribu6uV+aA9zZuXI1zc/etK9E8nrgdoF2+LgUw7+9tJQ==" }, - "@types/node": { + "node_modules/@types/node": { "version": "12.12.27", "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.27.tgz", "integrity": "sha512-odQFl/+B9idbdS0e8IxDl2ia/LP8KZLXhV3BUeI98TrZp0uoIzQPhGd+5EtzHmT0SMOIaPd7jfz6pOHLWTtl7A==" }, - "@types/range-parser": { + "node_modules/@types/range-parser": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.3.tgz", "integrity": "sha512-ewFXqrQHlFsgc09MK5jP5iR7vumV/BYayNC6PgJO2LPe8vrnNFyjQjSppfEngITi0qvfKtzFvgKymGheFM9UOA==" }, - "JSONStream": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.5.tgz", - "integrity": "sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==", - "requires": { - "jsonparse": "^1.2.0", - "through": ">=2.2.7 <3" - } - }, - "commander": { + "node_modules/commander": { "version": "2.20.3", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==" }, - "es6-promise": { + "node_modules/es6-promise": { "version": "4.2.8", "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz", "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==" }, - "es6-promisify": { + "node_modules/es6-promisify": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", - "requires": { + "dependencies": { "es6-promise": "^4.0.3" } }, - "eyes": { + "node_modules/eyes": { "version": "0.1.8", "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", - "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=" + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "engines": { + "node": "> 0.1.90" + } }, - "jayson": { + "node_modules/jayson": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/jayson/-/jayson-3.2.0.tgz", "integrity": "sha512-DZQnwA57GcStw4soSYB2VntWXFfoWvmSarlaWePDYOWhjxT72PBM4atEBomaTaS1uqk3jFC9UO9AyWjlujo3xw==", - "requires": { + "dependencies": { "@types/connect": "^3.4.32", "@types/express-serve-static-core": "^4.16.9", "@types/lodash": "^4.14.139", "@types/node": "^12.7.7", - "JSONStream": "^1.3.1", "commander": "^2.12.2", "es6-promisify": "^5.0.0", "eyes": "^0.1.8", "json-stringify-safe": "^5.0.1", + "JSONStream": "^1.3.1", "lodash": "^4.17.15", "uuid": "^3.2.1" + }, + "bin": { + "jayson": "bin/jayson.js" } }, - "json-stringify-safe": { + "node_modules/json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" }, - "jsonparse": { + "node_modules/jsonparse": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", - "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=" + "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=", + "engines": [ + "node >= 0.2.0" + ] }, - "lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + "node_modules/JSONStream": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.5.tgz", + "integrity": "sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==", + "dependencies": { + "jsonparse": "^1.2.0", + "through": ">=2.2.7 <3" + }, + "bin": { + "JSONStream": "bin.js" + }, + "engines": { + "node": "*" + } }, - "through": { + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==" + }, + "node_modules/through": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" }, - "uuid": { + "node_modules/uuid": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", - "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==" + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).", + "bin": { + "uuid": "bin/uuid" + } } } } diff --git a/doc/samples/v3_api_node/readme.md b/doc/samples/v3_api_node/readme.md index e08ccbf..ed8e907 100644 --- a/doc/samples/v3_api_node/readme.md +++ b/doc/samples/v3_api_node/readme.md @@ -10,19 +10,21 @@ First run the Owner API: grin-wallet owner_api ``` -This sample doesn't use the authentication specified in the wallet's `.api_secret`, so before running the owner_api please ensure api authentication is commented out in `grin-wallet.toml`. Including the authentication token as part of the request is a function of your json-rpc client library of choice, so it's not included in the sample to make setup a bit simpler. - -ensure the client url in `src\index.js` is set correctly: +The Owner API uses HTTP Basic authentication when `api_secret_path` is configured in `grin-wallet.toml`. Before running the sample, load the secret from that file into an environment variable: ```.sh -const client = jayson.client.http('http://localhost:3420/v3/owner'); +export GRIN_OWNER_API_SECRET="$(cat /path/to/.owner_api_secret)" ``` +The sample sends it as the password for the `grin` user. If `api_secret_path` is disabled, the environment variable can be omitted. + +Ensure the client connection settings in `src/index.js` match the Owner API address. + Then (assuming node.js and npm are installed on the system): ```.sh npm install -node src/index.json +node src/index.js ``` Feel free to play around with the sample, modifying it to call whatever functions you'd like to see in operation! diff --git a/doc/samples/v3_api_node/src/index.js b/doc/samples/v3_api_node/src/index.js index 6de1c5b..a198d5b 100644 --- a/doc/samples/v3_api_node/src/index.js +++ b/doc/samples/v3_api_node/src/index.js @@ -8,7 +8,20 @@ const jayson = require('jayson/promise'); const crypto = require('crypto'); -const client = jayson.client.http('http://localhost:3420/v3/owner'); +const ownerApiSecret = process.env.GRIN_OWNER_API_SECRET; +const clientOptions = { + hostname: 'localhost', + port: 3420, + path: '/v3/owner', +}; + +if (ownerApiSecret) { + clientOptions.headers = { + Authorization: `Basic ${Buffer.from(`grin:${ownerApiSecret}`).toString('base64')}`, + }; +} + +const client = jayson.client.http(clientOptions); // Demo implementation of using `aes-256-gcm` with node.js's `crypto` lib. const aes256gcm = (shared_secret) => { @@ -33,8 +46,7 @@ const aes256gcm = (shared_secret) => { const tag = data_.slice(len-16, len) const text = data_.slice(0, len-16) decipher.setAuthTag(tag) - const dec = decipher.update(text, 'binary', 'utf8') + decipher.final('utf8'); - return dec + return decipher.update(text, 'binary', 'utf8') + decipher.final('utf8') }; return { @@ -69,8 +81,7 @@ class JSONRequestEncrypted { const nonce2 = Buffer.from(response.result.Ok.nonce, 'hex'); const data = Buffer.from(response.result.Ok.body_enc, 'base64'); - let dec = aesCipher.decrypt(data, nonce2) - return dec + return aesCipher.decrypt(data, nonce2) } } @@ -101,7 +112,7 @@ async function main() { "password": "", }).send(shared_key); - let token = JSON.parse(response).result.Ok; + let token = JSON.parse(response).result; let iterations = 1; @@ -131,4 +142,3 @@ async function main() { main(); - diff --git a/grin b/grin new file mode 160000 index 0000000..bad44b4 --- /dev/null +++ b/grin @@ -0,0 +1 @@ +Subproject commit bad44b4e9bd7e37417d80cc469bcba316249bd93 diff --git a/impls/Cargo.toml b/impls/Cargo.toml index 9625570..893f61f 100644 --- a/impls/Cargo.toml +++ b/impls/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_impls" -version = "5.4.0-alpha.1" +version = "5.4.1" authors = ["Grin Developers "] description = "Concrete types derived from libwallet traits" license = "Apache-2.0" @@ -18,64 +18,45 @@ serde = "1" serde_derive = "1" serde_json = "1" log = "0.4" -ring = "0.16" -uuid = { version = "0.8", features = ["serde", "v4"] } +ring = "0.17.14" chrono = { version = "0.4.11", features = ["serde"] } lazy_static = "1" -tokio = { version = "0.2", features = ["full"] } -reqwest = { version = "0.10", features = ["rustls-tls", "socks"] } +tokio = { version = "1.52.3", features = ["full"] } +reqwest = { version = "0.13.3", features = ["socks"] } #Socks/Tor/Bridge/Proxy -byteorder = "1" -ed25519-dalek = "1.0.0-pre.4" -x25519-dalek = "0.6" -data-encoding = "2" +ed25519-dalek = "2" regex = "1.3" timer = "0.2" sysinfo = "0.29" base64 = "0.12.0" url = "2.1" -grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" } -grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" } -grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-alpha.1" } +arti-client = { version = "0.44.0", features = ["static", "pt-client", "onion-service-service", "onion-service-client"] } +tor-rtcompat = { version = "0.44.0", features = ["static"] } +fs-mistrust = "0.15.0" +fslock-guard = "0.8" +tor-hsservice = "0.44.0" +tor-hsrproxy = "0.44.0" +tor-keymgr = "0.44.0" +tor-llcrypto = "0.44.0" +tor-hscrypto = "0.44.0" +sha2 = "0.10.8" +hyper = { version = "1.10.1", features = ["http1", "client"] } +hyper-util = { version = "0.1.20", features = ["tokio"] } +http-body-util = "0.1.3" +bytes = "1.11.1" + +grin_wallet_util = { path = "../util", version = "5.4.1" } +grin_wallet_config = { path = "../config", version = "5.4.1" } +grin_wallet_libwallet = { path = "../libwallet", version = "5.4.1" } ##### Grin Imports -# For Release -#grin_core = "5.4.0" -#grin_keychain = "5.4.0" -#grin_chain = "5.4.0" -#grin_util = "5.4.0" -#grin_api = "5.4.0" -#grin_store = "5.4.0" +grin_core = { path = "../grin/core"} +grin_keychain = { path = "../grin/keychain"} +grin_chain = { path = "../grin/chain"} +grin_util = { path = "../grin/util"} +grin_api = { path = "../grin/api"} -# For beta release - -# grin_core = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3"} -# grin_keychain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_chain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_api = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_store = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } - -# For bleeding edge -grin_core = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_keychain = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_chain = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_util = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_api = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_store = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } - -# For local testing -# grin_core = { path = "../../grin/core"} -# grin_keychain = { path = "../../grin/keychain"} -# grin_chain = { path = "../../grin/chain"} -# grin_util = { path = "../../grin/util"} -# grin_api = { path = "../../grin/api"} -# grin_store = { path = "../../grin/store"} - -##### - -[dev-dependencies] -"remove_dir_all" = "0.7" \ No newline at end of file +##### \ No newline at end of file diff --git a/impls/src/adapters/mod.rs b/impls/src/adapters/mod.rs index 44fe8bf..361009e 100644 --- a/impls/src/adapters/mod.rs +++ b/impls/src/adapters/mod.rs @@ -13,12 +13,12 @@ // limitations under the License. mod file; -pub mod http; mod slatepack; +pub mod tor; pub use self::file::PathToSlate; -pub use self::http::HttpSlateSender; pub use self::slatepack::PathToSlatepack; +pub use self::tor::TorSlateSender; use crate::config::WalletConfig; use crate::libwallet::{Error, Slate}; diff --git a/impls/src/adapters/slatepack.rs b/impls/src/adapters/slatepack.rs index 850c3d5..2b04c23 100644 --- a/impls/src/adapters/slatepack.rs +++ b/impls/src/adapters/slatepack.rs @@ -104,7 +104,7 @@ mod tests { use grin_core::global; fn clean_output_dir(test_dir: &str) { - let _ = remove_dir_all::remove_dir_all(test_dir); + let _ = fs::remove_dir_all(test_dir); } fn setup(test_dir: &str) { diff --git a/impls/src/adapters/http.rs b/impls/src/adapters/tor.rs similarity index 54% rename from impls/src/adapters/http.rs rename to impls/src/adapters/tor.rs index 4c79da7..8975ad0 100644 --- a/impls/src/adapters/http.rs +++ b/impls/src/adapters/tor.rs @@ -12,128 +12,108 @@ // See the License for the specific language governing permissions and // limitations under the License. -/// HTTP Wallet 'plugin' implementation use crate::client_utils::{Client, ClientError}; use crate::libwallet::slate_versions::{SlateVersion, VersionedSlate}; use crate::libwallet::{Error, Slate}; +use crate::tor::arti::{start_tor_client, tor_post}; use crate::tor::bridge::TorBridge; +use crate::tor::config as tor_config; +use crate::tor::process::TorProcess; use crate::tor::proxy::TorProxy; use crate::SlateSender; -use grin_wallet_config::types::{TorBridgeConfig, TorProxyConfig}; +use grin_wallet_config::TorConfig; use serde::Serialize; use serde_json::{json, Value}; use std::collections::HashMap; use std::convert::TryFrom; use std::net::SocketAddr; -use std::path::MAIN_SEPARATOR; +use std::path::PathBuf; use std::sync::Arc; -use crate::tor::config as tor_config; -use crate::tor::process as tor_process; - -const TOR_CONFIG_PATH: &str = "tor/sender"; - #[derive(Clone)] -pub struct HttpSlateSender { +pub struct TorSlateSender { base_url: String, - use_socks: bool, - socks_proxy_addr: Option, - tor_config_dir: String, - process: Option>, - bridge: TorBridgeConfig, - proxy: TorProxyConfig, + config: TorConfig, + tor_process: Arc>, } -impl HttpSlateSender { +impl TorSlateSender { /// Create, return Err if scheme is not "http" - fn new(base_url: &str) -> Result { + pub fn new(base_url: &str, config: TorConfig) -> Result { if !base_url.starts_with("http") && !base_url.starts_with("https") { - Err(SchemeNotHttp) + Err(Error::GenericError("Scheme must be http".to_string())) } else { - Ok(HttpSlateSender { + let tor = if config.use_integrated.unwrap_or(false) { + start_tor_client(config.clone())?; + None + } else { + let tor_dir = { + let mut path = PathBuf::from(&config.send_config_dir); + path.push("tor"); + path.push("sender"); + path + }; + let p = Self::launch_tor_process(&config, &tor_dir)?; + Some(p) + }; + Ok(TorSlateSender { base_url: base_url.to_owned(), - use_socks: false, - socks_proxy_addr: None, - tor_config_dir: String::from(""), - process: None, - bridge: TorBridgeConfig::default(), - proxy: TorProxyConfig::default(), + config, + tor_process: Arc::new(tor), }) } } - /// Switch to using socks proxy - pub fn with_socks_proxy( - base_url: &str, - proxy_addr: &str, - tor_config_dir: &str, - tor_bridge: TorBridgeConfig, - tor_proxy: TorProxyConfig, - ) -> Result { - let mut ret = Self::new(base_url)?; - ret.use_socks = true; - //TODO: Unwrap - ret.socks_proxy_addr = Some(SocketAddr::V4(proxy_addr.parse().unwrap())); - ret.tor_config_dir = tor_config_dir.into(); - ret.bridge = tor_bridge; - ret.proxy = tor_proxy; - Ok(ret) - } + /// Launch external Tor process. + fn launch_tor_process(config: &TorConfig, tor_dir: &PathBuf) -> Result { + let mut tor = TorProcess::new(); + let socks_proxy_addr = SocketAddr::V4( + config + .socks_proxy_addr + .parse() + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?, + ); + info!("Starting TOR Process for send at {:?}", socks_proxy_addr); - /// launch TOR process - pub fn launch_tor(&mut self) -> Result<(), Error> { - // set up tor send process if needed - let mut tor = tor_process::TorProcess::new(); - if self.use_socks && self.process.is_none() { - let tor_dir = format!( - "{}{}{}", - &self.tor_config_dir, MAIN_SEPARATOR, TOR_CONFIG_PATH - ); - info!( - "Starting TOR Process for send at {:?}", - self.socks_proxy_addr - ); - - let mut hm_tor_bridge: HashMap = HashMap::new(); - if self.bridge.bridge_line.is_some() { - let bridge_struct = TorBridge::try_from(self.bridge.clone()) - .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; - hm_tor_bridge = bridge_struct - .to_hashmap() - .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; - } - - let mut hm_tor_proxy: HashMap = HashMap::new(); - if self.proxy.transport.is_some() || self.proxy.allowed_port.is_some() { - let proxy = TorProxy::try_from(self.proxy.clone()) - .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; - hm_tor_proxy = proxy - .to_hashmap() - .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; - } - - tor_config::output_tor_sender_config( - &tor_dir, - &self.socks_proxy_addr.unwrap().to_string(), - hm_tor_bridge, - hm_tor_proxy, - ) - .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; - // Start TOR process - tor.torrc_path(&format!("{}/torrc", &tor_dir)) - .working_dir(&tor_dir) - .timeout(20) - .completion_percent(100) - .launch() - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; - self.process = Some(Arc::new(tor)); + let mut hm_tor_bridge: HashMap = HashMap::new(); + if config.bridge.bridge_line.is_some() { + let bridge_struct = TorBridge::try_from(config.bridge.clone()) + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + hm_tor_bridge = bridge_struct + .to_hashmap() + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; } - Ok(()) + + let mut hm_tor_proxy: HashMap = HashMap::new(); + if config.proxy.transport.is_some() || config.proxy.allowed_port.is_some() { + let proxy = TorProxy::try_from(config.proxy.clone()) + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + hm_tor_proxy = proxy + .to_hashmap() + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + } + + tor_config::output_tor_sender_config( + tor_dir.to_str().unwrap(), + socks_proxy_addr.to_string().as_str(), + hm_tor_bridge, + hm_tor_proxy, + ) + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + // Start TOR process + let mut path = tor_dir.clone(); + path.push("torrc"); + tor.torrc_path(path.to_str().unwrap()) + .working_dir(tor_dir.to_str().unwrap()) + .timeout(config.bootstrap_timeout().as_secs()) + .completion_percent(100) + .launch() + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + Ok(tor) } /// Check version of the listening wallet pub fn check_other_version(&mut self, url: &str) -> Result { - self.launch_tor()?; let req = json!({ "jsonrpc": "2.0", "method": "check_version", @@ -141,7 +121,7 @@ impl HttpSlateSender { "params": [] }); - let res: String = self.post(url, None, req).map_err(|e| { + let res: String = self.post(url, req).map_err(|e| { let mut report = format!("Performing version check (is recipient listening?): {}", e); let err_string = format!("{}", e); if err_string.contains("404") { @@ -154,7 +134,8 @@ impl HttpSlateSender { Error::ClientCallback(report) })?; - let res: Value = serde_json::from_str(&res).unwrap(); + let res: Value = serde_json::from_str(&res) + .map_err(|_| Error::ClientCallback(format!("Can not parse response {:?}", res)))?; trace!("Response: {}", res); if res["error"] != json!(null) { let report = format!( @@ -168,9 +149,11 @@ impl HttpSlateSender { let resp_value = res["result"]["Ok"].clone(); trace!("resp_value: {}", resp_value.clone()); let foreign_api_version: u16 = - serde_json::from_value(resp_value["foreign_api_version"].clone()).unwrap(); + serde_json::from_value(resp_value["foreign_api_version"].clone()) + .map_err(|_| Error::ClientCallback(format!("Can not parse response {:?}", res)))?; let supported_slate_versions: Vec = - serde_json::from_value(resp_value["supported_slate_versions"].clone()).unwrap(); + serde_json::from_value(resp_value["supported_slate_versions"].clone()) + .map_err(|_| Error::ClientCallback(format!("Can not parse response {:?}", res)))?; // trivial tests for now, but will be expanded later if foreign_api_version < 2 { @@ -192,32 +175,30 @@ impl HttpSlateSender { Err(Error::ClientCallback(report)) } - fn post( - &self, - url: &str, - api_secret: Option, - input: IN, - ) -> Result + fn post(&self, url: &str, input: IN) -> Result where IN: Serialize, { - let client = if !self.use_socks { - Client::new() + let res = if self.tor_process.is_some() { + let socks_proxy_addr = + SocketAddr::V4(self.config.socks_proxy_addr.parse().map_err(|_| { + ClientError::Internal("Socks proxy address is not set".to_string()) + })?); + let timeout = self.config.request_timeout(); + let client = Client::with_proxy(socks_proxy_addr, "socks5h://", timeout) + .map_err(|_| ClientError::Internal("Unable to create http client".into()))?; + let req = client.create_post_request(url, None, &input)?; + let res = client.send_request(req)?; + res } else { - Client::with_proxy( - self.socks_proxy_addr - .ok_or_else(|| ClientError::Internal("No socks proxy address set".into()))?, - "socks5h://", - ) - } - .map_err(|_| ClientError::Internal("Unable to create http client".into()))?; - let req = client.create_post_request(url, api_secret, &input)?; - let res = client.send_request(req)?; + tor_post(&self.config, &input, url) + .map_err(|e| ClientError::RequestError(format!("{:?}", e)))? + }; Ok(res) } } -impl SlateSender for HttpSlateSender { +impl SlateSender for TorSlateSender { fn send_tx(&mut self, slate: &Slate, finalize: bool) -> Result { let trailing = match self.base_url.ends_with('/') { true => "", @@ -225,8 +206,6 @@ impl SlateSender for HttpSlateSender { }; let url_str = format!("{}{}v2/foreign", self.base_url, trailing); - self.launch_tor()?; - let slate_send = match self.check_other_version(&url_str)? { SlateVersion::V5 => VersionedSlate::into_version(slate.clone(), SlateVersion::V5)?, SlateVersion::V4 => VersionedSlate::into_version(slate.clone(), SlateVersion::V4)?, @@ -255,7 +234,7 @@ impl SlateSender for HttpSlateSender { trace!("Sending receive_tx request: {}", req); - let res: String = self.post(&url_str, None, req).map_err(|e| { + let res: String = self.post(&url_str, req).map_err(|e| { let report = format!( "Sending transaction slate to other wallet (is recipient listening?): {}", e @@ -263,7 +242,8 @@ impl SlateSender for HttpSlateSender { Error::ClientCallback(report) })?; - let res: Value = serde_json::from_str(&res).unwrap(); + let res: Value = serde_json::from_str(&res) + .map_err(|_| Error::ClientCallback(format!("Can not parse response {:?}", res)))?; trace!("Response: {}", res); if res["error"] != json!(null) { let report = format!( @@ -277,22 +257,15 @@ impl SlateSender for HttpSlateSender { let slate_value = res["result"]["Ok"].clone(); trace!("slate_value: {}", slate_value); - let slate = Slate::deserialize_upgrade(&serde_json::to_string(&slate_value).unwrap()) - .map_err(|e| { + if let Ok(slate_value) = serde_json::to_string(&slate_value) { + let slate = Slate::deserialize_upgrade(&slate_value).map_err(|e| { error!("Error deserializing response slate: {}", e); Error::SlateDeser })?; - - Ok(slate) - } -} - -#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] -pub struct SchemeNotHttp; - -impl Into for SchemeNotHttp { - fn into(self) -> Error { - let err_str = "url scheme must be http".to_string(); - Error::GenericError(err_str) + Ok(slate) + } else { + error!("Error deserializing response slate: {}", slate_value); + Err(Error::SlateDeser) + } } } diff --git a/impls/src/client_utils/client.rs b/impls/src/client_utils/client.rs index ec0ee0f..4bb8f97 100644 --- a/impls/src/client_utils/client.rs +++ b/impls/src/client_utils/client.rs @@ -21,23 +21,14 @@ use reqwest::{ClientBuilder, Method, Proxy, RequestBuilder}; use serde::{Deserialize, Serialize}; use serde_json; use std::net::SocketAddr; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::time::Duration; use tokio::runtime::{Builder, Handle, Runtime}; // Global Tokio runtime. -// Needs a `Mutex` because `Runtime::block_on` requires mutable access. -// Tokio v0.3 requires immutable self, but we are waiting on upstream -// updates before we can upgrade. -// See: https://github.com/seanmonstar/reqwest/pull/1076 lazy_static! { - pub static ref RUNTIME: Arc> = Arc::new(Mutex::new( - Builder::new() - .threaded_scheduler() - .enable_all() - .build() - .unwrap() - )); + pub static ref RUNTIME: Arc = + Arc::new(Builder::new_multi_thread().enable_all().build().unwrap()); } #[derive(Clone, Eq, thiserror::Error, PartialEq, Debug)] @@ -61,22 +52,26 @@ pub struct Client { impl Client { /// New client - pub fn new() -> Result { - Self::build(None) + pub fn new(request_timeout: Duration) -> Result { + Self::build(None, request_timeout) } - pub fn with_proxy(socks_proxy_addr: SocketAddr, scheme: &'static str) -> Result { - Self::build(Some((socks_proxy_addr, scheme))) + pub fn with_proxy( + socks_proxy_addr: SocketAddr, + scheme: &'static str, + request_timeout: Duration, + ) -> Result { + Self::build(Some((socks_proxy_addr, scheme)), request_timeout) } - fn build(proxy: Option<(SocketAddr, &str)>) -> Result { + fn build(proxy: Option<(SocketAddr, &str)>, request_timeout: Duration) -> Result { let mut headers = HeaderMap::new(); headers.insert(USER_AGENT, HeaderValue::from_static("grin-client")); headers.insert(ACCEPT, HeaderValue::from_static("application/json")); headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); let mut builder = ClientBuilder::new() - .timeout(Duration::from_secs(20)) + .timeout(request_timeout) .use_rustls_tls() .default_headers(headers); @@ -273,18 +268,11 @@ impl Client { if Handle::try_current().is_ok() { let rt = RUNTIME.clone(); let client = self.clone(); - std::thread::spawn(move || { - rt.lock() - .unwrap() - .block_on(async { client.send_request_async(req).await }) - }) - .join() - .unwrap() - } else { - RUNTIME - .lock() + std::thread::spawn(move || rt.block_on(async { client.send_request_async(req).await })) + .join() .unwrap() - .block_on(self.send_request_async(req)) + } else { + RUNTIME.block_on(self.send_request_async(req)) } } } diff --git a/impls/src/lib.rs b/impls/src/lib.rs index 9e9c32c..9bbedfa 100644 --- a/impls/src/lib.rs +++ b/impls/src/lib.rs @@ -42,8 +42,8 @@ pub mod test_framework; pub mod tor; pub use crate::adapters::{ - HttpSlateSender, PathToSlate, PathToSlatepack, SlateGetter, SlatePutter, SlateReceiver, - SlateSender, + PathToSlate, PathToSlatepack, SlateGetter, SlatePutter, SlateReceiver, SlateSender, + TorSlateSender, }; pub use crate::error::Error; pub use crate::lifecycle::DefaultLCProvider; diff --git a/impls/src/lifecycle/default.rs b/impls/src/lifecycle/default.rs index 4514eb3..7514a30 100644 --- a/impls/src/lifecycle/default.rs +++ b/impls/src/lifecycle/default.rs @@ -24,6 +24,7 @@ use crate::lifecycle::seed::WalletSeed; use crate::util::secp::key::SecretKey; use crate::util::ZeroingString; use grin_util::logger::LoggingConfig; +use grin_wallet_config::config::reload_global_config; use std::fs; use std::path::PathBuf; use std::path::MAIN_SEPARATOR; @@ -89,48 +90,11 @@ where logging_config: Option, tor_config: Option, ) -> Result<(), Error> { - let mut default_config = GlobalWalletConfig::for_chain(&chain_type); - let config_file_version = match default_config.members.as_ref() { - Some(m) => m.clone().config_file_version, - None => None, - }; - let logging = match logging_config { - Some(l) => Some(l), - None => match default_config.members.as_ref() { - Some(m) => m.clone().logging, - None => None, - }, - }; - // Check if config was provided, if not load default and set update to "true" - let (wallet, update) = match wallet_config { - Some(w) => (w, false), - None => match default_config.members.as_ref() { - Some(m) => (m.clone().wallet, true), - None => (WalletConfig::default(), true), - }, - }; - let tor = match tor_config { - Some(t) => Some(t), - None => match default_config.members.as_ref() { - Some(m) => m.clone().tor, - None => Some(TorConfig::default()), - }, - }; - default_config = GlobalWalletConfig { - members: Some(GlobalWalletConfigMembers { - config_file_version, - wallet, - tor, - logging, - }), - ..default_config - }; let mut config_file_name = PathBuf::from(self.data_dir.clone()); config_file_name.push(file_name); let mut data_dir_name = PathBuf::from(self.data_dir.clone()); data_dir_name.push(GRIN_WALLET_DIR); - if config_file_name.exists() && data_dir_name.exists() { let msg = format!( "{} already exists in the target directory ({}). Please remove it first", @@ -140,10 +104,35 @@ where return Err(Error::Lifecycle(msg)); } - // If config exists but the datadir return ok if config_file_name.exists() { return Ok(()); } + + let mut default_config = GlobalWalletConfig::for_chain(&chain_type, &config_file_name); + let config_file_version = default_config.members.config_file_version; + let logging = match logging_config.clone() { + Some(l) => Some(l), + None => default_config.members.logging, + }; + // Check if config was provided, if not load default and set update to "true" + let (wallet, update) = match wallet_config.clone() { + Some(w) => (w, false), + None => (default_config.members.wallet, true), + }; + let tor = match tor_config.clone() { + Some(t) => Some(t), + None => default_config.members.tor, + }; + default_config = GlobalWalletConfig { + members: GlobalWalletConfigMembers { + config_file_version, + wallet, + tor, + logging, + }, + ..default_config + }; + // default settings are updated if no config was provided, no support for top_dir/here let mut abs_path_node = std::env::current_dir()?; abs_path_node.push(self.data_dir.clone()); @@ -171,6 +160,8 @@ where return Err(Error::Lifecycle(msg)); } + reload_global_config(&config_file_name)?; + info!( "File {} configured and created", config_file_name.to_str().unwrap(), diff --git a/impls/src/node_clients/http.rs b/impls/src/node_clients/http.rs index 6b80b49..b7e29c6 100644 --- a/impls/src/node_clients/http.rs +++ b/impls/src/node_clients/http.rs @@ -14,7 +14,9 @@ //! Client functions, implementations of the NodeClient trait +use super::resp_types::*; use crate::api::{self, LocatedTxKernel, OutputListing, OutputPrintable}; +use crate::client_utils::json_rpc::*; use crate::client_utils::{Client, RUNTIME}; use crate::core::core::{Transaction, TxKernel}; use crate::libwallet; @@ -26,9 +28,7 @@ use futures::TryStreamExt; use std::collections::HashMap; use std::env; use std::net::SocketAddr; - -use super::resp_types::*; -use crate::client_utils::json_rpc::*; +use std::time::Duration; const ENDPOINT: &str = "/v2/foreign"; @@ -45,8 +45,9 @@ impl HTTPNodeClient { pub fn new( node_url: &str, node_api_secret: Option, + request_timeout: Duration, ) -> Result { - Self::new_proxy(node_url, node_api_secret, None) + Self::new_proxy(node_url, node_api_secret, None, request_timeout) } /// Create a new client with proxy @@ -54,16 +55,17 @@ impl HTTPNodeClient { node_url: &str, node_api_secret: Option, proxy: Option<(SocketAddr, &'static str)>, + request_timeout: Duration, ) -> Result { let client = if let Some((a, s)) = proxy { - Client::with_proxy(a, s) + Client::with_proxy(a, s, request_timeout) } else { - Client::new() + Client::new(request_timeout) }; Ok(HTTPNodeClient { client: client.map_err(|_| libwallet::Error::Node)?, node_url: node_url.to_owned(), - node_api_secret: node_api_secret, + node_api_secret, node_version_info: None, }) } @@ -107,18 +109,25 @@ impl NodeClient for HTTPNodeClient { fn node_url(&self) -> &str { &self.node_url } - fn node_api_secret(&self) -> Option { - self.node_api_secret.clone() - } - fn set_node_url(&mut self, node_url: &str) { self.node_url = node_url.to_owned(); } + fn node_api_secret(&self) -> Option { + self.node_api_secret.clone() + } + fn set_node_api_secret(&mut self, node_api_secret: Option) { self.node_api_secret = node_api_secret; } + /// Posts a transaction to a grin node + fn post_tx(&self, tx: &Transaction, fluff: bool) -> Result<(), libwallet::Error> { + let params = json!([tx, fluff]); + self.send_json_request::("push_transaction", ¶ms)?; + Ok(()) + } + fn get_version_info(&mut self) -> Option { if let Some(v) = self.node_version_info.as_ref() { return Some(v.clone()); @@ -135,30 +144,23 @@ impl NodeClient for HTTPNodeClient { // If node isn't available, allow offline functions // unfortunately have to parse string due to error structure let err_string = format!("{}", e); - if err_string.contains("404") { - return Some(NodeVersionInfo { + return if err_string.contains("404") { + Some(NodeVersionInfo { node_version: "1.0.0".into(), block_header_version: 1, verified: Some(false), - }); + }) } else { error!("Unable to contact Node to get version info: {}, check your node is running", e); warn!("Warning: a) Node is offline, or b) 'node_api_secret_path' in 'grin-wallet.toml' is set incorrectly"); - return None; - } + None + }; } }; self.node_version_info = Some(retval.clone()); Some(retval) } - /// Posts a transaction to a grin node - fn post_tx(&self, tx: &Transaction, fluff: bool) -> Result<(), libwallet::Error> { - let params = json!([tx, fluff]); - self.send_json_request::("push_transaction", ¶ms)?; - Ok(()) - } - /// Return the chain tip from a given node fn get_chain_tip(&self) -> Result<(u64, String), libwallet::Error> { let result = self.send_json_request::("get_tip", &serde_json::Value::Null)?; @@ -222,7 +224,7 @@ impl NodeClient for HTTPNodeClient { .collect(); // going to leave this here even though we're moving - // to the json RPC api to keep the functionality of + // to the JSON RPC api to keep the functionality of // parallelizing larger requests. Will raise default // from 200 to 500, however let chunk_default = 500; @@ -272,7 +274,7 @@ impl NodeClient for HTTPNodeClient { let rt = RUNTIME.clone(); let res: Result, _> = - std::thread::spawn(move || rt.lock().unwrap().block_on(async move { task.await })) + std::thread::spawn(move || rt.block_on(async move { task.await })) .join() .unwrap(); @@ -420,8 +422,8 @@ mod tests { } } - // Wallet will "push" a transaction to node, serializing the transaction as json. - // We are testing the json structure is what we expect here. + // Wallet will "push" a transaction to node, serializing the transaction as JSON. + // We are testing the JSON structure is what we expect here. #[test] fn test_transaction_json_ser_deser() { let tx1 = tx1i1o_v2_compatible(); diff --git a/impls/src/tor/arti.rs b/impls/src/tor/arti.rs new file mode 100644 index 0000000..769e2bc --- /dev/null +++ b/impls/src/tor/arti.rs @@ -0,0 +1,478 @@ +// Copyright 2026 The Grin Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::tor::config::exp_sec_key_bytes; +use arti_client::config::pt::TransportConfigBuilder; +use arti_client::config::{BridgeConfigBuilder, TorClientConfigBuilder}; +use arti_client::{TorClient, TorClientConfig}; +use bytes::Bytes; +use ed25519_dalek::hazmat::ExpandedSecretKey; +use ed25519_dalek::Digest; +use fs_mistrust::Mistrust; +use fslock_guard::LockFileGuard; +use grin_util::secp::SecretKey; +use grin_wallet_config::TorConfig; +use grin_wallet_libwallet::Error; +use grin_wallet_util::OnionV3Address; +use http_body_util::{BodyExt, Full}; +use hyper::{Request, Uri}; +use hyper_util::rt::TokioIo; +use lazy_static::lazy_static; +use serde::Serialize; +use sha2::Sha512; +use std::collections::HashMap; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, LazyLock, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::Duration; +use tor_hscrypto::pk::{HsIdKey, HsIdKeypair}; +use tor_hsrproxy::config::{ + Encapsulation, ProxyAction, ProxyConfigBuilder, ProxyPattern, ProxyRule, TargetAddr, +}; +use tor_hsrproxy::OnionServiceReverseProxy; +use tor_hsservice::config::OnionServiceConfigBuilder; +use tor_hsservice::{ + HsIdKeypairSpecifier, HsIdPublicKeySpecifier, HsNickname, RunningOnionService, +}; +use tor_keymgr::config::CfgPath; +use tor_keymgr::{ArtiNativeKeystore, KeyMgrBuilder, KeystoreSelector}; +use tor_llcrypto::pk::ed25519::ExpandedKeypair; +use tor_rtcompat::tokio::TokioNativeTlsRuntime; +use tor_rtcompat::{SleepProviderExt, ToplevelBlockOn}; + +struct TorService { + service: Arc, + proxy: Arc, + worker: JoinHandle<()>, + state_lock: PathBuf, +} + +lazy_static! { + /// Arti Tokio runtime. + static ref ARTI_RUNTIME: LazyLock>> = + LazyLock::new(|| Mutex::new(ArtiRuntimeWrapper::create().ok())); + /// Arti client and config. + static ref ARTI_CLIENT_CONFIG: LazyLock>, TorClientConfig)>>> = + LazyLock::new(|| Mutex::new(None)); + /// Running services, where key is onion address. + static ref ARTI_PROXY_SERVICES: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); +} + +/// Arti client runtime wrapper. +#[derive(Clone)] +struct ArtiRuntimeWrapper { + runtime: TokioNativeTlsRuntime, +} + +impl ArtiRuntimeWrapper { + fn create() -> Result { + Ok(Self { + runtime: TokioNativeTlsRuntime::create()?, + }) + } +} + +/// Get Tor client runtime. +fn runtime() -> Result { + let mut runtime = ARTI_RUNTIME.lock().unwrap(); + let r = match runtime.as_ref() { + None => runtime.insert(ArtiRuntimeWrapper::create()?), + Some(r) => r, + }; + Ok(r.runtime.clone()) +} + +/// Stop running Tor service by onion address as key. +pub fn stop_tor_service(onion_addr: String) -> Result<(), Error> { + let service = ARTI_PROXY_SERVICES.lock().unwrap().remove(&onion_addr); + let Some(service) = service else { + error!("Service {} to stop was not found", onion_addr); + return Ok(()); + }; + let TorService { + service, + proxy, + worker, + state_lock, + } = service; + + proxy.shutdown(); + worker + .join() + .map_err(|_| Error::TorProcess("Tor proxy thread panicked".into()))?; + drop(service); + drop( + LockFileGuard::lock(state_lock) + .map_err(|e| Error::TorProcess(format!("Can not stop Tor service: {}", e)))?, + ); + Ok(()) +} + +/// Get state and cache data paths. +fn state_cache_paths(config: &TorConfig) -> (PathBuf, PathBuf) { + let mut tor_dir = PathBuf::from(&config.send_config_dir); + tor_dir.push("arti"); + let state_path = tor_dir.join("state"); + let cache_path = tor_dir.join("cache"); + (state_path, cache_path) +} + +/// Start Tor service from provided key. +pub fn start_tor_service(key: SecretKey, addr: &str, config: &TorConfig) -> Result<(), Error> { + info!("Starting integrated Tor listener."); + let use_proxy = config.proxy.transport.is_some() && config.proxy.address.is_some(); + if use_proxy { + info!("Proxy configuration will be ignored."); + } + + let (state_path, cache_path) = state_cache_paths(&config); + let (client, config) = init_client(&state_path, &cache_path, config)?; + + // Add service key to keystore. + let onion_address = + OnionV3Address::from_private(&key.0).map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + let hs = HsNickname::new(onion_address.to_string()) + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + let keystore_path = Path::new(&state_path).join("keystore"); + // Arti 0.44 uses this lock to finish stopping a service before it can start again. + let state_lock = state_path + .join("hss") + .join(format!("{}.lock", onion_address)); + let _ = add_service_key(config.fs_mistrust(), &key, &hs, keystore_path)?; + + // Launch Onion service. + let service_config = OnionServiceConfigBuilder::default() + .nickname(hs.clone()) + .build() + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + let (service, proxy, worker) = match client.launch_onion_service(service_config) { + Ok(res) => { + if let Some((service, mut request)) = res { + let addr: SocketAddr = addr + .parse() + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let proxy = create_service_proxy(addr)?; + let c = client.clone(); + let p = proxy.clone(); + // Launch service proxy. + let worker = thread::spawn(move || { + c.clone().runtime().block_on(async move { + loop { + match run_service_proxy(p.clone(), &mut request, hs.clone()).await { + Ok(_) => { + info!("Tor proxy stopped"); + break; + } + Err(e) => { + error!("Tor proxy error: {:?}, restarting", e); + tokio::time::sleep(Duration::from_millis(1000)).await; + continue; + } + } + } + }) + }); + (service, proxy, worker) + } else { + return Err(Error::TorProcess("Can not launch onion service".to_owned())); + } + } + Err(e) => return Err(Error::TorProcess(format!("{:?}", e))), + }; + + let mut running_services = ARTI_PROXY_SERVICES.lock().unwrap(); + running_services.insert( + onion_address.to_string(), + TorService { + service, + proxy, + worker, + state_lock, + }, + ); + + Ok(()) +} + +/// Start Tor client to send requests. +pub fn start_tor_client(config: TorConfig) -> Result<(), Error> { + info!("Starting integrated Tor client"); + + let (state_path, cache_path) = state_cache_paths(&config); + let (_, _) = init_client(&state_path, &cache_path, &config)?; + Ok(()) +} + +/// Make POST request. +pub fn tor_post(tor_config: &TorConfig, input: &IN, url: &str) -> Result +where + IN: Serialize, +{ + let json = serde_json::to_string(input) + .map_err(|_| Error::GenericError("Could not serialize data to JSON".to_owned()))?; + let url = url.to_string(); + let url: Uri = url + .parse() + .map_err(|_| Error::GenericError(format!("Bad URL: {}", url)))?; + let host = match url.host() { + None => return Err(Error::GenericError(format!("URL {} has bad host", url))), + Some(h) => h, + } + .to_string(); + let timeout = tor_config.request_timeout(); + let (state_path, cache_path) = state_cache_paths(&tor_config); + let (client, _) = init_client(&state_path, &cache_path, tor_config)?; + let res: Result = thread::spawn(move || { + let c = client.clone(); + client.runtime().block_on(async move { + let res = c + .runtime() + .timeout(timeout, async { + let stream = c + .connect((host, url.port_u16().unwrap_or(80))) + .await + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let (mut request_sender, connection) = + hyper::client::conn::http1::handshake(TokioIo::new(stream)) + .await + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + + // Spawn a task to poll the connection and drive the HTTP state. + tokio::spawn(async move { + if let Err(e) = connection.await { + error!("Tor connection error: {}", e); + } + }); + + let resp = request_sender + .send_request( + Request::builder() + .uri(url) + .method("POST") + .body::>(Full::from(json)) + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?, + ) + .await + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + + let body_resp = resp + .into_body() + .collect() + .await + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let body = body_resp.to_bytes().into(); + let body_text = String::from_utf8(body) + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + Ok(body_text) + }) + .await; + match res { + Err(e) => Err(Error::TorProcess(format!("{:?}", e))), + Ok(body) => Ok(body), + } + }) + }) + .join() + .unwrap_or_else(|e| return Err(Error::TorProcess(format!("{:?}", e))))?; + res +} + +/// Create Tor client. +fn init_client( + state_path: &PathBuf, + cache_path: &PathBuf, + tor_config: &TorConfig, +) -> Result<(Arc>, TorClientConfig), Error> { + let mut builder = TorClientConfigBuilder::from_directories(&state_path, cache_path); + builder.address_filter().allow_onion_addrs(true); + + // Configure bridge. + if let Some(bridge_line) = tor_config.bridge.bridge_line.as_ref() { + let bridge: BridgeConfigBuilder = bridge_line + .parse() + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + builder.bridges().bridges().push(bridge.clone()); + match bridge.get_transport() { + None => { + return Err(Error::TorConfig(format!( + "No transport found at {}", + bridge_line + ))) + } + Some(t) => { + // Now configure bridge transport. (Requires the "pt-client" feature) + let bin_path = tor_config + .bridge + .bridge_bin_path + .clone() + .unwrap_or(t.to_owned()); + let mut transport = TransportConfigBuilder::default(); + transport + .protocols(vec![t + .parse() + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?]) + .path(CfgPath::new(bin_path)) + .run_on_startup(true); + builder.bridges().transports().push(transport); + } + } + } + let config = builder + .build() + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + + // Return existing client if config was not changed. + let mut cached_client_config = ARTI_CLIENT_CONFIG.lock().unwrap(); + if let Some((client, c)) = cached_client_config.as_ref() { + if c == &config { + debug!("Reusing Arti Tor client from global state."); + return Ok((client.clone(), c.clone())); + } else { + debug!("Tor config changed, rebuild client."); + *cached_client_config = None; + } + } + let res = launch_client(config.clone(), &tor_config); + match res { + Ok(client) => { + cached_client_config.replace((client.clone(), config.clone())); + Ok((client, config)) + } + Err(e) => Err(e), + } +} + +/// Launch tor client from provided configuration. +fn launch_client( + client_config: TorClientConfig, + tor_config: &TorConfig, +) -> Result>, Error> { + let r = runtime()?; + let client = TorClient::with_runtime(r) + .config(client_config) + .create_unbootstrapped() + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let c = client.clone(); + let timeout = tor_config.bootstrap_timeout(); + let res = client.runtime().block_on(async move { + let bootstrap = async || { + return match c.bootstrap().await { + Ok(_) => { + let mut percent = 0.0; + let mut prev_percent = 0.0; + while percent < 1.0 { + percent = c.bootstrap_status().as_frac(); + if percent != prev_percent { + info!("Starting Tor {}%", percent * 100.0); + } + prev_percent = percent; + tokio::time::sleep(Duration::from_millis(1000)).await; + } + info!("Tor client bootstrapped successfully"); + Ok(()) + } + Err(e) => Err(e), + }; + }; + match c.runtime().timeout(timeout, bootstrap()).await { + Ok(r) => match r { + Err(e) => Err(Error::TorProcess(format!("{:?}", e))), + Ok(_) => Ok(c), + }, + Err(e) => Err(Error::TorProcess(format!("{:?}", e))), + } + }); + res +} + +/// Create Onion service proxy. +fn create_service_proxy(addr: SocketAddr) -> Result, Error> { + // Setup proxy to forward request from Tor address to local address. + let proxy_rule = ProxyRule::new( + ProxyPattern::one_port(80).map_err(|e| Error::TorConfig(format!("{}", e)))?, + ProxyAction::Forward(Encapsulation::Simple, TargetAddr::Inet(addr)), + ); + let mut proxy_cfg_builder = ProxyConfigBuilder::default(); + proxy_cfg_builder.set_proxy_ports(vec![proxy_rule]); + let proxy_cfg = proxy_cfg_builder + .build() + .map_err(|e| Error::TorConfig(format!("{}", e)))?; + let proxy = OnionServiceReverseProxy::new(proxy_cfg); + Ok(proxy) +} + +/// Launch service proxy. +async fn run_service_proxy( + proxy: Arc, + request: &mut S, + nickname: HsNickname, +) -> Result<(), Error> +where + S: futures::Stream + Unpin + Send + 'static, +{ + let runtime = runtime()?; + proxy + .handle_requests(runtime, nickname, request) + .await + .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + Ok(()) +} + +/// Save Onion service key to keystore. +fn add_service_key( + mistrust: &Mistrust, + key: &SecretKey, + hs_nickname: &HsNickname, + path: PathBuf, +) -> Result<(), Error> { + let arti_store = ArtiNativeKeystore::from_path_and_mistrust(path, mistrust) + .map_err(|e| Error::TorProcess(format!("{}", e)))?; + + let key_manager = KeyMgrBuilder::default() + .primary_store(Box::new(arti_store)) + .build() + .map_err(|e| Error::TorProcess(format!("{}", e)))?; + + let expanded_sk = + ExpandedSecretKey::from_bytes(Sha512::default().chain_update(key).finalize().as_ref()); + let sk_bytes = exp_sec_key_bytes(expanded_sk); + match ExpandedKeypair::from_secret_key_bytes(sk_bytes) { + None => { + return Err(Error::TorProcess( + "Hidden service key can not be created".into(), + )) + } + Some(expanded_kp) => { + key_manager + .insert( + HsIdKey::from(expanded_kp.public().clone()), + &HsIdPublicKeySpecifier::new(hs_nickname.clone()), + KeystoreSelector::Primary, + true, + ) + .map_err(|e| Error::TorProcess(format!("{}", e)))?; + key_manager + .insert( + HsIdKeypair::from(expanded_kp), + &HsIdKeypairSpecifier::new(hs_nickname.clone()), + KeystoreSelector::Primary, + true, + ) + .map_err(|e| Error::TorProcess(format!("{}", e)))?; + } + } + Ok(()) +} diff --git a/impls/src/tor/config.rs b/impls/src/tor/config.rs index d5e0374..422fae1 100644 --- a/impls/src/tor/config.rs +++ b/impls/src/tor/config.rs @@ -17,9 +17,9 @@ use crate::util::secp::key::SecretKey; use crate::Error; use grin_wallet_util::OnionV3Address; -use ed25519_dalek::ExpandedSecretKey; -use ed25519_dalek::PublicKey as DalekPublicKey; -use ed25519_dalek::SecretKey as DalekSecretKey; +use ed25519_dalek::hazmat::ExpandedSecretKey; +use ed25519_dalek::SigningKey as DalekSecretKey; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use std::collections::HashMap; use std::convert::TryFrom; use std::fs::{self, File}; @@ -92,6 +92,14 @@ impl TorRcConfig { } } +/// Convert expanded secret key to byte array (works for both external Tor process and Arti). +pub(crate) fn exp_sec_key_bytes(expanded_sk: ExpandedSecretKey) -> [u8; 64] { + let mut sk_bytes = [0_u8; 64]; + sk_bytes[0..32].copy_from_slice(&expanded_sk.scalar.to_bytes()); + sk_bytes[32..64].copy_from_slice(&expanded_sk.hash_prefix); + sk_bytes +} + pub fn create_onion_service_sec_key_file( os_directory: &str, sec_key: &DalekSecretKey, @@ -101,9 +109,9 @@ pub fn create_onion_service_sec_key_file( // Tag is always 32 bytes, so pad with null zeroes file.write(b"== ed25519v1-secret: type0 ==\0\0\0") .map_err(|_| Error::IO)?; - let expanded_skey: ExpandedSecretKey = ExpandedSecretKey::from(sec_key); - file.write_all(&expanded_skey.to_bytes()) - .map_err(|_| Error::IO)?; + let expanded_skey: ExpandedSecretKey = ExpandedSecretKey::from(sec_key.as_bytes()); + let sk_bytes = exp_sec_key_bytes(expanded_skey); + file.write_all(&sk_bytes).map_err(|_| Error::IO)?; Ok(()) } @@ -138,8 +146,7 @@ pub fn output_onion_service_config( tor_config_directory: &str, sec_key: &SecretKey, ) -> Result { - let d_sec_key = DalekSecretKey::from_bytes(&sec_key.0) - .map_err(|_| Error::ED25519Key("Unable to parse private key".into()))?; + let d_sec_key = DalekSecretKey::from_bytes(&sec_key.0); let address = OnionV3Address::from_private(&sec_key.0)?; let hs_dir_file_path = format!( "{}{}{}{}{}", @@ -291,7 +298,7 @@ mod tests { use crate::util::{self, secp, static_secp_instance}; pub fn clean_output_dir(test_dir: &str) { - let _ = remove_dir_all::remove_dir_all(test_dir); + let _ = fs::remove_dir_all(test_dir); } pub fn setup(test_dir: &str) { diff --git a/impls/src/tor/mod.rs b/impls/src/tor/mod.rs index 37821c9..9eb97ec 100644 --- a/impls/src/tor/mod.rs +++ b/impls/src/tor/mod.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +pub mod arti; pub mod bridge; pub mod config; pub mod process; diff --git a/impls/src/tor/process.rs b/impls/src/tor/process.rs index f964326..4e53f8e 100644 --- a/impls/src/tor/process.rs +++ b/impls/src/tor/process.rs @@ -51,13 +51,13 @@ extern crate timer; use regex::Regex; use std::fs::{self, File}; -use std::io; use std::io::Write; use std::io::{BufRead, BufReader}; use std::path::{Path, MAIN_SEPARATOR}; use std::process::{Child, ChildStdout, Command, Stdio}; use std::sync::mpsc::channel; use std::thread; +use std::{cmp, io}; use sysinfo::{Process, ProcessExt, System, SystemExt}; #[cfg(windows)] @@ -83,7 +83,7 @@ pub struct TorProcess { args: Vec, torrc_path: Option, completion_percent: u8, - timeout: u32, + timeout: u64, working_dir: Option, pub stdout: Option>, pub process: Option, @@ -96,8 +96,8 @@ impl TorProcess { tor_cmd: TOR_EXE_NAME.to_string(), args: vec![], torrc_path: None, - completion_percent: 100 as u8, - timeout: 0 as u32, + completion_percent: 100, + timeout: 0, working_dir: None, stdout: None, process: None, @@ -137,7 +137,7 @@ impl TorProcess { self } - pub fn timeout(&mut self, timeout: u32) -> &mut Self { + pub fn timeout(&mut self, timeout: u64) -> &mut Self { self.timeout = timeout; self } @@ -198,10 +198,11 @@ impl TorProcess { let stdout_timeout_tx = stdout_tx.clone(); let timer = timer::Timer::new(); - let _guard = - timer.schedule_with_delay(chrono::Duration::seconds(self.timeout as i64), move || { - stdout_timeout_tx.send(Err(Error::Timeout)).unwrap_or(()); - }); + // Keep this below chrono's DateTime range used by timer. + let timeout = chrono::Duration::seconds(cmp::min(self.timeout, u32::MAX as u64) as i64); + let _guard = timer.schedule_with_delay(timeout, move || { + stdout_timeout_tx.send(Err(Error::Timeout)).unwrap_or(()); + }); let stdout_thread = thread::spawn(move || { stdout_tx .send(Self::parse_tor_stdout(stdout, completion_percent)) @@ -225,8 +226,8 @@ impl TorProcess { mut stdout: BufReader, completion_perc: u8, ) -> Result, Error> { - let re_bootstrap = Regex::new(r"^\[notice\] Bootstrapped (?P[0-9]+)%(.*): ") - .map_err(Error::Regex)?; + let re_bootstrap = + Regex::new(r"^\[notice] Bootstrapped (?P[0-9]+)%(.*): ").map_err(Error::Regex)?; let timestamp_len = "May 16 02:50:08.792".len(); let mut warnings = Vec::new(); diff --git a/integration/tests/framework.rs b/integration/tests/framework.rs index ffade00..3e0b883 100644 --- a/integration/tests/framework.rs +++ b/integration/tests/framework.rs @@ -37,7 +37,7 @@ use std::{fs, thread, time}; /// Just removes all results from previous runs pub fn clean_all_output(test_name_dir: &str) { let target_dir = format!("target/tmp/{}", test_name_dir); - if let Err(e) = remove_dir_all::remove_dir_all(target_dir) { + if let Err(e) = fs::remove_dir_all(target_dir) { println!("can't remove output from previous test :{}, may be ok", e); } } @@ -281,7 +281,11 @@ impl LocalServerContainer { let _ = fs::create_dir_all(self.wallet_config.clone().data_file_dir); let r = wallet::WalletSeed::init_file(&self.wallet_config, 32, None, ""); - let client_n = HTTPNodeClient::new(&self.wallet_config.check_node_api_http_addr, None); + let client_n = HTTPNodeClient::new( + &self.wallet_config.check_node_api_http_addr, + None, + std::time::Duration::from_secs(60), + ); if let Err(_e) = r { //panic!("Error initializing wallet seed: {}", e); @@ -354,7 +358,11 @@ impl LocalServerContainer { let keychain: keychain::ExtKeychain = wallet_seed .derive_keychain(false) .expect("Failed to derive keychain from seed file and passphrase."); - let client_n = HTTPNodeClient::new(&config.check_node_api_http_addr, None); + let client_n = HTTPNodeClient::new( + &config.check_node_api_http_addr, + None, + std::time::Duration::from_secs(60), + ); let mut wallet = LMDBBackend::new(config.clone(), "", client_n) .unwrap_or_else(|e| panic!("Error creating wallet: {:?} Config: {:?}", e, config)); wallet.keychain = Some(keychain); @@ -382,7 +390,11 @@ impl LocalServerContainer { .derive_keychain(false) .expect("Failed to derive keychain from seed file and passphrase."); - let client_n = HTTPNodeClient::new(&config.check_node_api_http_addr, None); + let client_n = HTTPNodeClient::new( + &config.check_node_api_http_addr, + None, + std::time::Duration::from_secs(60), + ); let client_w = HTTPWalletCommAdapter::new(); let max_outputs = 500; diff --git a/integration/tests/simulnet.rs b/integration/tests/simulnet.rs index df407ec..f3e9b09 100644 --- a/integration/tests/simulnet.rs +++ b/integration/tests/simulnet.rs @@ -908,7 +908,11 @@ fn replicate_tx_fluff_failure() { // Create Wallet 1 (Mining Input) and start it listening // Wallet 1 post to another node, just for fun - let client1 = HTTPNodeClient::new("http://127.0.0.1:23003", None); + let client1 = HTTPNodeClient::new( + "http://127.0.0.1:23003", + None, + std::time::Duration::from_secs(60), + ); let client1_w = HTTPWalletCommAdapter::new(); let wallet1 = create_wallet("target/tmp/tx_fluff/wallet1", client1.clone()); let _wallet1_handle = thread::spawn(move || { @@ -917,7 +921,11 @@ fn replicate_tx_fluff_failure() { }); // Create Wallet 2 (Recipient) and launch - let client2 = HTTPNodeClient::new("http://127.0.0.1:23001", None); + let client2 = HTTPNodeClient::new( + "http://127.0.0.1:23001", + None, + std::time::Duration::from_secs(60), + ); let wallet2 = create_wallet("target/tmp/tx_fluff/wallet2", client2.clone()); let _wallet2_handle = thread::spawn(move || { controller::foreign_listener(wallet2, "127.0.0.1:33001", None) diff --git a/libwallet/Cargo.toml b/libwallet/Cargo.toml index 2a1890b..b2770aa 100644 --- a/libwallet/Cargo.toml +++ b/libwallet/Cargo.toml @@ -1,13 +1,12 @@ [package] name = "grin_wallet_libwallet" -version = "5.4.0-alpha.1" +version = "5.4.1" authors = ["Grin Developers "] description = "Simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format." license = "Apache-2.0" repository = "https://github.com/mimblewimble/grin-wallet" keywords = [ "crypto", "grin", "mimblewimble" ] exclude = ["**/*.grin", "**/*.grin2"] -#build = "src/build/build.rs" edition = "2021" [dependencies] @@ -18,21 +17,20 @@ serde_derive = "1" serde_with = { version = "1", features = ["chrono"] } serde_json = "1" log = "0.4" -uuid = { version = "0.8", features = ["serde", "v4"] } +uuid = { version = "1.23.4", features = ["serde", "v4"] } chrono = { version = "0.4.11", features = ["serde"] } lazy_static = "1" strum = "0.18" strum_macros = "0.18" thiserror = "1" -ed25519-dalek = "1.0.0-pre.4" -x25519-dalek = "0.6" +ed25519-dalek = "2" +x25519-dalek = { version = "2", features = ["static_secrets"] } base64 = "0.9" regex = "1.3" sha2 = "0.10.0" bs58 = "0.3" -age = "0.7" -curve25519-dalek = "2.1" -secrecy = "0.6" +age = "0.8" +curve25519-dalek = "5" bech32 = "0.7" byteorder = "1.3" num-bigint = "0.2" @@ -41,34 +39,14 @@ num-bigint = "0.2" chacha20 = "0.8.1" hmac = { version = "0.12.0", features = ["std"]} -grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" } -grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" } +grin_wallet_util = { path = "../util", version = "5.4.1" } +grin_wallet_config = { path = "../config", version = "5.4.1" } ##### Grin Imports -# For Release -#grin_core = "5.4.0" -#grin_keychain = "5.4.0" -#grin_util = "5.4.0" -#grin_store = "5.4.0" - -# For beta release - -# grin_core = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3"} -# grin_keychain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } -# grin_store = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } - -# For bleeding edge -grin_core = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_keychain = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_util = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } -grin_store = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } - -# For local testing -# grin_core = { path = "../../grin/core"} -# grin_keychain = { path = "../../grin/keychain"} -# grin_util = { path = "../../grin/util"} -# grin_store = { path = "../../grin/store"} +grin_core = { path = "../grin/core"} +grin_keychain = { path = "../grin/keychain"} +grin_util = { path = "../grin/util"} +grin_store = { path = "../grin/store"} ##### diff --git a/libwallet/src/api_impl/foreign.rs b/libwallet/src/api_impl/foreign.rs index 144d61d..7a9cc63 100644 --- a/libwallet/src/api_impl/foreign.rs +++ b/libwallet/src/api_impl/foreign.rs @@ -14,13 +14,13 @@ //! Generic implementation of owner API functions -use grin_keychain::Identifier; use strum::IntoEnumIterator; use super::owner::tx_lock_outputs; use crate::api_impl::owner::contract_new as owner_contract_new; use crate::api_impl::owner::contract_sign as owner_contract_sign; use crate::api_impl::owner::{check_ttl, post_tx}; +use crate::api_impl::types::update_tx_slate_state; use crate::backend::WalletBackend; use crate::contract::proofs::InvoiceProof; use crate::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI}; @@ -32,7 +32,7 @@ use crate::slate_versions::SlateVersion; use crate::{ address, BlockFees, CbData, Error, NodeClient, Slate, SlateState, TxLogEntryType, VersionInfo, }; -use ed25519_dalek::PublicKey as DalekPublicKey; +use ed25519_dalek::VerifyingKey as DalekPublicKey; const FOREIGN_API_VERSION: u16 = 2; @@ -244,42 +244,6 @@ where Ok(sl) } -/// Update transaction slate state. -fn update_tx_slate_state( - wallet: &mut WalletBackend, - keychain_mask: Option<&SecretKey>, - parent_key_id: &Identifier, - slate: &Slate, -) -> Result<(), Error> -where - C: NodeClient, - K: Keychain, -{ - let mut bad_records = 0; - let tx = wallet - .tx_log_iter()? - .filter(|tx| { - if tx.is_err() { - bad_records += 1; - } - tx.is_ok() - }) - .map(|tx| tx.unwrap()) - .find(|tx| tx.tx_slate_id == Some(slate.id)); - if let Some(mut tx) = tx { - let mut batch = wallet.batch(keychain_mask)?; - tx.tx_slate_state = Some(slate.state.clone()); - batch.save_tx_log_entry(tx.clone(), parent_key_id)?; - batch.commit()?; - } else { - return Err(Error::Backend(format!( - "Tx log entry with slate id {} not found, there are {} bad tx log records", - slate.id, bad_records - ))); - } - Ok(()) -} - /// Initialize a receive transaction contract pub fn contract_new( w: &mut WalletBackend, diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index abfd899..a5f6144 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -45,9 +45,9 @@ use crate::{ WalletInitStatus, WalletInst, WalletLCProvider, }; use chrono::prelude::{DateTime, NaiveDateTime, Utc}; -use ed25519_dalek::PublicKey as DalekPublicKey; -use ed25519_dalek::SecretKey as DalekSecretKey; +use ed25519_dalek::SigningKey as DalekSecretKey; use ed25519_dalek::Verifier; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use x25519_dalek::{PublicKey as xPublicKey, StaticSecret}; use std::convert::{TryFrom, TryInto}; @@ -137,16 +137,7 @@ where let parent_key_id = w.parent_key_id(); let k = w.keychain(keychain_mask)?; let sec_addr_key = address::address_from_derivation_path(&k, &parent_key_id, index)?; - let d_skey = match DalekSecretKey::from_bytes(&sec_addr_key.0) { - Ok(k) => k, - Err(e) => { - return Err(OnionV3AddressError::InvalidPrivateKey(format!( - "Unable to create secret key: {}", - e - )) - .into()); - } - }; + let d_skey = DalekSecretKey::from_bytes(&sec_addr_key.0); Ok(d_skey) } @@ -1386,12 +1377,7 @@ where // for now, simple test whether one of the addresses belongs to this wallet let sec_key = address::address_from_derivation_path(&keychain, &parent_key_id, 0)?; - let d_skey = match DalekSecretKey::from_bytes(&sec_key.0) { - Ok(k) => k, - Err(e) => { - return Err(Error::ED25519Key(format!("{}", e))); - } - }; + let d_skey = DalekSecretKey::from_bytes(&sec_key.0); let my_address_pubkey: DalekPublicKey = (&d_skey).into(); let sender_mine = my_address_pubkey == sender_pubkey; diff --git a/libwallet/src/api_impl/types.rs b/libwallet/src/api_impl/types.rs index e59c515..d87a7bd 100644 --- a/libwallet/src/api_impl/types.rs +++ b/libwallet/src/api_impl/types.rs @@ -21,10 +21,12 @@ use crate::grin_util::secp::pedersen; use crate::slate_versions::ser as dalek_ser; use crate::slate_versions::SlateVersion; use crate::types::OutputData; -use crate::SlatepackAddress; +use crate::{Error, NodeClient, Slate, SlatepackAddress, WalletBackend}; use chrono::prelude::*; use ed25519_dalek::Signature as DalekSignature; +use grin_keychain::Keychain; +use grin_util::secp::SecretKey; pub use crate::mwixnet::{Hop, MixnetReqCreationParams, SwapReq}; @@ -102,7 +104,7 @@ pub struct InitTxSendArgs { /// Whether to use dandelion when posting. If false, skip the dandelion relay pub fluff: bool, /// If set, skip the Slatepack TOR send attempt - pub skip_tor: bool, + pub skip_tor: Option, } impl Default for InitTxArgs { @@ -347,3 +349,39 @@ pub struct BuiltOutput { /// Output pub output: Output, } + +/// Update transaction slate state. +pub fn update_tx_slate_state( + wallet: &mut WalletBackend, + keychain_mask: Option<&SecretKey>, + parent_key_id: &Identifier, + slate: &Slate, +) -> Result<(), Error> +where + C: NodeClient, + K: Keychain, +{ + let mut bad_records = 0; + let tx = wallet + .tx_log_iter()? + .filter(|tx| { + if tx.is_err() { + bad_records += 1; + } + tx.is_ok() + }) + .map(|tx| tx.unwrap()) + .find(|tx| tx.tx_slate_id == Some(slate.id)); + if let Some(mut tx) = tx { + let mut batch = wallet.batch(keychain_mask)?; + tx.tx_slate_state = Some(slate.state.clone()); + batch.save_tx_log_entry(tx.clone(), parent_key_id)?; + batch.commit()?; + } else { + return Err(Error::Backend(format!( + "Tx log entry with slate id {} not found, there are {} bad tx log records", + slate.id, bad_records + ))); + } + Ok(()) +} diff --git a/libwallet/src/contract/proofs.rs b/libwallet/src/contract/proofs.rs index 0874482..747f069 100644 --- a/libwallet/src/contract/proofs.rs +++ b/libwallet/src/contract/proofs.rs @@ -16,6 +16,7 @@ //! with contracts. Can move outside of this module if early proofs are adopted //! by legacy transactions +use crate::backend::WalletBackend; use crate::contract::types::ProofArgs; use crate::grin_core::libtx::aggsig; use crate::grin_core::libtx::secp_ser; @@ -29,14 +30,12 @@ use crate::grin_util::static_secp_instance; use crate::slate::{PaymentInfo, PaymentMemo, Slate}; use crate::slate_versions::ser as dalek_ser; use crate::types::{Context, NodeClient}; -use crate::backend::WalletBackend; use crate::{address, Error}; use byteorder::{BigEndian, ByteOrder}; use chrono::{DateTime, NaiveDateTime, Utc}; -use ed25519_dalek::Keypair as DalekKeypair; -use ed25519_dalek::PublicKey as DalekPublicKey; -use ed25519_dalek::SecretKey as DalekSecretKey; use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::SigningKey as DalekSecretKey; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use ed25519_dalek::{Signer, Verifier}; use grin_util::secp::Message; use std::convert::TryInto; @@ -159,7 +158,9 @@ impl Readable for InvoiceProofBin { } let sender_address_vec = reader.read_fixed_bytes(32)?; - let sender_address = DalekPublicKey::from_bytes(&sender_address_vec).unwrap(); + let sender_address_bytes = <&[u8; 32]>::try_from(sender_address_vec.as_slice()) + .map_err(|_| grin_ser::Error::CorruptedData)?; + let sender_address = DalekPublicKey::from_bytes(sender_address_bytes).unwrap(); let timestamp = reader.read_i64()?; @@ -254,22 +255,14 @@ impl InvoiceProof { /// Sign the invoice proof, provided all fields are populated pub fn sign(&self, sec_key: &SecretKey) -> Result<(DalekSignature, DalekPublicKey), Error> { - let d_skey = match DalekSecretKey::from_bytes(&sec_key.0) { - Ok(k) => k, - Err(e) => { - return Err(Error::ED25519Key(format!("{}", e))); - } - }; - let pub_key: DalekPublicKey = (&d_skey).into(); - let keypair = DalekKeypair { - public: pub_key, - secret: d_skey, - }; + let d_skey = DalekSecretKey::from_bytes(&sec_key.0); + let pub_key = d_skey.verifying_key(); let mut sig_data_bin = Vec::new(); - grin_ser::serialize_default(&mut sig_data_bin, &InvoiceProofBin(self.clone())) - .map_err(|e| Error::GenericError(format!("InvoiceProof serialization failed: {}", e)))?; + grin_ser::serialize_default(&mut sig_data_bin, &InvoiceProofBin(self.clone())).map_err( + |e| Error::GenericError(format!("InvoiceProof serialization failed: {}", e)), + )?; - Ok((keypair.sign(&sig_data_bin), pub_key)) + Ok((d_skey.sign(&sig_data_bin), pub_key)) } /// Verify the signature of the invoice proof @@ -285,8 +278,9 @@ impl InvoiceProof { // Rebuild message let mut sig_data_bin = Vec::new(); - grin_ser::serialize_default(&mut sig_data_bin, &InvoiceProofBin(self.clone())) - .map_err(|e| Error::GenericError(format!("InvoiceProof serialization failed: {}", e)))?; + grin_ser::serialize_default(&mut sig_data_bin, &InvoiceProofBin(self.clone())).map_err( + |e| Error::GenericError(format!("InvoiceProof serialization failed: {}", e)), + )?; if recipient_address .verify(&sig_data_bin, self.promise_signature.as_ref().unwrap()) diff --git a/libwallet/src/contract/slate.rs b/libwallet/src/contract/slate.rs index 7c5810c..aeb0498 100644 --- a/libwallet/src/contract/slate.rs +++ b/libwallet/src/contract/slate.rs @@ -14,18 +14,18 @@ //! Contract functions on the Slate +use crate::backend::WalletBackend; use crate::grin_core::libtx::build; use crate::grin_core::libtx::proof::ProofBuilder; use crate::grin_keychain::Keychain; use crate::grin_util::secp::key::{PublicKey, SecretKey}; use crate::slate::{Slate, SlateState}; use crate::types::{Context, NodeClient}; -use crate::backend::WalletBackend; use crate::Error; use super::types::ProofArgs; use crate::contract::proofs::InvoiceProof; -use ed25519_dalek::PublicKey as DalekPublicKey; +use ed25519_dalek::VerifyingKey as DalekPublicKey; /// Add payment proof data to slate, noop for sender pub fn add_payment_proof( diff --git a/libwallet/src/contract/types.rs b/libwallet/src/contract/types.rs index 97cc387..06f6af7 100644 --- a/libwallet/src/contract/types.rs +++ b/libwallet/src/contract/types.rs @@ -16,7 +16,7 @@ use crate::error::Error; use crate::slate_versions::ser as dalek_ser; -use ed25519_dalek::PublicKey as DalekPublicKey; +use ed25519_dalek::VerifyingKey as DalekPublicKey; /// Output selection args #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] diff --git a/libwallet/src/error.rs b/libwallet/src/error.rs index ee64d47..1863d2d 100644 --- a/libwallet/src/error.rs +++ b/libwallet/src/error.rs @@ -350,6 +350,12 @@ pub enum Error { GenericError(String), } +impl From for Error { + fn from(error: grin_wallet_config::ConfigError) -> Error { + Error::GenericError(format!("{}", error)) + } +} + impl From for Error { fn from(error: grin_store::Error) -> Error { // Preserve "not found" so callers can distinguish a missing item from other diff --git a/libwallet/src/internal/tx.rs b/libwallet/src/internal/tx.rs index bf8967a..da2b6dd 100644 --- a/libwallet/src/internal/tx.rs +++ b/libwallet/src/internal/tx.rs @@ -30,10 +30,9 @@ use crate::types::{Context, NodeClient, StoredProofInfo, TxLogEntryType}; use crate::util::OnionV3Address; use crate::{address, Error}; use crate::{InitTxArgs, WalletBackend}; -use ed25519_dalek::Keypair as DalekKeypair; -use ed25519_dalek::PublicKey as DalekPublicKey; -use ed25519_dalek::SecretKey as DalekSecretKey; use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::SigningKey as DalekSecretKey; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use ed25519_dalek::{Signer, Verifier}; use grin_core::core::FeeFields; @@ -494,18 +493,8 @@ pub fn create_payment_proof_signature( sec_key: SecretKey, ) -> Result { let msg = payment_proof_message(amount, kernel_commitment, sender_address)?; - let d_skey = match DalekSecretKey::from_bytes(&sec_key.0) { - Ok(k) => k, - Err(e) => { - return Err(Error::ED25519Key(format!("{}", e))); - } - }; - let pub_key: DalekPublicKey = (&d_skey).into(); - let keypair = DalekKeypair { - public: pub_key, - secret: d_skey, - }; - Ok(keypair.sign(&msg)) + let d_skey = DalekSecretKey::from_bytes(&sec_key.0); + Ok(d_skey.sign(&msg)) } /// Verify all aspects of a completed payment proof on the current slate @@ -650,7 +639,7 @@ mod test { let secp = secp_inst.lock(); let mut test_rng = StepRng::new(1_234_567_890_u64, 1); let sec_key = secp::key::SecretKey::new(&secp, &mut test_rng); - let d_skey = DalekSecretKey::from_bytes(&sec_key.0).unwrap(); + let d_skey = DalekSecretKey::from_bytes(&sec_key.0); let address: DalekPublicKey = (&d_skey).into(); diff --git a/libwallet/src/mwixnet/onion/crypto/comsig.rs b/libwallet/src/mwixnet/onion/crypto/comsig.rs index bf9e347..89eb8f8 100644 --- a/libwallet/src/mwixnet/onion/crypto/comsig.rs +++ b/libwallet/src/mwixnet/onion/crypto/comsig.rs @@ -204,7 +204,6 @@ mod tests { use super::{ComSigError, ComSignature, ContextFlag, Secp256k1, SecretKey}; use grin_util::secp::rand::{thread_rng, RngCore}; - use rand::Rng; /// Test signing and verification of ComSignatures #[test] @@ -213,13 +212,13 @@ mod tests { let amount = thread_rng().next_u64(); let blind = SecretKey::new(&secp, &mut thread_rng()); - let msg: [u8; 16] = rand::thread_rng().gen(); + let msg: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; let comsig = ComSignature::sign(amount, &blind, &msg.to_vec(), false)?; let commit = secp.commit(amount, blind.clone())?; assert!(comsig.verify(&commit, &msg.to_vec()).is_ok()); - let wrong_msg: [u8; 16] = rand::thread_rng().gen(); + let wrong_msg: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17]; assert!(comsig.verify(&commit, &wrong_msg.to_vec()).is_err()); let wrong_commit = secp.commit(amount, SecretKey::new(&secp, &mut thread_rng()))?; diff --git a/libwallet/src/mwixnet/onion/crypto/dalek.rs b/libwallet/src/mwixnet/onion/crypto/dalek.rs index 38fd408..62084dd 100644 --- a/libwallet/src/mwixnet/onion/crypto/dalek.rs +++ b/libwallet/src/mwixnet/onion/crypto/dalek.rs @@ -14,9 +14,10 @@ //! Dalek key wrapper for mwixnet primitives +use ed25519_dalek::Verifier; use grin_util::secp::key::SecretKey; -use ed25519_dalek::{PublicKey, Signature, Verifier}; +use ed25519_dalek::VerifyingKey; use grin_core::ser::{self, Readable, Reader, Writeable, Writer}; use grin_util::ToHex; use thiserror::Error; @@ -37,7 +38,7 @@ pub enum DalekError { /// Encapsulates an ed25519_dalek::PublicKey and provides (de-)serialization #[derive(Clone, Debug, PartialEq)] -pub struct DalekPublicKey(PublicKey); +pub struct DalekPublicKey(VerifyingKey); impl DalekPublicKey { /// Convert DalekPublicKey to hex string @@ -47,23 +48,23 @@ impl DalekPublicKey { /// Convert hex string to DalekPublicKey. pub fn from_hex(hex: &str) -> Result { - let bytes = grin_util::from_hex(hex) - .map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?; - let pk = PublicKey::from_bytes(bytes.as_ref()) - .map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?; + let err = DalekError::HexError(format!("failed to decode {}", hex)); + let bytes = grin_util::from_hex(hex).map_err(|_| err.clone())?; + let b = <&[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| err.clone())?; + let pk = VerifyingKey::from_bytes(b).map_err(|_| err)?; Ok(DalekPublicKey(pk)) } /// Compute DalekPublicKey from a SecretKey pub fn from_secret(key: &SecretKey) -> Self { - let secret = ed25519_dalek::SecretKey::from_bytes(&key.0).unwrap(); - let pk: PublicKey = (&secret).into(); + let secret = ed25519_dalek::SigningKey::from_bytes(&key.0); + let pk: VerifyingKey = (&secret).into(); DalekPublicKey(pk) } } -impl AsRef for DalekPublicKey { - fn as_ref(&self) -> &PublicKey { +impl AsRef for DalekPublicKey { + fn as_ref(&self) -> &VerifyingKey { &self.0 } } @@ -103,8 +104,9 @@ pub mod option_dalek_pubkey_serde { impl Readable for DalekPublicKey { fn read(reader: &mut R) -> Result { - let pk = PublicKey::from_bytes(&reader.read_fixed_bytes(32)?) - .map_err(|_| ser::Error::CorruptedData)?; + let bytes = reader.read_fixed_bytes(32)?; + let b = <&[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| ser::Error::CorruptedData)?; + let pk = VerifyingKey::from_bytes(b).map_err(|_| ser::Error::CorruptedData)?; Ok(DalekPublicKey(pk)) } } @@ -119,7 +121,7 @@ impl Writeable for DalekPublicKey { /// Encapsulates an ed25519_dalek::Signature and provides (de-)serialization #[allow(dead_code)] #[derive(Clone, Debug, PartialEq)] -pub struct DalekSignature(Signature); +pub struct DalekSignature(ed25519_dalek::Signature); impl DalekSignature { /// Convert hex string to DalekSignature. @@ -127,7 +129,9 @@ impl DalekSignature { pub fn from_hex(hex: &str) -> Result { let bytes = grin_util::from_hex(hex) .map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?; - let sig = Signature::from_bytes(bytes.as_ref()) + let b = <[u8; 64]>::try_from(bytes.as_slice()) + .map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?; + let sig = ed25519_dalek::Signature::try_from(b) .map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?; Ok(DalekSignature(sig)) } @@ -141,8 +145,8 @@ impl DalekSignature { } } -impl AsRef for DalekSignature { - fn as_ref(&self) -> &Signature { +impl AsRef for DalekSignature { + fn as_ref(&self) -> &ed25519_dalek::Signature { &self.0 } } @@ -160,7 +164,7 @@ pub mod dalek_sig_serde { where S: Serializer, { - serializer.serialize_str(&sig.0.to_hex()) + serializer.serialize_str(&sig.0.to_bytes().to_hex()) } /// @@ -178,22 +182,19 @@ pub mod dalek_sig_serde { // TODO: This is likely duplicated throughout crate, check #[cfg(test)] pub fn sign(sk: &SecretKey, message: &[u8]) -> Result { - use ed25519_dalek::{Keypair, Signer}; - let secret = - ed25519_dalek::SecretKey::from_bytes(&sk.0).map_err(|_| DalekError::KeyParseError)?; - let public: PublicKey = (&secret).into(); - let keypair = Keypair { secret, public }; - let sig = keypair.sign(&message); + use ed25519_dalek::{Signer, SigningKey}; + let secret = SigningKey::from_bytes(&sk.0); + let sig = secret.sign(&message); Ok(DalekSignature(sig)) } #[cfg(test)] mod tests { use super::*; + use crate::mwixnet::onion::crypto::secp::Secp256k1; use crate::mwixnet::onion::test_util::rand_keypair; use grin_core::ser::{self, ProtocolVersion}; use grin_util::ToHex; - use rand::Rng; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -262,23 +263,27 @@ mod tests { #[test] fn sig_test() -> Result<(), Box> { // Sign a message - let (sk, pk) = rand_keypair(); - let msg: [u8; 16] = rand::thread_rng().gen(); + let s = Secp256k1::new(); + let sk = SecretKey::from_slice(&s, &[1; 32]).unwrap(); + let pk = DalekPublicKey::from_secret(&sk); + + let msg: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; let sig = sign(&sk, &msg).unwrap(); // Verify signature assert!(sig.verify(&pk, &msg).is_ok()); // Wrong message - let wrong_msg: [u8; 16] = rand::thread_rng().gen(); + let wrong_msg: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17]; assert!(sig.verify(&pk, &wrong_msg).is_err()); // Wrong pubkey - let wrong_pk = rand_keypair().1; + let wrong_sk = SecretKey::from_slice(&s, &[2; 32]).unwrap(); + let wrong_pk = DalekPublicKey::from_secret(&wrong_sk); assert!(sig.verify(&wrong_pk, &msg).is_err()); // Test from_hex - let sig_from_hex = DalekSignature::from_hex(sig.0.to_hex().as_str()).unwrap(); + let sig_from_hex = DalekSignature::from_hex(sig.0.to_bytes().to_hex().as_str()).unwrap(); assert_eq!(sig.0, sig_from_hex.0); // Test serde (de-)serialization @@ -286,7 +291,7 @@ mod tests { let val = serde_json::to_value(serde_test.clone()).unwrap(); if let Value::Object(o) = &val { if let Value::String(s) = o.get("sig").unwrap() { - assert_eq!(s, &sig.0.to_hex()); + assert_eq!(s, &sig.0.to_bytes().to_hex()); } else { panic!("Invalid type"); } diff --git a/libwallet/src/slate.rs b/libwallet/src/slate.rs index 677fac9..caccd86 100644 --- a/libwallet/src/slate.rs +++ b/libwallet/src/slate.rs @@ -29,8 +29,8 @@ use crate::grin_util::secp::pedersen::Commitment; use crate::grin_util::secp::Signature; use crate::grin_util::{secp, static_secp_instance}; use chrono::prelude::{DateTime, NaiveDateTime, Utc}; -use ed25519_dalek::PublicKey as DalekPublicKey; use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde::ser::{Serialize, Serializer}; use serde_json; use std::fmt; diff --git a/libwallet/src/slate_versions/mod.rs b/libwallet/src/slate_versions/mod.rs index 8a6efca..466516d 100644 --- a/libwallet/src/slate_versions/mod.rs +++ b/libwallet/src/slate_versions/mod.rs @@ -155,8 +155,8 @@ pub mod tests { slate, Error, Slate, Slatepacker, SlatepackerArgs, VersionedBinSlate, VersionedSlate, }; use chrono::{DateTime, NaiveDateTime, Utc}; - use ed25519_dalek::PublicKey as DalekPublicKey; use ed25519_dalek::Signature as DalekSignature; + use ed25519_dalek::VerifyingKey as DalekPublicKey; use grin_core::global::{set_local_chain_type, ChainTypes}; use grin_keychain::{ExtKeychain, Keychain, SwitchCommitmentType}; use std::convert::TryInto; @@ -225,7 +225,8 @@ pub mod tests { // current style payment proof let raw_pubkey_str = "d03c09e9c19bb74aa9ea44e0fe5ae237a9bf40bddf0941064a80913a4459c8bb"; let b = from_hex(raw_pubkey_str).unwrap(); - let d_pkey = DalekPublicKey::from_bytes(&b).unwrap(); + let b = <&[u8; 32]>::try_from(b.as_slice()).unwrap(); + let d_pkey = DalekPublicKey::from_bytes(b).unwrap(); // Need to remove milliseconds component for comparison. Won't be serialized let ts = NaiveDateTime::from_timestamp_opt(Utc::now().timestamp(), 0).unwrap(); let ts = DateTime::::from_utc(ts, Utc); @@ -234,7 +235,7 @@ pub mod tests { memo: [9; 32], }; - let psig = DalekSignature::from_bytes(&[0u8; 64]).unwrap(); + let psig = DalekSignature::from_bytes(&[0u8; 64]); slate_internal.payment_proof = Some(PaymentInfo { sender_address: Some(d_pkey.clone()), receiver_address: d_pkey.clone(), diff --git a/libwallet/src/slate_versions/ser.rs b/libwallet/src/slate_versions/ser.rs index 8d97ac3..845c351 100644 --- a/libwallet/src/slate_versions/ser.rs +++ b/libwallet/src/slate_versions/ser.rs @@ -131,7 +131,7 @@ pub mod ov3_serde { /// Serializes an ed25519 PublicKey to and from hex pub mod dalek_seckey_serde { use crate::grin_util::{from_hex, ToHex}; - use ed25519_dalek::SecretKey as DalekSecretKey; + use ed25519_dalek::SigningKey as DalekSecretKey; use serde::{Deserialize, Deserializer, Serializer}; /// @@ -151,7 +151,9 @@ pub mod dalek_seckey_serde { String::deserialize(deserializer) .and_then(|string| from_hex(&string).map_err(|err| Error::custom(err.to_string()))) .and_then(|bytes: Vec| { - DalekSecretKey::from_bytes(&bytes).map_err(|err| Error::custom(err.to_string())) + let b = <&[u8; 32]>::try_from(bytes.as_slice()) + .map_err(|_| Error::custom("Error deserializing secret key"))?; + Ok(DalekSecretKey::from_bytes(b)) }) } } @@ -159,7 +161,7 @@ pub mod dalek_seckey_serde { /// Serializes an ed25519 PublicKey to and from hex pub mod dalek_pubkey_serde { use crate::grin_util::{from_hex, ToHex}; - use ed25519_dalek::PublicKey as DalekPublicKey; + use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde::{Deserialize, Deserializer, Serializer}; /// @@ -179,12 +181,17 @@ pub mod dalek_pubkey_serde { String::deserialize(deserializer) .and_then(|string| from_hex(&string).map_err(|err| Error::custom(err.to_string()))) .and_then(|bytes: Vec| { - DalekPublicKey::from_bytes(&bytes).map_err(|err| Error::custom(err.to_string())) + let b = <&[u8; 32]>::try_from(bytes.as_slice()) + .map_err(|_| Error::custom("Error deserializing public key"))?; + Ok(match DalekPublicKey::from_bytes(b) { + Ok(pk) => pk, + Err(e) => return Err(Error::custom(format!("{:?}", e))), + }) }) } } -/// Serializes an x25519 PublicKey to and from hex +/// Serializes a x25519 PublicKey to and from hex pub mod dalek_xpubkey_serde { use crate::grin_util::{from_hex, ToHex}; use serde::{Deserialize, Deserializer, Serializer}; @@ -220,7 +227,7 @@ pub mod dalek_xpubkey_serde { /// Serializes an ed25519 PublicKey to and from base64 pub mod dalek_pubkey_base64 { use base64; - use ed25519_dalek::PublicKey as DalekPublicKey; + use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde::{Deserialize, Deserializer, Serializer}; /// @@ -242,7 +249,12 @@ pub mod dalek_pubkey_base64 { base64::decode(&string).map_err(|err| Error::custom(err.to_string())) }) .and_then(|bytes: Vec| { - DalekPublicKey::from_bytes(&bytes).map_err(|err| Error::custom(err.to_string())) + let b = <&[u8; 32]>::try_from(bytes.as_slice()) + .map_err(|_| Error::custom("Error deserializing public key"))?; + Ok(match DalekPublicKey::from_bytes(b) { + Ok(pk) => pk, + Err(e) => return Err(Error::custom(format!("{:?}", e))), + }) }) } } @@ -250,7 +262,7 @@ pub mod dalek_pubkey_base64 { /// Serializes an Option to and from hex pub mod option_dalek_pubkey_base64 { use base64; - use ed25519_dalek::PublicKey as DalekPublicKey; + use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; @@ -293,7 +305,7 @@ pub mod option_dalek_pubkey_base64 { /// Serializes an Option to and from hex pub mod option_dalek_pubkey_serde { - use ed25519_dalek::PublicKey as DalekPublicKey; + use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; @@ -398,11 +410,8 @@ pub mod dalek_sig_serde { String::deserialize(deserializer) .and_then(|string| from_hex(&string).map_err(|err| Error::custom(err.to_string()))) .and_then(|bytes: Vec| { - if bytes.len() != 64 { - return Err(Error::custom("unexpected byte length")); - } - let mut b = [0u8; 64]; - b.copy_from_slice(&bytes[0..64]); + let b = <[u8; 64]>::try_from(bytes.as_slice()) + .map_err(|_| Error::custom("invalid signature length"))?; DalekSignature::try_from(b).map_err(|err| Error::custom(err.to_string())) }) } @@ -437,11 +446,8 @@ pub mod option_dalek_sig_serde { Some(string) => from_hex(&string) .map_err(|err| Error::custom(err.to_string())) .and_then(|bytes: Vec| { - if bytes.len() != 64 { - return Err(Error::custom("unexpected byte length")); - } - let mut b = [0u8; 64]; - b.copy_from_slice(&bytes[0..64]); + let b = <[u8; 64]>::try_from(bytes.as_slice()) + .map_err(|_| Error::custom("invalid signature length"))?; DalekSignature::try_from(b) .map(Some) .map_err(|err| Error::custom(err.to_string())) @@ -479,11 +485,8 @@ pub mod option_dalek_sig_base64 { Some(string) => base64::decode(&string) .map_err(|err| Error::custom(err.to_string())) .and_then(|bytes: Vec| { - if bytes.len() != 64 { - return Err(Error::custom("unexpected byte length")); - } - let mut b = [0u8; 64]; - b.copy_from_slice(&bytes[0..64]); + let b = <[u8; 64]>::try_from(bytes.as_slice()) + .map_err(|_| Error::custom("invalid signature length"))?; DalekSignature::try_from(b) .map(Some) .map_err(|err| Error::custom(err.to_string())) @@ -708,11 +711,10 @@ mod test { use rand::rngs::mock::StepRng; use crate::grin_util::{secp, static_secp_instance}; - use ed25519_dalek::Keypair; - use ed25519_dalek::PublicKey as DalekPublicKey; - use ed25519_dalek::SecretKey as DalekSecretKey; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::Signer; + use ed25519_dalek::SigningKey as DalekSecretKey; + use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde::Deserialize; use serde_json; @@ -735,15 +737,10 @@ mod test { let secp = secp_inst.lock(); let mut test_rng = StepRng::new(1234567890u64, 1); let sec_key = secp::key::SecretKey::new(&secp, &mut test_rng); - let d_skey = DalekSecretKey::from_bytes(&sec_key.0).unwrap(); + let d_skey = DalekSecretKey::from_bytes(&sec_key.0); let d_pub_key: DalekPublicKey = (&d_skey).into(); - let keypair = Keypair { - public: d_pub_key, - secret: d_skey, - }; - - let d_sig = keypair.sign("test sig".as_bytes()); + let d_sig = d_skey.sign("test sig".as_bytes()); println!("D sig: {:?}", d_sig); SerTest { diff --git a/libwallet/src/slate_versions/v4.rs b/libwallet/src/slate_versions/v4.rs index 26c59e0..a3ba1b1 100644 --- a/libwallet/src/slate_versions/v4.rs +++ b/libwallet/src/slate_versions/v4.rs @@ -62,8 +62,8 @@ use crate::grin_util::secp::key::PublicKey; use crate::grin_util::secp::pedersen::{Commitment, RangeProof}; use crate::grin_util::secp::Signature; use crate::{slate_versions::ser, CbData}; -use ed25519_dalek::PublicKey as DalekPublicKey; use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use uuid::Uuid; #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/libwallet/src/slate_versions/v4_bin.rs b/libwallet/src/slate_versions/v4_bin.rs index e7a8fc0..dfb073c 100644 --- a/libwallet/src/slate_versions/v4_bin.rs +++ b/libwallet/src/slate_versions/v4_bin.rs @@ -21,8 +21,8 @@ use crate::grin_keychain::BlindingFactor; use crate::grin_util::secp::key::PublicKey; use crate::grin_util::secp::pedersen::{Commitment, RangeProof}; use crate::grin_util::secp::Signature; -use ed25519_dalek::PublicKey as DalekPublicKey; use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use std::convert::TryFrom; use uuid::Uuid; @@ -345,11 +345,24 @@ impl<'a> Writeable for ProofWrapRef<'a> { impl Readable for ProofWrap { fn read(reader: &mut R) -> Result { - let saddr = DalekPublicKey::from_bytes(&reader.read_fixed_bytes(32)?).unwrap(); - let raddr = DalekPublicKey::from_bytes(&reader.read_fixed_bytes(32)?).unwrap(); + let saddr_bytes = reader.read_fixed_bytes(32)?; + let saddr_bytes = <&[u8; 32]>::try_from(saddr_bytes.as_slice()) + .map_err(|_| grin_ser::Error::CorruptedData)?; + let saddr = + DalekPublicKey::from_bytes(saddr_bytes).map_err(|_| grin_ser::Error::CorruptedData)?; + + let raddr_bytes = reader.read_fixed_bytes(32)?; + let raddr_bytes = <&[u8; 32]>::try_from(raddr_bytes.as_slice()) + .map_err(|_| grin_ser::Error::CorruptedData)?; + let raddr = + DalekPublicKey::from_bytes(raddr_bytes).map_err(|_| grin_ser::Error::CorruptedData)?; + let rsig = match reader.read_u8()? { 0 => None, - 1 | _ => Some(DalekSignature::try_from(&reader.read_fixed_bytes(64)?[..]).unwrap()), + 1 | _ => Some( + DalekSignature::try_from(&reader.read_fixed_bytes(64)?[..]) + .map_err(|_| grin_ser::Error::CorruptedData)?, + ), }; Ok(ProofWrap(PaymentInfoV4 { saddr, raddr, rsig })) } @@ -495,6 +508,7 @@ fn slate_v4_serialize_deserialize() { use crate::Slate; use grin_core::global::{set_local_chain_type, ChainTypes}; use grin_keychain::{ExtKeychain, Keychain, SwitchCommitmentType}; + set_local_chain_type(ChainTypes::Mainnet); let slate = Slate::blank(1, false); let mut v4 = SlateV4::from(slate); @@ -568,8 +582,9 @@ fn slate_v4_serialize_deserialize() { // Include Payment proof, remove coms to mix it up a bit let mut v4 = v4_1_copy; let raw_pubkey_str = "d03c09e9c19bb74aa9ea44e0fe5ae237a9bf40bddf0941064a80913a4459c8bb"; - let b = from_hex(raw_pubkey_str).unwrap(); - let d_pkey = DalekPublicKey::from_bytes(&b).unwrap(); + let bytes = from_hex(raw_pubkey_str).unwrap(); + let b = <&[u8; 32]>::try_from(bytes.as_slice()).unwrap(); + let d_pkey = DalekPublicKey::from_bytes(b.as_array().unwrap()).unwrap(); v4.proof = Some(PaymentInfoV4 { raddr: d_pkey.clone(), saddr: d_pkey.clone(), diff --git a/libwallet/src/slate_versions/v5.rs b/libwallet/src/slate_versions/v5.rs index 5bb4039..33338f0 100644 --- a/libwallet/src/slate_versions/v5.rs +++ b/libwallet/src/slate_versions/v5.rs @@ -41,8 +41,8 @@ use crate::grin_util::secp::pedersen::{Commitment, RangeProof}; use crate::grin_util::secp::Signature; use crate::{slate_versions::ser, CbData}; use chrono::prelude::{DateTime, Utc}; -use ed25519_dalek::PublicKey as DalekPublicKey; use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde_with::TimestampSeconds; use uuid::Uuid; diff --git a/libwallet/src/slate_versions/v5_bin.rs b/libwallet/src/slate_versions/v5_bin.rs index 600cd18..f1af734 100644 --- a/libwallet/src/slate_versions/v5_bin.rs +++ b/libwallet/src/slate_versions/v5_bin.rs @@ -22,8 +22,8 @@ use crate::grin_util::secp::key::PublicKey; use crate::grin_util::secp::pedersen::{Commitment, RangeProof}; use crate::grin_util::secp::Signature; use chrono::{DateTime, NaiveDateTime, Utc}; -use ed25519_dalek::PublicKey as DalekPublicKey; use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use std::convert::{TryFrom, TryInto}; use std::f64::consts::E; @@ -245,10 +245,17 @@ impl<'a> Writeable for ProofWrapRef<'a> { impl Readable for ProofWrap { fn read(reader: &mut R) -> Result { - let saddr = DalekPublicKey::from_bytes(&reader.read_fixed_bytes(32)?) + let saddr_bytes = reader.read_fixed_bytes(32)?; + let saddr_bytes = <&[u8; 32]>::try_from(saddr_bytes.as_slice()) .map_err(|_| grin_ser::Error::CorruptedData)?; - let raddr = DalekPublicKey::from_bytes(&reader.read_fixed_bytes(32)?) + let saddr = + DalekPublicKey::from_bytes(saddr_bytes).map_err(|_| grin_ser::Error::CorruptedData)?; + + let raddr_bytes = reader.read_fixed_bytes(32)?; + let raddr_bytes = <&[u8; 32]>::try_from(raddr_bytes.as_slice()) .map_err(|_| grin_ser::Error::CorruptedData)?; + let raddr = + DalekPublicKey::from_bytes(raddr_bytes).map_err(|_| grin_ser::Error::CorruptedData)?; let ts_raw: i64 = match reader.read_i64() { Ok(v) => v, Err(_) => return Err(grin_ser::Error::CorruptedData), @@ -497,7 +504,8 @@ fn slate_v5_serialize_deserialize() { let mut v5 = v4_1_copy; let raw_pubkey_str = "d03c09e9c19bb74aa9ea44e0fe5ae237a9bf40bddf0941064a80913a4459c8bb"; let b = from_hex(raw_pubkey_str).unwrap(); - let d_pkey = DalekPublicKey::from_bytes(&b).unwrap(); + let b = <&[u8; 32]>::try_from(b.as_slice()).unwrap(); + let d_pkey = DalekPublicKey::from_bytes(b).unwrap(); // Need to remove milliseconds component for comparison. Won't be serialized let ts = NaiveDateTime::from_timestamp_opt(Utc::now().timestamp(), 0).unwrap(); let ts = DateTime::::from_utc(ts, Utc); diff --git a/libwallet/src/slatepack/address.rs b/libwallet/src/slatepack/address.rs index 15c08b8..1e88541 100644 --- a/libwallet/src/slatepack/address.rs +++ b/libwallet/src/slatepack/address.rs @@ -13,9 +13,9 @@ // limitations under the License. use bech32::{self, FromBase32, ToBase32}; +use ed25519_dalek::SigningKey as edDalekSecretKey; /// Slatepack Address definition -use ed25519_dalek::PublicKey as edDalekPublicKey; -use ed25519_dalek::SecretKey as edDalekSecretKey; +use ed25519_dalek::VerifyingKey as edDalekPublicKey; use rand::{thread_rng, Rng}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use x25519_dalek::PublicKey as xDalekPublicKey; @@ -57,7 +57,7 @@ impl SlatepackAddress { /// new with a random key pub fn random() -> Self { let bytes: [u8; 32] = thread_rng().gen(); - let pub_key = edDalekPublicKey::from(&edDalekSecretKey::from_bytes(&bytes).unwrap()); + let pub_key = edDalekPublicKey::from(&edDalekSecretKey::from_bytes(&bytes)); SlatepackAddress::new(&pub_key) } @@ -88,7 +88,9 @@ impl TryFrom<&str> for SlatepackAddress { fn try_from(encoded: &str) -> Result { let (hrp, data) = bech32::decode(&encoded)?; let bytes = Vec::::from_base32(&data)?; - let pub_key = match edDalekPublicKey::from_bytes(&bytes) { + let b = <&[u8; 32]>::try_from(bytes.as_slice()) + .map_err(|_| Error::SlatepackAddress("Wrong encoded data".to_string()))?; + let pub_key = match edDalekPublicKey::from_bytes(&b) { Ok(k) => k, Err(e) => { return Err(Error::ED25519Key(format!("{}", e))); @@ -124,7 +126,10 @@ impl TryFrom<&SlatepackAddress> for xDalekPublicKey { fn try_from(addr: &SlatepackAddress) -> Result { let cep = curve25519_dalek::edwards::CompressedEdwardsY::from_slice(addr.pub_key.as_bytes()); - let ep = match cep.decompress() { + let ep = match cep + .map_err(|e| Error::ED25519Key(format!("{}", e)))? + .decompress() + { Some(p) => p, None => { return Err(Error::ED25519Key( @@ -140,15 +145,7 @@ impl TryFrom<&SlatepackAddress> for xDalekPublicKey { impl TryFrom<&SecretKey> for SlatepackAddress { type Error = Error; fn try_from(key: &SecretKey) -> Result { - let d_skey = match edDalekSecretKey::from_bytes(&key.0) { - Ok(k) => k, - Err(e) => { - return Err(Error::ED25519Key(format!( - "Can't create slatepack address from SecretKey: {}", - e - ))); - } - }; + let d_skey = edDalekSecretKey::from_bytes(&key.0); let d_pub_key: edDalekPublicKey = (&d_skey).into(); Ok(Self::new(&d_pub_key)) } @@ -251,7 +248,7 @@ fn slatepack_address() -> Result<(), Error> { global::set_local_chain_type(global::ChainTypes::AutomatedTesting); let sec_key_bytes: [u8; 32] = thread_rng().gen(); - let ed_sec_key = edDalekSecretKey::from_bytes(&sec_key_bytes).unwrap(); + let ed_sec_key = edDalekSecretKey::from_bytes(&sec_key_bytes); let ed_pub_key = edDalekPublicKey::from(&ed_sec_key); let addr = SlatepackAddress::new(&ed_pub_key); let x_pub_key = xDalekPublicKey::try_from(&addr)?; diff --git a/libwallet/src/slatepack/armor.rs b/libwallet/src/slatepack/armor.rs index eacdf32..c8be299 100644 --- a/libwallet/src/slatepack/armor.rs +++ b/libwallet/src/slatepack/armor.rs @@ -74,7 +74,10 @@ impl SlatepackArmor { // Get the length of the header let header_len = header_bytes.len() + 1; // Skip the length of the header to read for the payload until the next period - let payload_bytes = armor_bytes[header_len as usize..] + let payload_source = armor_bytes + .get(header_len..) + .ok_or_else(|| Error::InvalidSlatepackData("Bad armor header".to_string()))?; + let payload_bytes = payload_source .iter() .take_while(|byte| **byte != b'.') .cloned() @@ -82,8 +85,14 @@ impl SlatepackArmor { // Get length of the payload to check the footer framing let payload_len = payload_bytes.len(); // Get footer bytes and verify them - let consumed_bytes = header_len + payload_len + 1; - let footer_bytes = armor_bytes[consumed_bytes as usize..] + let consumed_bytes = header_len + .checked_add(payload_len) + .and_then(|v| v.checked_add(1)) + .ok_or_else(|| Error::InvalidSlatepackData("Bad armor footer".to_string()))?; + let footer_source = armor_bytes + .get(consumed_bytes..) + .ok_or_else(|| Error::InvalidSlatepackData("Bad armor footer".to_string()))?; + let footer_bytes = footer_source .iter() .take_while(|byte| **byte != b'.') .cloned() @@ -99,8 +108,10 @@ impl SlatepackArmor { let base_decode = bs58::decode(&clean_payload) .into_vec() .map_err(|_| Error::SlatepackDeser("Bad bytes".into()))?; - let error_code = &base_decode[0..4]; - let slatepack_bytes = &base_decode[4..]; + if base_decode.len() < 4 { + return Err(Error::SlatepackDeser("Payload too short".into())); + } + let (error_code, slatepack_bytes) = base_decode.split_at(4); // Make sure the error check code is valid for the slate data error_check(error_code, slatepack_bytes)?; // Return slate as binary or string diff --git a/libwallet/src/slatepack/packer.rs b/libwallet/src/slatepack/packer.rs index 32c3e41..a19de72 100644 --- a/libwallet/src/slatepack/packer.rs +++ b/libwallet/src/slatepack/packer.rs @@ -24,7 +24,7 @@ use crate::{ use grin_wallet_util::byte_ser; -use ed25519_dalek::SecretKey as edSecretKey; +use ed25519_dalek::SigningKey as edSecretKey; #[derive(Clone)] /// Arguments, mostly for encrypting decrypting a slatepack diff --git a/libwallet/src/slatepack/types.rs b/libwallet/src/slatepack/types.rs index fe08c93..72867a9 100644 --- a/libwallet/src/slatepack/types.rs +++ b/libwallet/src/slatepack/types.rs @@ -15,7 +15,7 @@ use bech32::{self, ToBase32}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; /// Slatepack Types + Serialization implementation -use ed25519_dalek::SecretKey as edSecretKey; +use ed25519_dalek::SigningKey as edSecretKey; use sha2::{Digest, Sha512}; use x25519_dalek::StaticSecret; @@ -208,10 +208,23 @@ impl Slatepack { reader.read_to_end(&mut decrypted)?; // Parse encrypted metadata from payload, first 4 bytes of decrypted payload // will be encrypted metadata length + if decrypted.len() < 4 { + return Err(Error::SlatepackDeser( + "Encrypted payload missing metadata length".into(), + )); + } let mut len_bytes = [0u8; 4]; len_bytes.copy_from_slice(&decrypted[0..4]); let meta_len = Cursor::new(len_bytes).read_u32::()?; - self.payload = decrypted.split_off(meta_len as usize + 4); + let payload_start = (meta_len as usize) + .checked_add(4) + .ok_or_else(|| Error::SlatepackDeser("Encrypted metadata length overflow".into()))?; + if payload_start > decrypted.len() { + return Err(Error::SlatepackDeser( + "Encrypted metadata length exceeds payload".into(), + )); + } + self.payload = decrypted.split_off(payload_start); let meta = byte_ser::from_bytes::(&decrypted) .map_err(|_| Error::SlatepackSer)? .0; @@ -755,15 +768,15 @@ fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { fn slatepack_encrypted_meta() -> Result<(), Error> { use crate::grin_core::global; use crate::{Slate, SlateVersion, VersionedBinSlate, VersionedSlate}; - use ed25519_dalek::PublicKey as edDalekPublicKey; - use ed25519_dalek::SecretKey as edDalekSecretKey; + use ed25519_dalek::SigningKey as edDalekSecretKey; + use ed25519_dalek::VerifyingKey as edDalekPublicKey; use rand::{thread_rng, Rng}; use std::convert::TryFrom; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); let sec_key_bytes: [u8; 32] = thread_rng().gen(); - let ed_sec_key = edDalekSecretKey::from_bytes(&sec_key_bytes).unwrap(); + let ed_sec_key = edDalekSecretKey::from_bytes(&sec_key_bytes); let ed_pub_key = edDalekPublicKey::from(&ed_sec_key); let addr = SlatepackAddress::new(&ed_pub_key); @@ -804,15 +817,15 @@ fn slatepack_encrypted_meta() -> Result<(), Error> { fn slatepack_encrypted_meta_future() -> Result<(), Error> { use crate::grin_core::global; use crate::{Slate, SlateVersion, VersionedBinSlate, VersionedSlate}; - use ed25519_dalek::PublicKey as edDalekPublicKey; - use ed25519_dalek::SecretKey as edDalekSecretKey; + use ed25519_dalek::SigningKey as edDalekSecretKey; + use ed25519_dalek::VerifyingKey as edDalekPublicKey; use rand::{thread_rng, Rng}; use std::convert::TryFrom; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); let sec_key_bytes: [u8; 32] = thread_rng().gen(); - let ed_sec_key = edDalekSecretKey::from_bytes(&sec_key_bytes).unwrap(); + let ed_sec_key = edDalekSecretKey::from_bytes(&sec_key_bytes); let ed_pub_key = edDalekPublicKey::from(&ed_sec_key); let addr = SlatepackAddress::new(&ed_pub_key); @@ -848,3 +861,53 @@ fn slatepack_encrypted_meta_future() -> Result<(), Error> { Ok(()) } + +#[cfg(test)] +fn slatepack_test_decryption_key() -> (edSecretKey, SlatepackAddress) { + use ed25519_dalek::VerifyingKey as edDalekPublicKey; + use rand::{thread_rng, Rng}; + + let sec_key_bytes: [u8; 32] = thread_rng().gen(); + let ed_sec_key = edSecretKey::from_bytes(&sec_key_bytes); + let ed_pub_key = edDalekPublicKey::from(&ed_sec_key); + let addr = SlatepackAddress::new(&ed_pub_key); + + (ed_sec_key, addr) +} + +#[cfg(test)] +fn encrypt_plaintext_to_slatepack_recipient( + recipient: &SlatepackAddress, + plaintext: &[u8], +) -> Result, Error> { + let recp_key: age::x25519::Recipient = recipient.to_age_pubkey_str()?.parse()?; + let keys = vec![Box::new(recp_key) as Box]; + let encryptor = age::Encryptor::with_recipients(keys); + let mut encrypted = vec![]; + let mut writer = encryptor.wrap_output(&mut encrypted)?; + writer.write_all(plaintext)?; + writer.finish()?; + Ok(encrypted) +} + +#[test] +fn slatepack_decrypt_rejects_malformed_plaintexts() -> Result<(), Error> { + use crate::grin_core::global; + + global::set_local_chain_type(global::ChainTypes::AutomatedTesting); + let (ed_sec_key, addr) = slatepack_test_decryption_key(); + + for plaintext in vec![vec![], vec![0], vec![0, 0, 0], vec![0xff; 4]] { + let mut slatepack = Slatepack { + mode: 1, + payload: encrypt_plaintext_to_slatepack_recipient(&addr, &plaintext)?, + ..Slatepack::default() + }; + assert!(matches!( + slatepack.try_decrypt_payload(Some(&ed_sec_key)), + Err(Error::SlatepackDeser(_)) + )); + } + + Ok(()) +} diff --git a/libwallet/src/types.rs b/libwallet/src/types.rs index 876e044..d3a6b46 100644 --- a/libwallet/src/types.rs +++ b/libwallet/src/types.rs @@ -16,6 +16,7 @@ //! implementation use crate::config::{TorConfig, WalletConfig}; +use crate::contract::types::ContractSetupArgsAPI; use crate::error::Error; use crate::grin_core::core::hash::Hash; use crate::grin_core::core::FeeFields; @@ -27,13 +28,12 @@ use crate::grin_util::logger::LoggingConfig; use crate::grin_util::secp::key::{PublicKey, SecretKey}; use crate::grin_util::secp::{self, pedersen, Secp256k1, Signature}; use crate::grin_util::{ToHex, ZeroingString}; -use crate::contract::types::ContractSetupArgsAPI; use crate::slate::PaymentMemo; use crate::slate_versions::ser as dalek_ser; use crate::{InitTxArgs, SlateState, WalletBackend}; use chrono::prelude::*; -use ed25519_dalek::PublicKey as DalekPublicKey; use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use rand::rngs::mock::StepRng; use rand::thread_rng; use serde; diff --git a/src/bin/grin-wallet.rs b/src/bin/grin-wallet.rs index 9189f02..6e90995 100644 --- a/src/bin/grin-wallet.rs +++ b/src/bin/grin-wallet.rs @@ -31,7 +31,7 @@ use std::env; use std::path::PathBuf; use std::path::MAIN_SEPARATOR; -// include build information +/// Include build information pub mod built_info { include!(concat!(env!("OUT_DIR"), "/built.rs")); } @@ -55,7 +55,7 @@ pub fn info_strings() -> (String, String) { ) } -// Helper fuction to format paths according to OS, avoids bugs on Linux +/// Helper function to format paths according to OS, avoids bugs on Linux pub fn fmt_path(path: String) -> String { let sep = &MAIN_SEPARATOR.to_string(); let path = path.replace("/", &sep).replace("\\", &sep); @@ -117,24 +117,24 @@ fn real_main() -> i32 { // Load relevant config, try and load a wallet config file // Use defaults for configuration if config file not found anywhere - let mut config = match config::initial_setup_wallet(&chain_type, current_dir, create_path) { + let config = match config::initial_setup_wallet(&chain_type, current_dir, create_path) { Ok(c) => c, - Err(e) => match e { - ConfigError::PathNotFoundError(m) => { - println!("Wallet configuration not found at {}. (Run `grin-wallet init` to create a new wallet)", m); - return 0; + Err(e) => { + return match e { + ConfigError::PathNotFoundError(m) => { + println!("Wallet configuration not found at {}. (Run `grin-wallet init` to create a new wallet)", m); + 0 + } + m => { + println!("Unable to load wallet configuration: {} (Run `grin-wallet init` to create a new wallet)", m); + 0 + } } - m => { - println!("Unable to load wallet configuration: {} (Run `grin-wallet init` to create a new wallet)", m); - return 0; - } - }, + } }; - //config.members.as_mut().unwrap().wallet.chain_type = Some(chain_type); - // Load logging config - let mut l = config.members.as_mut().unwrap().logging.clone().unwrap(); + let mut l = config.members.logging.clone().unwrap(); // no logging to stdout if we're running cli match args.subcommand() { ("cli", _) => l.log_to_stdout = true, @@ -143,24 +143,16 @@ fn real_main() -> i32 { init_logger(Some(l), None); info!( "Using wallet configuration file at {}", - config.config_file_path.as_ref().unwrap().to_str().unwrap() + config.config_file_path.to_str().unwrap() ); log_build_info(); - global::init_global_chain_type( - config - .members - .as_ref() - .unwrap() - .wallet - .chain_type - .as_ref() - .unwrap() - .clone(), - ); + global::init_global_chain_type(config.members.wallet.chain_type.as_ref().unwrap().clone()); - global::init_global_accept_fee_base(config.members.as_ref().unwrap().wallet.accept_fee_base()); - let wallet_config = config.clone().members.unwrap().wallet; - let node_client = HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None).unwrap(); + global::init_global_accept_fee_base(config.members.wallet.accept_fee_base()); + let wallet_config = config.clone().members.wallet; + let timeout = wallet_config.api_request_timeout(); + let node_client = + HTTPNodeClient::new(&wallet_config.check_node_api_http_addr, None, timeout).unwrap(); cmd::wallet_command(&args, config, node_client) } diff --git a/src/cli/cli.rs b/src/cli/cli.rs index cf01dd7..d410785 100644 --- a/src/cli/cli.rs +++ b/src/cli/cli.rs @@ -19,7 +19,8 @@ use clap::App; //use colored::Colorize; use grin_keychain as keychain; use grin_wallet_api::Owner; -use grin_wallet_config::{TorConfig, WalletConfig}; +use grin_wallet_config::config::get_global_config; +use grin_wallet_config::GlobalWalletConfig; use grin_wallet_controller::command::GlobalArgs; use grin_wallet_controller::Error; use grin_wallet_impls::DefaultWalletImpl; @@ -107,10 +108,9 @@ pub fn start_updater_thread(rx: Receiver) -> Result<(), Error> { } pub fn command_loop( + config: GlobalWalletConfig, wallet_inst: Arc>>>, keychain_mask: Option, - wallet_config: &WalletConfig, - tor_config: &TorConfig, global_wallet_args: &GlobalArgs, test_mode: bool, ) -> Result<(), Error> @@ -151,7 +151,7 @@ where // catch updater messages let (tx, rx) = channel(); - let mut owner_api = Owner::new(wallet_inst, Some(tx)); + let mut owner_api = Owner::new(wallet_inst, Some(tx), config.config_file_path.clone()); start_updater_thread(rx)?; // start the automatic updater @@ -189,7 +189,7 @@ where let lc = wallet_lock.lc_provider().unwrap(); let mask = match lc.open_wallet( None, - wallet_args::prompt_password(&global_wallet_args.password), + wallet_args::prompt_password(&global_wallet_args.password)?, false, false, ) { @@ -218,11 +218,15 @@ where } _ => keychain_mask, }; + let config = get_global_config(&config.config_file_path) + .map_err(|e| Error::GenericError(e.to_string()))?; + let tor_config = config.tor_config(); + let wallet_config = config.members.wallet; match wallet_args::parse_and_execute( &mut owner_api, keychain_mask.clone(), &wallet_config, - &tor_config, + tor_config, &global_wallet_args, &args, test_mode, @@ -276,6 +280,8 @@ impl Completer for EditorHelper { } impl Hinter for EditorHelper { + type Hint = String; + fn hint(&self, line: &str, _pos: usize, _ctx: &Context<'_>) -> Option { let mut contents = STDIN_CONTENTS.lock(); *contents = line.into(); diff --git a/src/cmd/wallet.rs b/src/cmd/wallet.rs index 2a76b98..e538ef6 100644 --- a/src/cmd/wallet.rs +++ b/src/cmd/wallet.rs @@ -30,37 +30,35 @@ pub fn wallet_command( where C: NodeClient + 'static, { - // just get defaults from the global config - let wallet_config = config.members.clone().unwrap().wallet; - - let tor_config = config.members.unwrap().tor; - // Check the node version info, and exit with report if we're not compatible - let global_wallet_args = wallet_args::parse_global_args(&wallet_config, &wallet_args) + let global_wallet_args = wallet_args::parse_global_args(&config.members.wallet, &wallet_args) .expect("Can't read configuration file"); node_client.set_node_api_secret(global_wallet_args.node_api_secret.clone()); // This will also cache the node version info for calls to foreign API check middleware if let Some(v) = node_client.clone().get_version_info() { - if Version::parse(&v.node_version) < Version::parse(MIN_COMPAT_NODE_VERSION) { - println!("The Grin Node in use (version {}) is outdated and incompatible with this wallet version.", v.node_version); + let node_version = Version::parse(&v.node_version); + let min_version = Version::parse(MIN_COMPAT_NODE_VERSION).ok(); + if let Ok(v) = node_version { + if Some(v.clone()) < min_version { + println!("The Grin Node in use (version {}) is outdated and incompatible with this wallet version.", v); + println!( + "Please update the node to version {} or later and try again.", + MIN_COMPAT_NODE_VERSION + ); + return 1; + } + } else { println!( - "Please update the node to version {} or later and try again.", - MIN_COMPAT_NODE_VERSION + "Can not parse node version {}. Minimal compatible node version: {}", + v.node_version, MIN_COMPAT_NODE_VERSION ); return 1; } } // ... if node isn't available, allow offline functions - let res = wallet_args::wallet_command( - wallet_args, - wallet_config, - tor_config, - node_client, - false, - |_| {}, - ); + let res = wallet_args::wallet_command(wallet_args, config, node_client, false, |_| {}); // we need to give log output a chance to catch up before exiting thread::sleep(Duration::from_millis(100)); diff --git a/src/cmd/wallet_args.rs b/src/cmd/wallet_args.rs index 3634c40..1f3b196 100644 --- a/src/cmd/wallet_args.rs +++ b/src/cmd/wallet_args.rs @@ -24,7 +24,7 @@ use grin_core as core; use grin_core::core::amount_to_hr_string; use grin_keychain as keychain; use grin_wallet_api::Owner; -use grin_wallet_config::{TorConfig, WalletConfig}; +use grin_wallet_config::{GlobalWalletConfig, TorConfig, WalletConfig}; use grin_wallet_controller::{command, Error}; use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl}; use grin_wallet_libwallet::{self, Slate, SlatepackAddress, SlatepackArmor}; @@ -33,6 +33,7 @@ use linefeed::terminal::Signal; use linefeed::{Interface, ReadResult}; use rpassword; use std::convert::TryFrom; +use std::io::{IsTerminal, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -67,25 +68,39 @@ impl From for ParseError { } } -fn prompt_password_stdout(prompt: &str) -> ZeroingString { - ZeroingString::from(rpassword::prompt_password_stdout(prompt).unwrap()) +fn prompt_password_internal(prompt: &str) -> Result { + print!("{}", prompt); + std::io::stdout().flush().unwrap(); + let stdin = std::io::stdin(); + let password = if stdin.is_terminal() { + rpassword::read_password() + } else { + rpassword::read_password_with_config( + rpassword::ConfigBuilder::new() + .input_reader(stdin) + .output_discard() + .build(), + ) + } + .map_err(|e| Error::GenericError(format!("{}", e)))?; + Ok(ZeroingString::from(password)) } -pub fn prompt_password(password: &Option) -> ZeroingString { +pub fn prompt_password(password: &Option) -> Result { match password { - None => prompt_password_stdout("Password: "), - Some(p) => p.clone(), + None => Ok(prompt_password_internal("Password: ")?), + Some(p) => Ok(p.clone()), } } -fn prompt_password_confirm() -> ZeroingString { +fn prompt_password_confirm() -> Result { let mut first = ZeroingString::from("first"); let mut second = ZeroingString::from("second"); while first != second { - first = prompt_password_stdout("Password: "); - second = prompt_password_stdout("Confirm Password: "); + first = prompt_password_internal("Password: ")?; + second = prompt_password_internal("Confirm Password: ")?; } - first + Ok(first) } fn prompt_recovery_phrase( @@ -320,7 +335,7 @@ pub fn parse_global_args( let key = match config.tls_certificate_key.clone() { Some(k) => k, None => { - let msg = format!("Private key for certificate is not set"); + let msg = "Private key for certificate is not set".to_string(); return Err(ParseError::ArgumentError(msg)); } }; @@ -330,11 +345,11 @@ pub fn parse_global_args( Ok(command::GlobalArgs { account: account.to_owned(), - show_spent: show_spent, - api_secret: api_secret, - node_api_secret: node_api_secret, - password: password, - tls_conf: tls_conf, + show_spent, + api_secret, + node_api_secret, + password, + tls_conf, }) } @@ -344,7 +359,7 @@ pub fn parse_init_args( g_args: &command::GlobalArgs, args: &ArgMatches, _test_mode: bool, -) -> Result +) -> Result where DefaultWalletImpl: WalletInst<'static, L, C, K>, L: WalletLCProvider<'static, C, K>, @@ -356,7 +371,9 @@ where true => 16, }; let recovery_phrase = match args.is_present("recover") { - true => Some(prompt_recovery_phrase(wallet)?), + true => { + Some(prompt_recovery_phrase(wallet).map_err(|e| Error::GenericError(e.to_string()))?) + } false => None, }; @@ -366,10 +383,11 @@ where println!("Please enter a password for your new wallet"); } - let password = g_args - .password - .clone() - .unwrap_or_else(|| prompt_password_confirm()); + let password = if let Some(p) = g_args.password.clone() { + p + } else { + prompt_password_confirm()? + }; Ok(command::InitArgs { list_length, @@ -380,32 +398,13 @@ where }) } -pub fn parse_recover_args( - g_args: &command::GlobalArgs, -) -> Result +pub fn parse_recover_args(g_args: &command::GlobalArgs) -> Result where { - let passphrase = prompt_password(&g_args.password); + let passphrase = prompt_password(&g_args.password)?; Ok(command::RecoverArgs { passphrase }) } -pub fn parse_listen_args( - config: &mut WalletConfig, - tor_config: &mut TorConfig, - args: &ArgMatches, -) -> Result { - if let Some(port) = args.value_of("port") { - config.api_listen_port = port.parse().unwrap(); - } - if let Some(bridge) = args.value_of("bridge") { - tor_config.bridge.bridge_line = Some(bridge.into()); - } - if args.is_present("no_tor") { - tor_config.use_tor_listener = false; - } - Ok(command::ListenArgs {}) -} - pub fn parse_owner_api_args( config: &mut WalletConfig, args: &ArgMatches, @@ -426,7 +425,7 @@ pub fn parse_scan_rewind_hash_args( let start_height = parse_u64_or_none(args.value_of("start_height")); let backwards_from_tip = parse_u64_or_none(args.value_of("backwards_from_tip")); if backwards_from_tip.is_some() && start_height.is_some() { - let msg = format!("backwards_from tip and start_height cannot both be present"); + let msg = "backwards_from tip and start_height cannot both be present".to_string(); return Err(ParseError::ArgumentError(msg)); } Ok(command::ViewWalletScanArgs { @@ -441,7 +440,7 @@ pub fn parse_account_args(account_args: &ArgMatches) -> Result None, Some(s) => Some(s.to_owned()), }; - Ok(command::AccountArgs { create: create }) + Ok(command::AccountArgs { create }) } pub fn parse_send_args(args: &ArgMatches) -> Result { @@ -477,10 +476,7 @@ pub fn parse_send_args(args: &ArgMatches) -> Result d, - None => "default", - }; + let dest = args.value_of("dest").unwrap_or_else(|| "default"); // change_outputs let change_outputs = parse_required(args, "change_outputs")?; @@ -523,6 +519,12 @@ pub fn parse_send_args(args: &ArgMatches) -> Result Some(b.to_string()), None => None, @@ -531,24 +533,24 @@ pub fn parse_send_args(args: &ArgMatches) -> Result Result Result Result Result Result d, - None => "default", - }; + let dest = args.value_of("dest").unwrap_or_else(|| "default"); let outfile = parse_optional(args, "outfile")?; @@ -705,7 +716,7 @@ pub fn parse_issue_invoice_args( target_slate_version, }, outfile, - slatepack_qr: slatepack_qr, + slatepack_qr, }) } @@ -781,6 +792,12 @@ pub fn parse_process_invoice_args( let outfile = parse_optional(args, "outfile")?; + let skip_tor = if args.is_present("manual") { + Some(true) + } else { + None + }; + let bridge = parse_optional(args, "bridge")?; let slatepack_qr = args.is_present("slatepack_qr"); @@ -793,10 +810,10 @@ pub fn parse_process_invoice_args( slate, max_outputs, ttl_blocks, - skip_tor: args.is_present("manual"), + skip_tor, outfile, bridge, - slatepack_qr: slatepack_qr, + slatepack_qr, }) } @@ -814,7 +831,7 @@ pub fn parse_check_args(args: &ArgMatches) -> Result Result }, }; if tx_id.is_some() && tx_slate_id.is_some() { - let msg = format!("At most one of 'id' (-i) or 'txid' (-t) may be provided."); + let msg = "At most one of 'id' (-i) or 'txid' (-t) may be provided.".to_string(); return Err(ParseError::ArgumentError(msg)); } let count = match args.value_of("count") { @@ -849,8 +866,8 @@ pub fn parse_txs_args(args: &ArgMatches) -> Result }; Ok(command::TxsArgs { id: tx_id, - tx_slate_id: tx_slate_id, - count: count, + tx_slate_id, + count, }) } @@ -897,8 +914,8 @@ pub fn parse_repost_args(args: &ArgMatches) -> Result Result Result( wallet_args: &ArgMatches, - mut wallet_config: WalletConfig, - tor_config: Option, + config: GlobalWalletConfig, mut node_client: C, test_mode: bool, wallet_inst_cb: F, @@ -1159,6 +1175,7 @@ where >, ), { + let mut wallet_config = config.members.wallet.clone(); if let Some(dir) = wallet_args.value_of("top_level_dir") { wallet_config.data_file_dir = dir.to_string().clone(); } @@ -1181,13 +1198,6 @@ where wallet_config.data_file_dir = top_level_wallet_dir.to_str().unwrap().into(); } - // for backwards compatibility: If tor config doesn't exist in the file, assume - // the top level directory for data - let tor_config = tor_config.unwrap_or_else(|| TorConfig { - send_config_dir: wallet_config.data_file_dir.clone(), - ..Default::default() - }); - // Instantiate wallet (doesn't open the wallet) let wallet = inst_wallet::, C, keychain::ExtKeychain>( @@ -1201,12 +1211,12 @@ where { let mut wallet_lock = wallet.lock(); - let lc = wallet_lock.lc_provider().unwrap(); + let lc = wallet_lock.lc_provider()?; let _ = lc.set_top_level_directory(&wallet_config.data_file_dir); } // provide wallet instance back to the caller (handy for testing with - // local wallet proxy, etc) + // local wallet proxy, etc.) wallet_inst_cb(wallet.clone()); // don't open wallet for certain lifecycle commands @@ -1218,7 +1228,7 @@ where ("owner_api", _) => { // If wallet exists and password is present then open it. Otherwise, that's fine too. let mut wallet_lock = wallet.lock(); - let lc = wallet_lock.lc_provider().unwrap(); + let lc = wallet_lock.lc_provider()?; open_wallet = wallet_args.is_present("pass") && lc.wallet_exists(None)?; } _ => {} @@ -1227,10 +1237,10 @@ where let keychain_mask = match open_wallet { true => { let mut wallet_lock = wallet.lock(); - let lc = wallet_lock.lc_provider().unwrap(); + let lc = wallet_lock.lc_provider()?; let mask = lc.open_wallet( None, - prompt_password(&global_wallet_args.password), + prompt_password(&global_wallet_args.password)?, false, false, )?; @@ -1245,20 +1255,20 @@ where let res = match wallet_args.subcommand() { ("cli", Some(_)) => command_loop( + config, wallet, keychain_mask, - &wallet_config, - &tor_config, &global_wallet_args, test_mode, ), _ => { - let mut owner_api = Owner::new(wallet, None); + let tor_config = config.tor_config(); + let mut owner_api = Owner::new(wallet, None, config.config_file_path); parse_and_execute( &mut owner_api, keychain_mask, &wallet_config, - &tor_config, + tor_config, &global_wallet_args, &wallet_args, test_mode, @@ -1278,7 +1288,7 @@ pub fn parse_and_execute( owner_api: &mut Owner, keychain_mask: Option, wallet_config: &WalletConfig, - tor_config: &TorConfig, + tor_config: TorConfig, global_wallet_args: &command::GlobalArgs, wallet_args: &ArgMatches, test_mode: bool, @@ -1314,14 +1324,25 @@ where } ("listen", Some(args)) => { let mut c = wallet_config.clone(); - let mut t = tor_config.clone(); - let a = arg_parse!(parse_listen_args(&mut c, &mut t, &args)); + if let Some(port) = args.value_of("port") { + c.api_listen_port = port.parse().unwrap(); + } + let bridge = if let Some(bridge) = args.value_of("bridge") { + Some(bridge.into()) + } else { + None + }; + let use_tor = if args.is_present("no_tor") { + Some(false) + } else { + None + }; command::listen( owner_api, Arc::new(Mutex::new(keychain_mask)), - &c, - &t, - &a, + c, + bridge, + use_tor, &global_wallet_args.clone(), cli_mode, test_mode, @@ -1332,13 +1353,12 @@ where let mut g = global_wallet_args.clone(); g.tls_conf = None; arg_parse!(parse_owner_api_args(&mut c, &args)); - command::owner_api(owner_api, keychain_mask, &c, &tor_config, &g, test_mode) + command::owner_api(owner_api, keychain_mask, &c, &g, test_mode) } ("web", Some(_)) => command::owner_api( owner_api, keychain_mask, wallet_config, - tor_config, global_wallet_args, test_mode, ), @@ -1360,22 +1380,15 @@ where command::send( owner_api, km, - Some(tor_config.clone()), a, + tor_config, wallet_config.dark_background_color_scheme.unwrap_or(true), test_mode, ) } ("receive", Some(args)) => { let a = arg_parse!(parse_receive_args(&args)); - command::receive( - owner_api, - km, - &global_wallet_args, - a, - Some(tor_config.clone()), - test_mode, - ) + command::receive(owner_api, km, &global_wallet_args, a, tor_config, test_mode) } ("unpack", Some(args)) => { let a = arg_parse!(parse_unpack_args(&args)); @@ -1399,7 +1412,7 @@ where command::process_invoice( owner_api, km, - Some(tor_config.clone()), + tor_config, a, wallet_config.dark_background_color_scheme.unwrap_or(true), test_mode, @@ -1486,8 +1499,8 @@ where _ => Err(Error::ArgumentError(String::from("Unknown contract subcommand.")).into()), }, _ => { - let msg = format!("Unknown wallet command, use 'grin-wallet help' for details"); - return Err(Error::ArgumentError(msg)); + let msg = "Unknown wallet command, use 'grin-wallet help' for details".to_string(); + Err(Error::ArgumentError(msg)) } } } diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index bce4a8d..019e6cf 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -21,6 +21,7 @@ extern crate log; extern crate grin_wallet; use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy}; +use std::path::PathBuf; use clap::App; use std::thread; @@ -60,7 +61,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // add wallet to proxy //let wallet1 = test_framework::create_wallet(&format!("{}/wallet1", test_dir), client1.clone()); let config1 = initial_setup_wallet(test_dir, "wallet1"); - let wallet_config1 = config1.clone().members.unwrap().wallet; + let wallet_config1 = config1.clone().members.wallet; let (wallet1, mask1_i) = instantiate_wallet( wallet_config1.clone(), client1.clone(), @@ -80,7 +81,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; let config2 = initial_setup_wallet(test_dir, "wallet2"); - let wallet_config2 = config2.clone().members.unwrap().wallet; + let wallet_config2 = config2.clone().members.wallet; let (wallet2, mask2_i) = instantiate_wallet( wallet_config2.clone(), client2.clone(), @@ -148,14 +149,14 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // Mine a bit into wallet 1 so we have something to send // (TODO: Be able to stop listeners so we can test this better) - let wallet_config1 = config1.clone().members.unwrap().wallet; + let wallet_config1 = config1.clone().members.wallet; let (wallet1, mask1_i) = instantiate_wallet(wallet_config1, client1.clone(), "password1", "default")?; let mask1 = (&mask1_i).as_ref(); grin_wallet_controller::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |api, m| { api.set_active_account(m, "mining")?; Ok(()) @@ -222,7 +223,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; bh += 1; - let wallet_config1 = config1.clone().members.unwrap().wallet; + let wallet_config1 = config1.clone().members.wallet; let (wallet1, mask1_i) = instantiate_wallet( wallet_config1.clone(), client1.clone(), @@ -233,9 +234,9 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // Check our transaction log, should have 10 entries grin_wallet_controller::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |api, m| { api.set_active_account(m, "mining")?; let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; @@ -259,7 +260,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: execute_command(&app, test_dir, "wallet2", &client1, arg_vec)?; // check results in wallet 2 - let wallet_config2 = config2.clone().members.unwrap().wallet; + let wallet_config2 = config2.clone().members.wallet; let (wallet2, mask2_i) = instantiate_wallet( wallet_config2.clone(), client2.clone(), @@ -269,9 +270,9 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let mask2 = (&mask2_i).as_ref(); grin_wallet_controller::controller::owner_single_use( - Some(wallet2.clone()), + wallet2.clone(), mask2, - None, + PathBuf::from(test_dir), |api, m| { api.set_active_account(m, "account_1")?; let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; @@ -284,9 +285,9 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // Send to wallet 2 with --amount_includes_fee let mut old_balance = 0; grin_wallet_controller::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |api, m| { api.set_active_account(m, "mining")?; let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; @@ -344,9 +345,9 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // Check the new balance of wallet 1 reduced by EXACTLY the tx amount (instead of amount + fee) // This confirms that the TX amount was correctly computed to allow for the fee grin_wallet_controller::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |api, m| { api.set_active_account(m, "mining")?; let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; @@ -421,7 +422,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: bh += 1; // Check our transaction log, should have bh entries - let wallet_config1 = config1.clone().members.unwrap().wallet; + let wallet_config1 = config1.clone().members.wallet; let (wallet1, mask1_i) = instantiate_wallet( wallet_config1.clone(), client1.clone(), @@ -431,9 +432,9 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let mask1 = (&mask1_i).as_ref(); grin_wallet_controller::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |api, m| { api.set_active_account(m, "mining")?; let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; @@ -494,7 +495,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: bh += 1; // Check our transaction log, should have bh entries + 1 for self-seld - let wallet_config1 = config1.clone().members.unwrap().wallet; + let wallet_config1 = config1.clone().members.wallet; let (wallet1, mask1_i) = instantiate_wallet( wallet_config1.clone(), client1.clone(), @@ -504,9 +505,9 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let mask1 = (&mask1_i).as_ref(); grin_wallet_controller::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |api, m| { api.set_active_account(m, "mining")?; let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; @@ -629,15 +630,15 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // get tx output via -tx parameter let mut tx_id = "".to_string(); grin_wallet_controller::controller::owner_single_use( - Some(wallet2.clone()), + wallet2.clone(), mask2, - None, + PathBuf::from(test_dir), |api, m| { api.set_active_account(m, "default")?; let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; let some_tx_id = txs[0].tx_slate_id.clone(); assert!(some_tx_id.is_some()); - tx_id = some_tx_id.unwrap().to_hyphenated().to_string().clone(); + tx_id = some_tx_id.unwrap().to_string().clone(); Ok(()) }, )?; @@ -696,9 +697,9 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // and recently matured coinbase outputs, which were not mature at time of spending. // This confirms that the TX amount was correctly computed to allow for the fee grin_wallet_controller::controller::owner_single_use( - Some(wallet1.clone()), + wallet1.clone(), mask1, - None, + PathBuf::from(test_dir), |api, m| { api.set_active_account(m, "mining")?; let (_, wallet1_info) = api.retrieve_summary_info(m, true, 10)?; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index ee01a40..7833061 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -36,6 +36,7 @@ use util::secp::key::{PublicKey, SecretKey}; use grin_api as api; use grin_wallet::cmd::wallet_args; +use grin_wallet_config::config::reload_global_config; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -72,7 +73,7 @@ macro_rules! setup_proxy { // add wallet to proxy let config1 = initial_setup_wallet($test_dir, "wallet1"); - let wallet_config1 = config1.clone().members.unwrap().wallet; + let wallet_config1 = config1.clone().members.wallet; //config1.owner_api_listen_port = Some(13420); let ($wallet1, mask1_i) = instantiate_wallet( wallet_config1.clone(), @@ -97,7 +98,7 @@ macro_rules! setup_proxy { } let config2 = initial_setup_wallet($test_dir, "wallet2"); - let wallet_config2 = config2.clone().members.unwrap().wallet; + let wallet_config2 = config2.clone().members.wallet; //config2.api_listen_port = 23415; let ($wallet2, mask2_i) = instantiate_wallet( wallet_config2.clone(), @@ -124,14 +125,14 @@ macro_rules! setup_proxy { #[allow(dead_code)] pub fn clean_output_dir(test_dir: &str) { - let _ = remove_dir_all::remove_dir_all(test_dir); + let _ = fs::remove_dir_all(test_dir); } #[allow(dead_code)] pub fn setup(test_dir: &str) { util::init_test_logger(); clean_output_dir(test_dir); - global::set_local_chain_type(global::ChainTypes::AutomatedTesting); + global::set_local_chain_type(ChainTypes::AutomatedTesting); } /// Some tests require the global chain_type to be configured. @@ -141,7 +142,7 @@ pub fn setup(test_dir: &str) { /// leaks across multiple tests and will likely have unintended consequences. #[allow(dead_code)] pub fn setup_global_chain_type() { - global::init_global_chain_type(global::ChainTypes::AutomatedTesting); + global::init_global_chain_type(ChainTypes::AutomatedTesting); } /// Create a wallet config file in the given current directory @@ -150,7 +151,6 @@ pub fn config_command_wallet( wallet_name: &str, ) -> Result<(), grin_wallet_controller::Error> { let mut current_dir; - let mut default_config = GlobalWalletConfig::default(); current_dir = env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); @@ -165,6 +165,9 @@ pub fn config_command_wallet( .to_owned(), ))?; } + + let mut default_config = + GlobalWalletConfig::for_chain(&ChainTypes::AutomatedTesting, &config_file_name); default_config.update_paths(¤t_dir, ¤t_dir); default_config .write_to_file(config_file_name.to_str().unwrap(), false, None, None) @@ -191,7 +194,7 @@ pub fn initial_setup_wallet(dir_name: &str, wallet_name: &str) -> GlobalWalletCo let _ = fs::create_dir_all(current_dir.clone()); let mut config_file_name = current_dir.clone(); config_file_name.push("grin-wallet.toml"); - GlobalWalletConfig::new(config_file_name.to_str().unwrap()).unwrap() + reload_global_config(&config_file_name).unwrap() } fn get_wallet_subcommand<'a>( @@ -211,8 +214,8 @@ fn get_wallet_subcommand<'a>( _ => ArgMatches::new(), } } -// -// Helper to create an instance of the LMDB wallet + +/// Helper to create an instance of the LMDB wallet #[allow(dead_code)] pub fn instantiate_wallet( mut wallet_config: WalletConfig, @@ -275,21 +278,10 @@ pub fn execute_command( let args = app.clone().get_matches_from(arg_vec); let _ = get_wallet_subcommand(test_dir, wallet_name, args.clone()); let config = initial_setup_wallet(test_dir, wallet_name); - let mut wallet_config = config.clone().members.unwrap().wallet; - let tor_config = config.clone().members.unwrap().tor; - //unset chain type so it doesn't get reset - wallet_config.chain_type = None; - wallet_args::wallet_command( - &args, - wallet_config.clone(), - tor_config, - client.clone(), - true, - |_| {}, - ) + wallet_args::wallet_command(&args, config, client.clone(), true, |_| {}) } -// as above, but without necessarily setting up the wallet +/// As above, but without necessarily setting up the wallet #[allow(dead_code)] pub fn execute_command_no_setup( app: &App, @@ -307,13 +299,14 @@ where { let args = app.clone().get_matches_from(arg_vec); let _ = get_wallet_subcommand(test_dir, wallet_name, args.clone()); - let config = config::initial_setup_wallet(&ChainTypes::AutomatedTesting, None, true).unwrap(); - let mut wallet_config = config.clone().members.unwrap().wallet; + let mut config = + config::initial_setup_wallet(&ChainTypes::AutomatedTesting, None, true).unwrap(); + let mut wallet_config = config.clone().members.wallet; wallet_config.chain_type = None; wallet_config.api_secret_path = None; wallet_config.node_api_secret_path = None; - let tor_config = config.members.unwrap().tor.clone(); - wallet_args::wallet_command(&args, wallet_config, tor_config, client.clone(), true, f) + config.members.wallet = wallet_config; + wallet_args::wallet_command(&args, config, client.clone(), true, f) } pub fn post(url: &Url, api_secret: Option, input: &IN) -> Result diff --git a/tests/owner_v3_lifecycle.rs b/tests/owner_v3_lifecycle.rs index fd27a50..997bdb3 100644 --- a/tests/owner_v3_lifecycle.rs +++ b/tests/owner_v3_lifecycle.rs @@ -27,6 +27,7 @@ use std::thread; use std::time::Duration; use grin_keychain::ExtKeychain; +use grin_wallet_config::GlobalWalletConfig; use grin_wallet_impls::DefaultLCProvider; use grin_wallet_libwallet::{InitTxArgs, Slate, SlateVersion, VersionedSlate}; use serde_json; @@ -74,7 +75,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; let config2 = initial_setup_wallet(test_dir, "wallet2"); - let wallet_config2 = config2.clone().members.unwrap().wallet; + let wallet_config2 = config2.clone().members.wallet; //config2.api_listen_port = 23415; let (wallet2, mask2_i) = instantiate_wallet( wallet_config2.clone(), @@ -193,6 +194,26 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { let pb = PathBuf::from(format!("{}/wallet1/grin-wallet.toml", test_dir)); assert!(pb.exists()); + let req = serde_json::json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "set_tor_config", + "params": { + "tor_config": null + } + }); + let res = send_request_enc::<()>( + &JsonId::StrId(String::from("1")), + 1, + "http://127.0.0.1:43420/v3/owner", + &req.to_string(), + &shared_key, + )?; + assert!(res.is_ok()); + let tor = GlobalWalletConfig::new(pb.clone()).unwrap().tor_config(); + assert!(!tor.use_tor_listener); + assert_eq!(tor.skip_send_attempt, Some(true)); + // 5) Try and perform an operation without having a wallet open let req = include_str!("data/v3_reqs/retrieve_info.req.json"); let res = send_request_enc::( @@ -382,9 +403,9 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { // give this slate over to wallet 2 manually grin_wallet_controller::controller::owner_single_use( - Some(wallet2.clone()), + wallet2.clone(), mask2, - None, + PathBuf::from(test_dir), |api, m| { let args = InitTxArgs { src_acct_name: None, diff --git a/util/Cargo.toml b/util/Cargo.toml index 1cb5aa8..7552d89 100644 --- a/util/Cargo.toml +++ b/util/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_util" -version = "5.4.0-alpha.1" +version = "5.4.1" authors = ["Grin Developers "] description = "Util, for generic utilities and to re-export grin crates" license = "Apache-2.0" @@ -10,31 +10,15 @@ workspace = ".." edition = "2021" [dependencies] -rand = "0.6" serde = "1" serde_derive = "1" -ed25519-dalek = "1.0.0-pre.4" +ed25519-dalek = "2" data-encoding = "2" sha3 = "0.8" thiserror = "1" ##### Grin Imports -# For Release -#grin_util = "5.4.0" +grin_util = { path = "../grin/util"} -# For beta release - -# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" } - -# For bleeding edge -grin_util = { git = "https://github.com/mimblewimble/grin", rev = "cf2ed3f3becd62b5e754ec964fd90e332b9a021f" } - -# For local testing - -# grin_util = { path = "../../grin/util"} - -##### - -[dev-dependencies] -pretty_assertions = "0.6" +###### diff --git a/util/src/ov3.rs b/util/src/ov3.rs index 8c16b3d..924523f 100644 --- a/util/src/ov3.rs +++ b/util/src/ov3.rs @@ -13,8 +13,8 @@ // limitations under the License. use data_encoding::BASE32; -use ed25519_dalek::PublicKey as DalekPublicKey; -use ed25519_dalek::SecretKey as DalekSecretKey; +use ed25519_dalek::SigningKey as DalekSecretKey; +use ed25519_dalek::VerifyingKey as DalekPublicKey; use grin_util::from_hex; use sha3::{Digest, Sha3_256}; use std::convert::TryFrom; @@ -49,15 +49,7 @@ impl OnionV3Address { /// populate from a private key pub fn from_private(key: &[u8; 32]) -> Result { - let d_skey = match DalekSecretKey::from_bytes(key) { - Ok(k) => k, - Err(e) => { - return Err(OnionV3Error::InvalidPrivateKey(format!( - "Unable to create public key: {}", - e - ))); - } - }; + let d_skey = DalekSecretKey::from_bytes(key); let d_pub_key: DalekPublicKey = (&d_skey).into(); Ok(OnionV3Address(*d_pub_key.as_bytes())) }