diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 989bfb6..0da7c95 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -2,6 +2,17 @@ name: Continuous Integration on: [push, pull_request] jobs: + clippy: + name: Cargo clippy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + submodules: recursive + - run: rustup toolchain install 1.99.0 --profile minimal --component clippy + - run: cargo +1.99.0 clippy --workspace --all-targets -- -D warnings + + # Run tests alongside Clippy, even if lint fails linux-tests: name: Linux Tests runs-on: ubuntu-latest @@ -36,4 +47,4 @@ jobs: with: submodules: recursive - name: Tests - run: cargo test --release --all \ No newline at end of file + run: cargo test --release --all diff --git a/.hooks/pre-commit b/.hooks/pre-commit index 8056d6c..05bd537 100755 --- a/.hooks/pre-commit +++ b/.hooks/pre-commit @@ -14,6 +14,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +cargo +1.99.0 clippy --workspace --all-targets -- -D warnings +if [ $? != 0 ]; then + printf "clippy check failed; check with:\n" + printf "cargo +1.99.0 clippy --workspace --all-targets -- -D warnings\n" + printf "if clippy is missing: rustup toolchain install 1.99.0 --profile minimal --component clippy\n" + exit 1 +fi + rustfmt --version &>/dev/null if [ $? != 0 ]; then printf "[pre_commit] \033[0;31merror\033[0m: \"rustfmt\" not available. \n" diff --git a/Cargo.lock b/Cargo.lock index 5146a45..5d0ad67 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -202,9 +202,9 @@ checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arti-client" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d54b6c87059a9b6562bfe585f3a637b72f90cddaa327ac29b5ddf082a54b4" +checksum = "7ffc89b08e6a475a83d70e52f0ede139a433eb46e986a6cee6eeaa1b73297bf1" dependencies = [ "async-trait", "cfg-if 1.0.4", @@ -699,9 +699,9 @@ checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" [[package]] name = "caret" -version = "0.10.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bb840a063107846780a14acc022b55bf6c174997a393ffde8b58ff6630c1b56" +checksum = "beae2cb9f60bc3f21effaaf9c64e51f6627edd54eedc9199ba07f519ef2a2101" [[package]] name = "cc" @@ -1970,9 +1970,9 @@ dependencies = [ [[package]] name = "fs-mistrust" -version = "0.15.0" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd938e053fbfb6dba36106f4bcf27c53362e6152adc9341700c4bc2264cd4a8f" +checksum = "9cfebc7c6bb65d327ded064db65cd260b6c418c27ae790318650cfa2a81bf33f" dependencies = [ "derive_builder_fork_arti", "dirs 6.0.0", @@ -1984,6 +1984,17 @@ dependencies = [ "walkdir", ] +[[package]] +name = "fslock-guard" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e77b8a36ee17f9079b53db7281de9b16a8fb2bc97a7cd1e41a2998f3a837af7a" +dependencies = [ + "libc", + "thiserror 2.0.18", + "windows-sys 0.61.2", +] + [[package]] name = "fslock-guard" version = "0.8.0" @@ -2040,9 +2051,9 @@ dependencies = [ [[package]] name = "futures-copy" -version = "0.4.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcad91f8ba72542347d5cc8ee43891abe4698429fa7b3de56f17f4bb6fa514c4" +checksum = "24f320278d16b5617859cc2234ca5775a8d9b24faee8c14e54e79540caab053a" dependencies = [ "futures 0.3.32", "libc", @@ -2222,7 +2233,7 @@ checksum = "9985c9503b412198aa4197559e9a318524ebc4519c229bfa05a535828c950b9d" [[package]] name = "grin_api" -version = "5.5.1-alpha.0" +version = "5.5.2" dependencies = [ "bytes 1.12.0", "easy-jsonrpc-mw", @@ -2254,7 +2265,7 @@ dependencies = [ [[package]] name = "grin_chain" -version = "5.5.1-alpha.0" +version = "5.5.2" dependencies = [ "bit-vec", "bitflags 1.3.2", @@ -2278,7 +2289,7 @@ dependencies = [ [[package]] name = "grin_core" -version = "5.5.1-alpha.0" +version = "5.5.2" dependencies = [ "blake2-rfc", "byteorder", @@ -2304,7 +2315,7 @@ dependencies = [ [[package]] name = "grin_keychain" -version = "5.5.1-alpha.0" +version = "5.5.2" dependencies = [ "blake2-rfc", "byteorder", @@ -2325,7 +2336,7 @@ dependencies = [ [[package]] name = "grin_p2p" -version = "5.5.1-alpha.0" +version = "5.5.2" dependencies = [ "bitflags 1.3.2", "built", @@ -2348,7 +2359,7 @@ dependencies = [ [[package]] name = "grin_pool" -version = "5.5.1-alpha.0" +version = "5.5.2" dependencies = [ "blake2-rfc", "chrono", @@ -2365,9 +2376,9 @@ dependencies = [ [[package]] name = "grin_secp256k1zkp" -version = "0.7.15" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf7bb95f155b1eede2648a1b9afbba82bc3d9f2af0518b478767559a572bd973" +checksum = "57e0a5f761e8c56db5be865f79832677d3badb3be91d7172d468e448f3d69f82" dependencies = [ "arrayvec 0.7.8", "cc", @@ -2380,7 +2391,7 @@ dependencies = [ [[package]] name = "grin_store" -version = "5.5.1-alpha.0" +version = "5.5.2" dependencies = [ "byteorder", "chrono", @@ -2402,7 +2413,7 @@ dependencies = [ [[package]] name = "grin_util" -version = "5.5.1-alpha.0" +version = "5.5.2" dependencies = [ "anyhow", "backtrace", @@ -2422,7 +2433,7 @@ dependencies = [ [[package]] name = "grin_wallet" -version = "5.5.0" +version = "5.5.1" dependencies = [ "built", "clap", @@ -2446,11 +2457,12 @@ dependencies = [ "serde_json", "thiserror 1.0.69", "url", + "uuid", ] [[package]] name = "grin_wallet_api" -version = "5.5.0" +version = "5.5.1" dependencies = [ "base64 0.12.3", "chrono", @@ -2475,7 +2487,7 @@ dependencies = [ [[package]] name = "grin_wallet_config" -version = "5.5.0" +version = "5.5.1" dependencies = [ "dirs 2.0.2", "grin_core", @@ -2491,7 +2503,7 @@ dependencies = [ [[package]] name = "grin_wallet_controller" -version = "5.5.0" +version = "5.5.1" dependencies = [ "easy-jsonrpc-mw", "ed25519-dalek", @@ -2522,7 +2534,7 @@ dependencies = [ [[package]] name = "grin_wallet_impls" -version = "5.5.0" +version = "5.5.1" dependencies = [ "arti-client", "base64 0.12.3", @@ -2531,7 +2543,7 @@ dependencies = [ "chrono", "ed25519-dalek", "fs-mistrust", - "fslock-guard", + "fslock-guard 0.8.0", "futures 0.3.32", "grin_api", "grin_chain", @@ -2569,7 +2581,7 @@ dependencies = [ [[package]] name = "grin_wallet_libwallet" -version = "5.5.0" +version = "5.5.1" dependencies = [ "age", "base64 0.9.3", @@ -2608,7 +2620,7 @@ dependencies = [ [[package]] name = "grin_wallet_util" -version = "5.5.0" +version = "5.5.1" dependencies = [ "data-encoding", "ed25519-dalek", @@ -4005,9 +4017,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "oneshot-fused-workaround" -version = "0.7.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60d6f8f565703c8a15f98b7782e39526490f8c291910d80c9be54a753a822f6f" +checksum = "e17b52d0e4a06a4c7eb8d2943c0015fa628cf4ccc409429cebc0f5bed6d33a82" dependencies = [ "futures 0.3.32", ] @@ -5031,9 +5043,9 @@ dependencies = [ [[package]] name = "retry-error" -version = "0.13.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c0e06f9b501df8600ad8bd073f4990f703f36e0f48e574b431f4a15d69b449" +checksum = "cf6aa271ee564cc5d1df57c5cf7c6ac7a21a4f9f40d2bf1d32bf0a1bb3ddaeb0" dependencies = [ "humantime 2.4.0", "web-time", @@ -5344,9 +5356,9 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] name = "safelog" -version = "0.9.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c0812d386a9992c036500b92565c41f84c28fd2e48fe853a395c393261b730b" +checksum = "97a907e0d82c61b1b06a2030c968eb313dcf432686b77801a26bc4b206f96573" dependencies = [ "derive_more", "educe", @@ -5390,9 +5402,9 @@ dependencies = [ [[package]] name = "saturating-time" -version = "0.4.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "802bdbfcca9a239cb46eeaaedea507e37bb13ba1a673762d2e2ef7a9dac63144" +checksum = "b63583a1dd0647d1484228529ab4ecaa874048d2956f117362aa5f5826456230" [[package]] name = "schannel" @@ -5799,9 +5811,9 @@ dependencies = [ [[package]] name = "slotmap-careful" -version = "0.8.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7cd5208f878dce99cfbefa73c692c67edf946ac53e0cc4455e2dabe43d54af7" +checksum = "ed92816c1fbb29891a525b92d5fa95757c9dee47044f76c8e06ceb1e052a8d64" dependencies = [ "paste", "serde", @@ -6465,35 +6477,26 @@ checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" [[package]] name = "tor-async-utils" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58580b41636378f79500bca6a178787e0e434207e0880dd90698ae3f686f24d6" +checksum = "27fc83e7539ac5f717b722456df991ca8819782d04f7ae2ee28eefacca030eef" 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" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd3046aa299df67da91b45c02c24d48d40ae1845f9b91e27f9c8adbde78315ba" +checksum = "7bd01b9947f57a99193547f3a40a0bd179e9a332ead855c07e2fb702a1517f74" dependencies = [ - "derive-deftly", "derive_more", "getrandom 0.4.3", "hex", @@ -6506,16 +6509,15 @@ dependencies = [ "slab", "smallvec", "thiserror 2.0.18", - "tracing", "weak-table", "web-time-compat", ] [[package]] name = "tor-bytes" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b4833cc8ab3fca79eabc06f3ca97db102a3b7db861d77848d39932a6f0ed598" +checksum = "de6a7af55881d599cd48c841916520318d5711df17514001aafd5f796f61e337" dependencies = [ "bytes 1.12.0", "derive-deftly", @@ -6531,9 +6533,9 @@ dependencies = [ [[package]] name = "tor-cell" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73a01cb2ac6697c12b647729d3d7db404e306d1e08a7a3aacdbee08e35170ebd" +checksum = "dad292658d194b145aaec268ffb91566b7d96c98971eea4980c1bf951d7d082b" dependencies = [ "amplify", "bitflags 2.13.0", @@ -6562,15 +6564,14 @@ dependencies = [ [[package]] name = "tor-cert" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162d44b975e445de099b3a495710689652bbd0a9a3a0e4946341acbb3138b22b" +checksum = "474e732207b1be44f9ae4ddf295fba3644cd3c09494d131846ff9c9a624ab263" dependencies = [ "caret", "derive_builder_fork_arti", "derive_more", "digest 0.10.7", - "saturating-time", "thiserror 2.0.18", "tor-bytes", "tor-checkable", @@ -6581,9 +6582,9 @@ dependencies = [ [[package]] name = "tor-chanmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf15c4cbafa5745def4fced9e8e59148533a2bfc8d938e9fad7a0d6d16757712" +checksum = "b2bb088804f54de320ee97dd2a48ae319f0df9d9d0e37eef050d65488194a768" dependencies = [ "async-trait", "base64ct", @@ -6624,9 +6625,9 @@ dependencies = [ [[package]] name = "tor-checkable" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef81835cb0b2db460c694678eae8c4cbad5f31847e473aac42605f9b945fb31a" +checksum = "9505791bac25b31b8de88c0e2b02e1690e10ff1308583c6f61c320bab2677959" dependencies = [ "humantime 2.4.0", "signature", @@ -6637,9 +6638,9 @@ dependencies = [ [[package]] name = "tor-circmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b63cca1f18282f82b905b6a8c20c6f247787bc010d1b317d9eb98503e4352bf" +checksum = "7e986c7c4e1faae8a412b575ce66ff087050525a371db1034f0b24d70b459a2e" dependencies = [ "amplify", "async-trait", @@ -6687,9 +6688,9 @@ dependencies = [ [[package]] name = "tor-config" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a699adfb8bdb34699afcca7cbbd9d26329246940bc9dbc32f380c87578017350" +checksum = "224f85aa02b514c384ea5ec32f1b924233bea6b553195fd83da7f1e50a2e0d1b" dependencies = [ "amplify", "cfg-if 1.0.4", @@ -6721,9 +6722,9 @@ dependencies = [ [[package]] name = "tor-config-path" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38001695121fc778e67ac7a1c733d3158ee8942a55cfa343981b50d90f5daa" +checksum = "4232a56a8ce40a47ad6b42c9c7d9e6f4485e6e6a43b3149304c35bc295034107" dependencies = [ "directories", "serde", @@ -6735,9 +6736,9 @@ dependencies = [ [[package]] name = "tor-consdiff" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e9e3eb11e91ea4c1affe5e1f73628726c283942715739850546acb94bbe028" +checksum = "d5fcd0c631a66b45dca4421b8a06309dd02ae5d6aea5daa55399f68638b2abf3" dependencies = [ "derive_more", "digest 0.10.7", @@ -6752,9 +6753,9 @@ dependencies = [ [[package]] name = "tor-dirclient" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0027cd2a58abab9ebaf61c3c1da9b0fa9e6cbc914b88fedb7b3102bd4f4dd656" +checksum = "bf637d6a5d8c886f23ca2df50edfaa56443f23294428f037206fb3a0d07ba57e" dependencies = [ "async-compression", "base64ct", @@ -6781,9 +6782,9 @@ dependencies = [ [[package]] name = "tor-dircommon" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d2047b2f1ad3453c1060e5e39203bd87ead266e6873707bd7333b1d6bdac768" +checksum = "35e412167d54c3618c3261dc77f1a31fe20c518f59aca5abfdec5f600b6a9b1f" dependencies = [ "base64ct", "derive-deftly", @@ -6802,9 +6803,9 @@ dependencies = [ [[package]] name = "tor-dirmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57ebc162ccd628ef8e96912a9e42e848cd7305eb2a5a455a6002f54ad6826422" +checksum = "9b984d2b0f0a2764a1b24d7c4c203ef83600b071c0c5af36e20d4f63e80ce562" dependencies = [ "async-trait", "base64ct", @@ -6814,7 +6815,7 @@ dependencies = [ "educe", "event-listener", "fs-mistrust", - "fslock-guard", + "fslock-guard 0.7.0", "futures 0.3.32", "hex", "humantime 2.4.0", @@ -6859,9 +6860,9 @@ dependencies = [ [[package]] name = "tor-error" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6a7ed4aee3e0613a75d420032116dac82d7702594e28566befdfa6707a8fd0e" +checksum = "1409b1a9085502c7797405a01fe3f3292a9827c9ed6a3f7c34fbb222572db5ac" dependencies = [ "derive_more", "futures 0.3.32", @@ -6877,9 +6878,9 @@ dependencies = [ [[package]] name = "tor-general-addr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfee544a33dd3e67e0311cc46ef8f667cbf9c02c7c00ef4f25098a25b2b6e1cf" +checksum = "09f17e219140e587e169f71f53e528ca394c39e83593c9fbe9e9366cce7655e1" dependencies = [ "derive_more", "thiserror 2.0.18", @@ -6888,9 +6889,9 @@ dependencies = [ [[package]] name = "tor-guardmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1e8f52e4b1b08ba58970a9b9879b0b72c35dcba48bad389935f2778ed432d05" +checksum = "d56c43d7afa526449c6e6460d373a02624a24c78637ddd7c68e2ac1879ae587c" dependencies = [ "amplify", "base64ct", @@ -6933,9 +6934,9 @@ dependencies = [ [[package]] name = "tor-hsclient" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dc813f71e63fd324c4b1b1647ddc2fcc4b6e77c45091e6769ae80e591726ec" +checksum = "1ff8ba0afebc5f76b42240f76b2bfb92aa5862c19ff184492c59c654750ee275" dependencies = [ "async-trait", "derive-deftly", @@ -6978,9 +6979,9 @@ dependencies = [ [[package]] name = "tor-hscrypto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f82fd6a5a6ede5ece5e7f52708bdf0a007e8f975f9825689b376f038845f1e88" +checksum = "3761c1828e74818cba4eb661d1eb79d4f663b05e8e7d3bc6e35d754968282fc0" dependencies = [ "cipher 0.4.4", "data-encoding", @@ -7011,9 +7012,9 @@ dependencies = [ [[package]] name = "tor-hsrproxy" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4231a55048af49ae2a8fcb2d41ea0df986b68c26bf6128f97f7f1324d47498" +checksum = "cc0d8041225c2721fb68e8406c2121e3168ea3998148df253859fec70ea20741" dependencies = [ "derive-deftly", "futures 0.3.32", @@ -7040,9 +7041,9 @@ dependencies = [ [[package]] name = "tor-hsservice" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "170b66c977d3b16a5ff79ec344c06392076f0326d2d65146a58c450c50395dae" +checksum = "5fa87ed8d1ccfe8447b4e65bf0e2dfcab6a8ac9d2eadf7b3f37c102e1c18e9bb" dependencies = [ "amplify", "async-trait", @@ -7099,9 +7100,9 @@ dependencies = [ [[package]] name = "tor-key-forge" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30f83389917e9908c43457c80d0b982ba6dcd3e6ea36a37b29167b7619d9eaa3" +checksum = "86c877b95e0679f151743bc2b706320a29e14bd18d9bcb92918df34948e2e9d2" dependencies = [ "derive-deftly", "derive_more", @@ -7121,9 +7122,9 @@ dependencies = [ [[package]] name = "tor-keymgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7c18fb26d112c6022b7d1de558a4045b574fecfa1c504045145d8e1a9dc01a" +checksum = "5f59fbec28e31d688822b4c00a6f7fd94539886baccd3ce1b35dc26699c37873" dependencies = [ "amplify", "arrayvec 0.7.8", @@ -7162,9 +7163,9 @@ dependencies = [ [[package]] name = "tor-linkspec" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "638a849a5d65d4e37adb6a2fa597a5a5c0decb749c17e76d3c44c4aefd696270" +checksum = "0e1cc8d5469c324d1e0761066d868363d3fdccb723b14cdc983a5aef9b67981b" dependencies = [ "base64ct", "by_address", @@ -7189,9 +7190,9 @@ dependencies = [ [[package]] name = "tor-llcrypto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ef0e63e805e9c1da61511a93eca502dc29bcb0b8635e9668ec750b63a1e53a1" +checksum = "d0015d521f5e30a2f74879fe4c615fc2c3ace822d7cc88c1dfed0ae816b25f15" dependencies = [ "aes", "base64ct", @@ -7232,9 +7233,9 @@ dependencies = [ [[package]] name = "tor-log-ratelim" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37d0f759a875b6f9b6f3657a2626a70e2474e698a4404501033babe63ad888a6" +checksum = "7d16152b21f2e7b309dfbdcbe587c5adba9547d3119f2933b453d6edbce7e8e0" dependencies = [ "futures 0.3.32", "humantime 2.4.0", @@ -7248,9 +7249,9 @@ dependencies = [ [[package]] name = "tor-memquota" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c06f2e981120a4c1da1e361573cee4af618d05fa3c7ec37c139d766f1b8d47f" +checksum = "38ad2950d88e968572b0de6bb5702f5ed42f36555f362fb741c572c62441476e" dependencies = [ "cfg-if 1.0.4", "derive-deftly", @@ -7279,9 +7280,9 @@ dependencies = [ [[package]] name = "tor-memquota-cost" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b86eb903fee638e9211daddaddc146f0c5e4f5605d79983548fce6fec596325c" +checksum = "993ad5bfd39fb629990da40c2b2086284b1481b7d4843652a959db1d9e5ac463" dependencies = [ "derive-deftly", "itertools 0.14.0", @@ -7291,9 +7292,9 @@ dependencies = [ [[package]] name = "tor-netdir" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8160580273eec3576158c3e833ff198870665dacebb373585892dde93cf9803" +checksum = "6700c5e590818d9873a13e06b49b95cf3a39fa8fb3968bd67ec3295cd584b97c" dependencies = [ "async-trait", "bitflags 2.13.0", @@ -7324,9 +7325,9 @@ dependencies = [ [[package]] name = "tor-netdoc" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51598bfd24866de2c51e0de7a6e2418f86c6278cfeba2f85295ce45367fd8e06" +checksum = "a497ce4c36f59e4c67c352e3b80cd4642f6c5e660bb003de1922be4c7ed03081" dependencies = [ "amplify", "base64ct", @@ -7340,7 +7341,6 @@ dependencies = [ "hex", "hostname-validator", "humantime 2.4.0", - "ipnet", "itertools 0.14.0", "memchr", "paste", @@ -7374,16 +7374,16 @@ dependencies = [ [[package]] name = "tor-persist" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2ff75e20adb6a1a7ad07e16b55e56d5376706cc0090ab8831f008f1a89243f2" +checksum = "b6da1a96a1f6418faac1cd1892e029fd265cf50e67e941a4ba2580d92dd32d47" dependencies = [ "amplify", "derive-deftly", "derive_more", "filetime", "fs-mistrust", - "fslock-guard", + "fslock-guard 0.7.0", "futures 0.3.32", "itertools 0.14.0", "oneshot-fused-workaround", @@ -7403,9 +7403,9 @@ dependencies = [ [[package]] name = "tor-proto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "666b602da8ba5a4189d6ff551f5dd9db949b503780140d175435658970a1ea54" +checksum = "a0a5fa0e1a365fc089a7f140f4142379dd74c91c15103c2f9d11ea711e16029e" dependencies = [ "amplify", "async-trait", @@ -7439,6 +7439,7 @@ dependencies = [ "static_assertions", "strum 0.28.0", "subtle", + "sync_wrapper", "thiserror 2.0.18", "tokio", "tokio-util", @@ -7469,9 +7470,9 @@ dependencies = [ [[package]] name = "tor-protover" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef84569d020c36eb322976f9a5dec1d3fa992db9739237ad1ae923b0ddeb298" +checksum = "c4f7f4ee15c9bfa0b700ae06e85fa52abddf17a35531cd3d3833412900e8da5c" dependencies = [ "caret", "paste", @@ -7483,9 +7484,9 @@ dependencies = [ [[package]] name = "tor-ptmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66db88ee6c5ba60a077b592b7e566d465220de61ccfd473fba6567c577cad475" +checksum = "b4cc37ac22faff9e0233fa287b92819d8819f31cae85a50ff99c51dd549b31c0" dependencies = [ "async-trait", "cfg-if 1.0.4", @@ -7513,9 +7514,9 @@ dependencies = [ [[package]] name = "tor-relay-selection" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09778e3a45fdf49ca335fa16a0032abc5d4e1cacff9f46c3ed3e2a416d088aa6" +checksum = "5b565b6dec2e3edb7b033203a3662edb7b586e486d53e02af4295e05e7562870" dependencies = [ "rand 0.10.2", "serde", @@ -7527,9 +7528,9 @@ dependencies = [ [[package]] name = "tor-rtcompat" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "981279291476ad7ec309c874fa99b8d31250432a48ff6eea3f7405edbbd254e1" +checksum = "fcd7a4ff4898044b3ec693c0bf098251accf13c58741c44ed9364ce5faa89287" dependencies = [ "amplify", "async-native-tls", @@ -7562,9 +7563,9 @@ dependencies = [ [[package]] name = "tor-rtmock" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a3ee9695304cc44cc0de1dc673c9a71419318e214dc04ed7883a058d050654d" +checksum = "8331e7d57bf7cf157cf3610ff6dbb5a591de5c3b22fa65ea6be18b08ff81477a" dependencies = [ "amplify", "assert_matches", @@ -7592,9 +7593,9 @@ dependencies = [ [[package]] name = "tor-socksproto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbf78ef55dbfccb5a95cd75eb433621947923653cb91c9941d5a0a5116e510ee" +checksum = "55f432eda94343bdadd73995f0b3082d96637dadb0e20c3f9a1bf2349f623d3c" dependencies = [ "amplify", "caret", @@ -7609,9 +7610,9 @@ dependencies = [ [[package]] name = "tor-units" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0325a93f3b35c5a9bda74705ce89b753e1c8e183af6945826188cef16687d80" +checksum = "8cf033ee8b22b11abd8272272e19ccbbf58c7b3152f8d224aa8d21f358c43d0d" dependencies = [ "derive-deftly", "derive_more", @@ -8100,9 +8101,9 @@ dependencies = [ [[package]] name = "web-time-compat" -version = "0.2.0" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af46dad42aa37be3b4a116fe613365f991b8bdae6cd6ce82d84fa9f9e8f70ae4" +checksum = "39819265f219f60a92312f2755262dba9fff180a4ec281556863d69fa36adc59" dependencies = [ "web-time", ] diff --git a/Cargo.toml b/Cargo.toml index 901278d..725816d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format." license = "Apache-2.0" @@ -19,6 +19,14 @@ path = "src/bin/grin-wallet.rs" members = ["api", "config", "controller", "impls", "libwallet", "util"] exclude = ["integration"] +[workspace.dependencies] +grin_api = { path = "grin/api" } +grin_chain = { path = "grin/chain" } +grin_core = { path = "grin/core" } +grin_keychain = { path = "grin/keychain" } +grin_store = { path = "grin/store" } +grin_util = { path = "grin/util" } + [dependencies] clap = { version = "2.33", features = ["yaml"] } rpassword = "7.5.4" @@ -28,19 +36,20 @@ linefeed = "0.6" semver = "1.0.28" rustyline = "9" lazy_static = "1" +uuid = { version = "1.23.4", features = ["v4"] } -grin_wallet_api = { path = "./api", version = "5.5.0" } -grin_wallet_impls = { path = "./impls", version = "5.5.0" } -grin_wallet_libwallet = { path = "./libwallet", version = "5.5.0" } -grin_wallet_controller = { path = "./controller", version = "5.5.0" } -grin_wallet_config = { path = "./config", version = "5.5.0" } +grin_wallet_api = { path = "./api", version = "5.5.1" } +grin_wallet_impls = { path = "./impls", version = "5.5.1" } +grin_wallet_libwallet = { path = "./libwallet", version = "5.5.1" } +grin_wallet_controller = { path = "./controller", version = "5.5.1" } +grin_wallet_config = { path = "./config", version = "5.5.1" } ##### Grin Imports -grin_core = { path = "grin/core"} -grin_keychain = { path = "grin/keychain"} -grin_util = { path = "grin/util"} -grin_api = { path = "grin/api"} +grin_core = { workspace = true } +grin_keychain = { workspace = true } +grin_util = { workspace = true } +grin_api = { workspace = true } ###### @@ -51,4 +60,4 @@ built = { version = "0.8.0", features = ["git2"]} url = "2.1" serde = "1" serde_json = "1" -easy-jsonrpc-mw = "0.5.4" \ No newline at end of file +easy-jsonrpc-mw = "0.5.4" diff --git a/api/Cargo.toml b/api/Cargo.toml index c797161..31bca3a 100644 --- a/api/Cargo.toml +++ b/api/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_api" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Grin Wallet API" license = "Apache-2.0" @@ -22,16 +22,16 @@ ring = "0.17.14" base64 = "0.12" ed25519-dalek = "2" -grin_wallet_libwallet = { path = "../libwallet", version = "5.5.0" } -grin_wallet_config = { path = "../config", version = "5.5.0" } -grin_wallet_impls = { path = "../impls", version = "5.5.0" } -grin_wallet_util = { path = "../util", version = "5.5.0" } +grin_wallet_libwallet = { path = "../libwallet", version = "5.5.1" } +grin_wallet_config = { path = "../config", version = "5.5.1" } +grin_wallet_impls = { path = "../impls", version = "5.5.1" } +grin_wallet_util = { path = "../util", version = "5.5.1" } ##### Grin Imports -grin_core = { path = "../grin/core"} -grin_keychain = { path = "../grin/keychain"} -grin_util = { path = "../grin/util"} +grin_core = { workspace = true } +grin_keychain = { workspace = true } +grin_util = { workspace = true } ##### diff --git a/api/src/foreign.rs b/api/src/foreign.rs index c161249..c897a65 100644 --- a/api/src/foreign.rs +++ b/api/src/foreign.rs @@ -20,15 +20,12 @@ use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI}; use crate::libwallet::EarlyPaymentProof; use crate::libwallet::{ - BlockFees, CbData, Error, NodeClient, NodeVersionInfo, Slate, VersionInfo, WalletInst, - WalletLCProvider, + BlockFees, CbData, Error, NodeClient, NodeVersionInfo, Slate, VersionInfo, WalletLCProvider, }; use crate::try_slatepack_sync_workflow; use crate::util::secp::key::SecretKey; -use crate::util::Mutex; use ed25519_dalek::VerifyingKey as DalekPublicKey; use libwallet::SlatepackAddress; -use std::sync::Arc; /// ForeignAPI Middleware Check callback pub type ForeignCheckMiddleware = @@ -58,15 +55,14 @@ pub enum ForeignCheckMiddlewareFn { /// called the ['Owner'](struct.Owner.html) and ['Foreign'](struct.Foreign.html) APIs /// /// * The 'Foreign' API contains methods that other wallets will -/// use to interact with the owner's wallet. This API can be exposed -/// to the outside world, with the consideration as to how that can -/// be done securely up to the implementor. +/// use to interact with the owner's wallet. This API can be exposed +/// to the outside world, with the consideration as to how that can +/// be done securely up to the implementor. /// /// Methods in both APIs are intended to be 'single use', that is to say each /// method will 'open' the wallet (load the keychain with its master seed), perform /// its operation, then 'close' the wallet (unloading references to the keychain and master /// seed). - pub struct Foreign<'a, L, C, K> where L: WalletLCProvider<'a, C, K>, @@ -74,7 +70,7 @@ where K: Keychain + 'a, { /// Wallet instance - pub wallet_inst: Arc>>>, + pub wallet_inst: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, /// Wallet configuration path config_path: crate::ConfigPath, /// Flag to normalize some output during testing. Can mostly be ignored. @@ -101,13 +97,13 @@ where /// /// # Arguments /// * `wallet_in` - A reference-counted mutex containing an implementation of the - /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. + /// [`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) + /// whose seed has been XORed with a token value (such as when running the foreign + /// and owner listeners in the same instance) /// * middleware - Option middleware which containts the NodeVersionInfo and can call - /// a predefined function with the slate to check if the operation should continue + /// a predefined function with the slate to check if the operation should continue /// /// # Returns /// * An instance of the ForeignApi holding a reference to the provided wallet @@ -177,9 +173,8 @@ where /// // .. perform wallet operations /// /// ``` - pub fn new

( - wallet_inst: Arc>>>, + wallet_inst: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, config_path: P, keychain_mask: Option, middleware: Option, @@ -212,7 +207,6 @@ where /// let version_info = api_foreign.check_version(); /// // check and proceed accordingly /// ``` - pub fn check_version(&self) -> Result { if let Some(m) = self.middleware.as_ref() { let mut w_lock = self.wallet_inst.lock(); @@ -238,7 +232,7 @@ where /// # Arguments /// /// * `block_fees` - A [`BlockFees`](../grin_wallet_libwallet/api_impl/types/struct.BlockFees.html) - /// struct, set up as follows: + /// struct, set up as follows: /// /// `fees` - should contain the sum of all transaction fees included in the potential /// block @@ -251,7 +245,7 @@ where /// /// # Returns /// * `Ok`([`cb_data`](../grin_wallet_libwallet/api_impl/types/struct.CbData.html)`)` if successful. This - /// will contain the corresponding output, kernel and keyID used to create the coinbase output. + /// will contain the corresponding output, kernel and keyID used to create the coinbase output. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -275,7 +269,6 @@ where /// // ... /// } /// ``` - pub fn build_coinbase(&self, block_fees: &BlockFees) -> Result { let mut w_lock = self.wallet_inst.lock(); let w = w_lock.lc_provider()?.wallet_inst()?; @@ -288,7 +281,7 @@ where } foreign::build_coinbase( w, - (&self.keychain_mask).as_ref(), + self.keychain_mask.as_ref(), block_fees, self.doctest_mode, ) @@ -311,18 +304,18 @@ where /// /// # Arguments /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). - /// The slate should contain the results of the sender's round 1 (e.g, public nonce and public - /// excess value). + /// The slate should contain the results of the sender's round 1 (e.g, public nonce and public + /// excess value). /// * `dest_acct_name` - The name of the account into which the slate should be received. If - /// `None`, the default account is used. + /// `None`, the default account is used. /// * `r_addr` - If included, attempt to send the slate back to the sender using the slatepack sync - /// send (TOR). If providing this argument, check the `state` field of the slate to see if the - /// sync_send was successful (it should be S3 if the synced send sent successfully). + /// send (TOR). If providing this argument, check the `state` field of the slate to see if the + /// sync_send was successful (it should be S3 if the synced send sent successfully). /// /// # Returns /// * a result containing: /// * `Ok`([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html)`)` if successful, - /// containing the new slate updated with the recipient's output and public signing information. + /// containing the new slate updated with the recipient's output and public signing information. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Remarks @@ -346,7 +339,6 @@ where /// // ... /// } /// ``` - pub fn receive_tx( &self, slate: &Slate, @@ -368,7 +360,7 @@ where } let ret_slate = foreign::receive_tx( w, - (&self.keychain_mask).as_ref(), + self.keychain_mask.as_ref(), slate, dest_acct_name, self.doctest_mode, @@ -388,7 +380,7 @@ where let parent_key_id = w.parent_key_id(); match update_tx_slate_state( w, - (&self.keychain_mask).as_ref(), + self.keychain_mask.as_ref(), &parent_key_id, &s, ) { @@ -423,11 +415,11 @@ where /// # Arguments /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). The /// * `post_automatically` - If true, post the finalized transaction to the configured listening - /// node + /// node /// /// # Returns /// * Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html)) if successful, - /// containing the new finalized slate. + /// containing the new finalized slate. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -454,7 +446,6 @@ where /// let slate = api_foreign.finalize_tx(&slate, true); /// // if okay, then post via the owner API /// ``` - pub fn finalize_tx(&self, slate: &Slate, post_automatically: bool) -> Result { let mut w_lock = self.wallet_inst.lock(); let w = w_lock.lc_provider()?.wallet_inst()?; @@ -469,7 +460,7 @@ where true => false, false => post_automatically, }; - foreign::finalize_tx(w, (&self.keychain_mask).as_ref(), slate, post_automatically) + foreign::finalize_tx(w, self.keychain_mask.as_ref(), slate, post_automatically) } // Below is a foreign wrapper around owner calls to 'new' and 'sign' which are only executed @@ -511,7 +502,7 @@ where None, )?; } - foreign::contract_new(w, (&self.keychain_mask).as_ref(), args) + foreign::contract_new(w, self.keychain_mask.as_ref(), args) } /// Sign the receiving side of a contract through the foreign API. @@ -557,7 +548,7 @@ where Some(slate), )?; } - foreign::contract_sign(w, (&self.keychain_mask).as_ref(), args, slate) + foreign::contract_sign(w, self.keychain_mask.as_ref(), args, slate) } /// Verify an early payment proof against the chain diff --git a/api/src/foreign_rpc.rs b/api/src/foreign_rpc.rs index 1a93d68..7b59246 100644 --- a/api/src/foreign_rpc.rs +++ b/api/src/foreign_rpc.rs @@ -20,7 +20,6 @@ use crate::libwallet::{ Slate, SlateVersion, VersionInfo, VersionedCoinbase, VersionedSlate, WalletLCProvider, }; use crate::{Foreign, ForeignCheckMiddlewareFn}; -use easy_jsonrpc_mw; use grin_wallet_config::initial_setup_wallet; use libwallet::SlatepackAddress; use std::path::PathBuf; @@ -113,7 +112,6 @@ pub trait ForeignRpc { # ,false, 4, false, false); ``` */ - fn build_coinbase(&self, block_fees: &BlockFees) -> Result; /** @@ -323,19 +321,14 @@ where } }, }; - let out_slate = Foreign::receive_tx( - self, - &slate_from, - dest_acct_name.as_ref().map(String::as_str), - dest, - )?; - Ok(VersionedSlate::into_version(out_slate, version)?) + let out_slate = Foreign::receive_tx(self, &slate_from, dest_acct_name.as_deref(), dest)?; + VersionedSlate::into_version(out_slate, version) } fn finalize_tx(&self, in_slate: VersionedSlate) -> Result { let version = in_slate.version(); let out_slate = Foreign::finalize_tx(self, &Slate::from(in_slate), true)?; - Ok(VersionedSlate::into_version(out_slate, version)?) + VersionedSlate::into_version(out_slate, version) } } @@ -466,19 +459,14 @@ pub fn run_doctest_foreign( let _ = test_framework::award_blocks_to_wallet( &chain, wallet1.clone(), - (&mask1).as_ref(), - 1 as usize, + mask1.as_ref(), + 1_usize, false, ); //update local outputs after each block, so transaction IDs stay consistent - let (wallet_refreshed, _) = api_impl::owner::retrieve_summary_info( - wallet1.clone(), - (&mask1).as_ref(), - &None, - true, - 1, - ) - .unwrap(); + let (wallet_refreshed, _) = + api_impl::owner::retrieve_summary_info(wallet1.clone(), mask1.as_ref(), &None, true, 1) + .unwrap(); assert!(wallet_refreshed); } @@ -491,7 +479,7 @@ pub fn run_doctest_foreign( amount, ..Default::default() }; - api_impl::owner::issue_invoice_tx(w, (&mask2).as_ref(), args, true).unwrap() + api_impl::owner::issue_invoice_tx(w, mask2.as_ref(), args, true).unwrap() }; slate = { let mut w_lock = wallet1.lock(); @@ -505,7 +493,7 @@ pub fn run_doctest_foreign( selection_strategy_is_use_all: true, ..Default::default() }; - api_impl::owner::process_invoice_tx(w, (&mask1).as_ref(), &slate, args, true).unwrap() + api_impl::owner::process_invoice_tx(w, mask1.as_ref(), &slate, args, true).unwrap() }; println!("INIT INVOICE SLATE"); // Spit out slate for input to finalize_tx @@ -525,7 +513,7 @@ pub fn run_doctest_foreign( selection_strategy_is_use_all: true, ..Default::default() }; - let slate = api_impl::owner::init_send_tx(w, (&mask1).as_ref(), args, true).unwrap(); + let slate = api_impl::owner::init_send_tx(w, mask1.as_ref(), args, true).unwrap(); println!("INIT SLATE"); // Spit out slate for input to finalize_tx println!("{}", serde_json::to_string_pretty(&slate).unwrap()); diff --git a/api/src/owner.rs b/api/src/owner.rs index 24c3478..d707d35 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -14,6 +14,7 @@ //! Owner API External Definition +use crate::config::config::{reload_global_config, update_global_config, WALLET_CONFIG_FILE_NAME}; use crate::config::{TorConfig, WalletConfig}; use crate::core::core::OutputFeatures; use crate::core::global; @@ -26,21 +27,23 @@ use crate::libwallet::api_impl::{owner, owner_updater}; use crate::libwallet::contract::types::{ ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI, ContractView, }; +use crate::libwallet::mwixnet::{parse_mwixnet_response, MwixnetResponse, SwapReq}; +use crate::libwallet::mwixnet::{MixnetReqCreationParams, MwixnetReqCreationResult}; +use crate::libwallet::slatepack::SlatepackAddressIndex; +use crate::libwallet::wallet_lock; use crate::libwallet::EarlyPaymentProof; +use crate::libwallet::RetrieveTxQueryArgs; use crate::libwallet::{ AcctPathMapping, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress, - TxLogEntry, ViewWallet, WalletInfo, WalletInst, WalletLCProvider, + TxLogEntry, ViewWallet, WalletBackend, WalletInfo, WalletLCProvider, }; 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 impls::json_rpc; +use impls::tor::arti::tor_post; use chrono::prelude::*; use ed25519_dalek::SigningKey as DalekSecretKey; @@ -60,15 +63,14 @@ use uuid::Uuid; /// called the ['Owner'](struct.Owner.html) and ['Foreign'](struct.Foreign.html) APIs /// /// * The 'Owner' API is intended to expose methods that are to be -/// used by the wallet owner only. It is vital that this API is not -/// exposed to anyone other than the owner of the wallet (i.e. the -/// person with access to the seed and password. +/// used by the wallet owner only. It is vital that this API is not +/// exposed to anyone other than the owner of the wallet (i.e. the +/// person with access to the seed and password. /// /// Methods in both APIs are intended to be 'single use', that is to say each /// method will 'open' the wallet (load the keychain with its master seed), perform /// its operation, then 'close' the wallet (unloading references to the keychain and master /// seed). - pub struct Owner where L: WalletLCProvider<'static, C, K> + 'static, @@ -76,7 +78,7 @@ where K: Keychain + 'static, { /// Contains all methods to manage the wallet - pub wallet_inst: Arc>>>, + pub wallet_inst: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, /// Wallet configuration path config_path: crate::ConfigPath, /// Flag to normalize some output during testing. Can mostly be ignored. @@ -112,9 +114,9 @@ where /// /// # Arguments /// * `wallet_in` - A reference-counted mutex containing an implementation of the - /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. + /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. /// * `custom_channel` - A custom MPSC Tx/Rx pair to capture status - /// updates + /// updates /// * `config_path` - Path to the wallet configuration file /// /// # Returns @@ -184,9 +186,8 @@ where /// // .. perform wallet operations /// /// ``` - pub fn new

( - wallet_inst: Arc>>>, + wallet_inst: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, custom_channel: Option>, config_path: P, ) -> Self @@ -244,7 +245,6 @@ where /// * `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) -> Result<(), Error> { let _wallet_lock = self.wallet_inst.lock(); update_global_config(&self.config_path(), |config| { @@ -265,10 +265,10 @@ where } /// Returns a list of accounts stored in the wallet (i.e. mappings between - /// user-specified labels and BIP32 derivation paths. + /// user-specified labels and BIP32 derivation paths). /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// /// # Returns /// * Result Containing: @@ -278,7 +278,7 @@ where /// # Remarks /// /// * A wallet should always have the path with the label 'default' path defined, - /// with path m/0/0 + /// with path m/0/0 /// * This method does not need to use the wallet seed or keychain. /// /// # Example @@ -294,16 +294,26 @@ where /// //... /// } /// ``` - pub fn accounts( &self, keychain_mask: Option<&SecretKey>, ) -> Result, Error> { - let mut w_lock = self.wallet_inst.lock(); - let w = w_lock.lc_provider()?.wallet_inst()?; + wallet_lock!(self.wallet_inst, w); // Test keychain mask, to keep API consistent let _ = w.keychain(keychain_mask)?; - owner::accounts(w) + owner::accounts(w, None) + } + + /// Returns accounts with balances from local wallet data, without refreshing from the node. + /// `minimum_confirmations` is the minimum confirmations required for spendable outputs. + pub fn accounts_info( + &self, + keychain_mask: Option<&SecretKey>, + minimum_confirmations: u64, + ) -> Result, Error> { + wallet_lock!(self.wallet_inst, w); + let _ = w.keychain(keychain_mask)?; + owner::accounts(w, Some(minimum_confirmations)) } /// Creates a new 'account', which is a mapping of a user-specified @@ -312,8 +322,8 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. - /// * `label` - A human readable label to which to map the new BIP32 Path + /// being used. + /// * `label` - A human-readable label to which to map the new BIP32 Path /// /// # Returns /// * Result Containing: @@ -322,13 +332,13 @@ where /// /// # Remarks /// - /// * Wallets should be initialised with the 'default' path mapped to `m/0/0` + /// * Wallets should be initialized with the 'default' path mapped to `m/0/0` /// * Each call to this function will increment the first element of the path - /// so the first call will create an account at `m/1/0` and the second at - /// `m/2/0` etc. . . + /// so the first call will create an account at `m/1/0` and the second at + /// `m/2/0` etc. /// * The account path is used throughout as the parent key for most key-derivation - /// operations. See [`set_active_account`](struct.Owner.html#method.set_active_account) for - /// further details. + /// operations. See [`set_active_account`](struct.Owner.html#method.set_active_account) for + /// further details. /// /// * This function does not need to use the root wallet seed or keychain. /// @@ -345,7 +355,6 @@ where /// //... /// } /// ``` - pub fn create_account_path( &self, keychain_mask: Option<&SecretKey>, @@ -357,13 +366,14 @@ where } /// Sets the wallet's currently active account. This sets the - /// BIP32 parent path used for most key-derivation operations. + /// BIP32 parent path used for most key-derivation operations + /// persistently between wallet restarts. /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. - /// * `label` - The human readable label for the account. Accounts can be retrieved via - /// the [`account`](struct.Owner.html#method.accounts) method + /// being used. + /// * `label` - The human-readable label for the account. Accounts can be retrieved via + /// the [`account`](struct.Owner.html#method.accounts) method /// /// # Returns /// * Result Containing: @@ -373,9 +383,9 @@ where /// # Remarks /// /// * Wallet parent paths are 2 path elements long, e.g. `m/0/0` is the path - /// labelled 'default'. Keys derived from this parent path are 3 elements long, - /// e.g. the secret keys derived from the `m/0/0` path will be at paths `m/0/0/0`, - /// `m/0/0/1` etc... + /// labeled 'default'. Keys derived from this parent path are 3 elements long, + /// e.g. the secret keys derived from the `m/0/0` path will be at paths `m/0/0/0`, + /// `m/0/0/1` etc... /// /// * This function does not need to use the root wallet seed or keychain. /// @@ -393,7 +403,6 @@ where /// let result2 = api_owner.set_active_account(None, "account1"); /// } /// ``` - pub fn set_active_account( &self, keychain_mask: Option<&SecretKey>, @@ -403,37 +412,37 @@ where let w = w_lock.lc_provider()?.wallet_inst()?; // Test keychain mask, to keep API consistent let _ = w.keychain(keychain_mask)?; - owner::set_active_account(w, label) + owner::set_active_account(w, keychain_mask, label) } /// Returns a list of outputs from the active account in the wallet. /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `include_spent` - If `true`, outputs that have been marked as 'spent' - /// in the wallet will be returned. If `false`, spent outputs will omitted - /// from the results. + /// in the wallet will be returned. If `false`, spent outputs will omitted + /// from the results. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain output information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain output information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `tx_id` - If `Some(i)`, only return the outputs associated with - /// the transaction log entry of id `i`. + /// the transaction log entry of id `i`. /// /// # Returns /// * `(bool, Vec)` - A tuple: /// * The first `bool` element indicates whether the data was successfully - /// refreshed from the node (note this may be false even if the `refresh_from_node` - /// argument was set to `true`. + /// refreshed from the node (note this may be false even if the `refresh_from_node` + /// argument was set to `true`. /// * The second element contains a vector of - /// [OutputCommitMapping](../grin_wallet_libwallet/types/struct.OutputCommitMapping.html) - /// of which each element is a mapping between the wallet's internal - /// [OutputData](../grin_wallet_libwallet/types/struct.Output.html) - /// and the Output commitment as identified in the chain's UTXO set + /// [OutputCommitMapping](../grin_wallet_libwallet/types/struct.OutputCommitMapping.html) + /// of which each element is a mapping between the wallet's internal + /// [OutputData](../grin_wallet_libwallet/types/struct.Output.html) + /// and the Output commitment as identified in the chain's UTXO set /// /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. @@ -451,7 +460,6 @@ where /// //... /// } /// ``` - pub fn retrieve_outputs( &self, keychain_mask: Option<&SecretKey>, @@ -481,22 +489,22 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain transaction information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain transaction information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `minimum_confirmations` - The minimum number of confirmations an output - /// should have before it's included in the 'amount_currently_spendable' total + /// should have before it's included in the 'amount_currently_spendable' total /// /// # Returns /// * `(bool, u64, u64, u32)` - A tuple: /// * The first `bool` element indicates whether the data was successfully - /// refreshed from the node (note this may be false even if the `refresh_from_node` - /// argument was set to `true`). + /// refreshed from the node (note this may be false even if the `refresh_from_node` + /// argument was set to `true`). /// * The second `u64` is amount to send. /// * The third element is fee /// * The fourth is maximum input count @@ -515,7 +523,6 @@ where /// //... /// } /// ``` - pub fn estimate_max_sendable( &self, keychain_mask: Option<&SecretKey>, @@ -545,29 +552,29 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain transaction information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain transaction information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `tx_id` - If `Some(i)`, only return the transactions associated with - /// the transaction log entry of id `i`. + /// the transaction log entry of id `i`. /// * `tx_slate_id` - If `Some(uuid)`, only return transactions associated with - /// the given [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html) uuid. + /// the given [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html) uuid. /// * `tx_query_args` - If provided, use advanced query arguments as documented in - /// (../grin_wallet_libwallet/types.struct.RetrieveTxQueryArgs.html). If either - /// `tx_id` or `tx_slate_id` is provided in the same call, this argument is ignored + /// (../grin_wallet_libwallet/types.struct.RetrieveTxQueryArgs.html). If either + /// `tx_id` or `tx_slate_id` is provided in the same call, this argument is ignored /// /// # Returns /// * `(bool, Vec, @@ -630,22 +636,22 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain transaction information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain transaction information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `minimum_confirmations` - The minimum number of confirmations an output - /// should have before it's included in the 'amount_currently_spendable' total + /// should have before it's included in the 'amount_currently_spendable' total /// /// # Returns /// * (`bool`, [`WalletInfo`](../grin_wallet_libwallet/types/struct.WalletInfo.html)) - A tuple: /// * The first `bool` element indicates whether the data was successfully - /// refreshed from the node (note this may be false even if the `refresh_from_node` - /// argument was set to `true`. + /// refreshed from the node (note this may be false even if the `refresh_from_node` + /// argument was set to `true`. /// * The second element contains the Summary [`WalletInfo`](../grin_wallet_libwallet/types/struct.WalletInfo.html) /// /// # Example @@ -664,7 +670,6 @@ where /// //... /// } /// ``` - pub fn retrieve_summary_info( &self, keychain_mask: Option<&SecretKey>, @@ -713,9 +718,9 @@ where /// is confirmed. This method also returns a function that will perform that locking, and it is /// up to the caller to decide the best time to call the lock function /// (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) method). - /// If the exchange method is intended to be synchronous (such as via a direct http call,) + /// If the exchange method is intended to be synchronous (such as via a direct http call), /// then the lock call can wait until the response is confirmed. If it is asynchronous, (such - /// as via file transfer,) the lock call should happen immediately (before the file is sent + /// as via file transfer), the lock call should happen immediately (before the file is sent /// to the recipient). /// /// If the `send_args` [`InitTxSendArgs`](../grin_wallet_libwallet/types/struct.InitTxSendArgs.html), @@ -723,30 +728,34 @@ where /// function will attempt to send the slate back to the sender using the slatepack sync /// send (TOR). If providing this argument, check the `state` field of the slate to see if the /// sync_send was successful (it should be S2 if the sync sent successfully). It will also post - /// the transction if the `post_tx` field is set. + /// the transaction if the `post_tx` field is set. /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `args` - [`InitTxArgs`](../grin_wallet_libwallet/types/struct.InitTxArgs.html), - /// transaction initialization arguments. See struct documentation for further detail. + /// transaction initialization arguments. See struct documentation for further detail. /// /// # Returns /// * a result containing: /// * The transaction [Slate](../grin_wallet_libwallet/slate/struct.Slate.html), - /// which can be forwarded to the recieving party by any means. Once the caller is relatively - /// certain that the transaction has been sent to the recipient, the associated wallet - /// transaction outputs should be locked via a call to - /// [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs). This must be called before calling - /// [`finalize_tx`](struct.Owner.html#method.finalize_tx). + /// which can be forwarded to the receiving party by any means. With normal locking, an + /// attempted Tor send already locks the outputs, even if sending fails. Do not call + /// [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) again when forwarding manually. + /// If sending was not requested or was skipped, lock the outputs before forwarding the slate. + /// With late locking, outputs are locked during finalization instead. + /// If `skip_tor` is omitted, `skip_send_attempt` in the Tor config decides whether to send. + /// With normal locking, a returned S1 slate alone does not tell you whether outputs are locked. + /// Set `skip_tor` explicitly or check [`retrieve_txs`](struct.Owner.html#method.retrieve_txs) + /// for the slate ID before locking manually. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Remarks /// /// * This method requires an active connection to a node, and will fail with error if a node - /// cannot be contacted to refresh output statuses. + /// cannot be contacted to refresh output statuses. /// * This method will store a partially completed transaction in the wallet's transaction log, - /// which will be updated on the corresponding call to [`finalize_tx`](struct.Owner.html#method.finalize_tx). + /// which will be updated on the corresponding call to [`finalize_tx`](struct.Owner.html#method.finalize_tx). /// /// # Example /// Set up as in [new](struct.Owner.html#method.new) method above. @@ -772,15 +781,14 @@ where /// if let Ok(slate) = result { /// // Send slate somehow /// // ... - /// // Lock our outputs if we're happy the slate was (or is being) sent + /// // Lock outputs for manual sending without late locking /// api_owner.tx_lock_outputs(None, &slate); /// } /// ``` - pub fn init_send_tx( &self, keychain_mask: Option<&SecretKey>, - args: InitTxArgs, + mut args: InitTxArgs, ) -> Result { let send_args = args.send_args.clone(); let dest = match send_args.as_ref() { @@ -789,32 +797,65 @@ where } _ => None, }; - 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::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; - (slate, tor_config) + + let tor_config = send_args + .as_ref() + .map(|_| crate::tor_config::load(&self.config_path())) + .transpose()?; + + let init_send_tx = |w: &mut WalletBackend, args: &mut InitTxArgs| { + if args.address_index.is_none() && args.estimate_only != Some(true) { + let parent_key_id = match &args.src_acct_name { + Some(name) => w.get_acct_path(name.clone())?.map(|account| account.path), + None => None, + } + .unwrap_or_else(|| w.parent_key_id()); + args.address_index = Some(w.next_tx_slatepack_address_index(&parent_key_id)?); + } + owner::init_send_tx(w, keychain_mask, args.clone(), self.doctest_mode) }; + // Helper functionality. If send arguments exist, attempt to send sync and // finalize match send_args { Some(sa) => { - 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 || dest.is_none() { - return Ok(slate); - } - let res = - try_slatepack_sync_workflow(&slate, &dest.unwrap(), Some(tc), None, false); + let slate = { + wallet_lock!(self.wallet_inst, w); + let late_lock = args.late_lock.unwrap_or(false); + let slate = init_send_tx(w, &mut args)?; + let tc = tor_config.as_ref().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 || dest.is_none() { + return Ok(slate); + } + if !late_lock { + owner::tx_lock_outputs(w, keychain_mask, &slate)?; + } + + slate + }; + let res = try_slatepack_sync_workflow( + &slate, + dest.as_ref().unwrap(), + tor_config, + None, + false, + ); match res { Ok(s) => { - self.tx_lock_outputs(keychain_mask, &s)?; + // Output slatepack message to file. + match output_slatepack_file( + self, + keychain_mask, + &s, + dest, + args.address_index, + ) { + Ok(_) => {} + Err(e) => error!("Error on saving output slatepack message: {}", e), + } let ret_slate = self.finalize_tx(keychain_mask, &s)?; if sa.post_tx { let result = self.post_tx(keychain_mask, &ret_slate, sa.fluff); @@ -838,7 +879,11 @@ where } } } - None => Ok(slate), + None => { + wallet_lock!(self.wallet_inst, w); + let slate = init_send_tx(w, &mut args)?; + Ok(slate) + } } } @@ -850,13 +895,13 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `args` - [`IssueInvoiceTxArgs`](../grin_wallet_libwallet/types/struct.IssueInvoiceTxArgs.html), - /// invoice transaction initialization arguments. See struct documentation for further detail. + /// invoice transaction initialization arguments. See struct documentation for further detail. /// /// # Returns /// * ``Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html))` if successful, - /// containing the updated slate. + /// containing the updated slate. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -1007,15 +1052,15 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). The - /// payer should have filled in round 1 and 2. + /// payer should have filled in round 1 and 2. /// * `args` - [`InitTxArgs`](../grin_wallet_libwallet/types/struct.InitTxArgs.html), - /// transaction initialization arguments. See struct documentation for further detail. + /// transaction initialization arguments. See struct documentation for further detail. /// /// # Returns /// * ``Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html))` if successful, - /// containing the updated slate. + /// containing the updated slate. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -1026,7 +1071,7 @@ where /// 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 + /// // The slate has been received from the invoicer, somehow /// # let slate = Slate::blank(2, true); /// let args = InitTxArgs { /// src_acct_name: None, @@ -1045,7 +1090,6 @@ where /// // . . . /// } /// ``` - pub fn process_invoice_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1059,19 +1103,17 @@ where } _ => None, }; - let (slate, tor_config) = { + let tor_config = send_args + .as_ref() + .map(|_| crate::tor_config::load(&self.config_path())) + .transpose()?; + let slate = { 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) + owner::process_invoice_tx(w, keychain_mask, slate, args.clone(), self.doctest_mode)? }; // Helper functionality. If send arguments exist, attempt to send - match send_args { + match send_args.as_ref() { Some(sa) => { let tc = tor_config.ok_or_else(|| { Error::TorConfig("Tor config was not loaded with send arguments".into()) @@ -1095,7 +1137,13 @@ where } } // Output slatepack message to file. - match output_slatepack_file(&self, keychain_mask, &s, Some(dest)) { + match output_slatepack_file( + self, + keychain_mask, + &s, + Some(dest), + args.address_index, + ) { Ok(_) => {} Err(e) => error!("Error on saving output slatepack message: {}", e), } @@ -1126,12 +1174,12 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). All /// * `participant_id` - The participant id, generally 0 for the party putting in funds, 1 for the - /// party receiving. - /// elements in the `input` vector of the `tx` field that are found in the wallet's currently - /// active account will be set to status `Locked` + /// party receiving. + /// elements in the `input` vector of the `tx` field that are found in the wallet's currently + /// active account will be set to status `Locked` /// /// # Returns /// * Ok(()) if successful @@ -1164,7 +1212,6 @@ where /// api_owner.tx_lock_outputs(None, &slate); /// } /// ``` - pub fn tx_lock_outputs( &self, keychain_mask: Option<&SecretKey>, @@ -1189,14 +1236,14 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). All - /// participants must have filled in both rounds, and the sender should have locked their - /// outputs (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) function). + /// participants must have filled in both rounds, and the sender should have locked their + /// outputs (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) function). /// /// # Returns /// * ``Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html))` if successful, - /// containing the new finalized slate. + /// containing the new finalized slate. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -1230,7 +1277,6 @@ where /// let res = api_owner.finalize_tx(None, &slate); /// } /// ``` - pub fn finalize_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1246,13 +1292,13 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `tx` - A completed [`Transaction`](../grin_core/core/transaction/struct.Transaction.html), - /// typically the `tx` field in the transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). + /// typically the `tx` field in the transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). /// * `fluff` - Instruct the node whether to use the Dandelion protocol when posting the - /// transaction. If `true`, the node should skip the Dandelion phase and broadcast the - /// transaction to all peers immediately. If `false`, the node will follow dandelion logic and - /// initiate the stem phase. + /// transaction. If `true`, the node should skip the Dandelion phase and broadcast the + /// transaction to all peers immediately. If `false`, the node will follow dandelion logic and + /// initiate the stem phase. /// /// # Returns /// * `Ok(())` if successful @@ -1290,7 +1336,6 @@ where /// let res = api_owner.post_tx(None, &slate, true); /// } /// ``` - pub fn post_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1310,18 +1355,18 @@ where /// Cancels a transaction. This entails: /// * Setting the transaction status to either `TxSentCancelled` or `TxReceivedCancelled` /// * Deleting all change outputs or recipient outputs associated with the transaction - /// * Setting the status of all assocatied inputs from `Locked` to `Spent` so they can be - /// used in new transactions. + /// * Setting the status of all associated inputs from `Locked` to `Spent` so they can be + /// used in new transactions. /// - /// Transactions can be cancelled by transaction log id or slate id (call with either set to + /// Transactions can be canceled by transaction log id or slate id (call with either set to /// Some, not both) /// /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `tx_id` - If present, cancel by the [`TxLogEntry`](../grin_wallet_libwallet/types/struct.TxLogEntry.html) id - /// for the transaction. + /// for the transaction. /// /// * `tx_slate_id` - If present, cancel by the Slate id. /// @@ -1360,7 +1405,6 @@ where /// let res = api_owner.cancel_tx(None, None, Some(slate.id.clone())); /// } /// ``` - pub fn cancel_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1377,6 +1421,7 @@ where &tx, tx_id, tx_slate_id, + true, ) } @@ -1387,16 +1432,16 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `tx_id` - The id of the transaction in the wallet's Transaction Log. Either this or - /// `slate_id` must be provided. + /// `slate_id` must be provided. /// * `slate_id` - The UUID of the Transaction Slate to find. Either this or `tx_id` must be - /// provided + /// provided /// /// # Returns /// * Ok(Some([Slate](../grin_wallet_libwallet/slate/struct.Slate.html)) containing the stored - /// transaction, if successful. Note that this Slate will not contain all of the fields used by - /// the original Slate that resulted in the transaction. + /// transaction, if successful. Note that this Slate will not contain all the fields used by + /// the original Slate that resulted in the transaction. /// * Ok(None) if the stored Transaction isn't found. /// * [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// @@ -1418,7 +1463,6 @@ where /// //... /// } /// ``` - pub fn get_stored_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1433,17 +1477,16 @@ where } /// Return the rewind hash of the wallet. - /// The rewind hash when shared, help third-party to retrieve informations (outputs, balance, ...) that belongs to this wallet. + /// The rewind hash when shared, help third-party to retrieve information (outputs, balance, ...) that belongs to this wallet. /// /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// /// # Returns /// * `Ok(String)` if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. - /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. /// ``` @@ -1461,14 +1504,13 @@ where /// // ... /// } /// ``` - pub fn get_rewind_hash(&self, keychain_mask: Option<&SecretKey>) -> Result { owner::get_rewind_hash(self.wallet_inst.clone(), keychain_mask) } /// Scans the entire UTXO set from the node, identify which outputs belong to the given rewind hash view wallet. /// - /// This function can be used to retrieve outputs informations (outputs, balance, ...) from a rewind hash view wallet. + /// This function can be used to retrieve outputs information (outputs, balance, ...) from a rewind hash view wallet. /// /// This operation scans the entire chain, and is expected to be time intensive. It is imperative /// that no other processes should be trying to use the wallet at the same time this function is @@ -1478,12 +1520,11 @@ where /// /// * `rewind_hash` - Rewind hash of a wallet, used to retrieve the output of a third-party wallet. /// * `start_height` - If provided, the height of the first block from which to start scanning. - /// The scan will start from block 1 if this is not provided. + /// The scan will start from block 1 if this is not provided. /// /// # Returns /// * `Ok(ViewWallet)` if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. - /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. /// ``` @@ -1501,7 +1542,6 @@ where /// // ... /// } /// ``` - pub fn scan_rewind_hash( &self, rewind_hash: String, @@ -1518,7 +1558,7 @@ where /// update the wallet state to be consistent with what's currently in the UTXO set. /// /// This function can be used to repair wallet state, particularly by restoring outputs that may - /// be missing if the wallet owner has cancelled transactions locally that were then successfully + /// be missing if the wallet owner has canceled transactions locally that were then successfully /// posted to the chain. /// /// This operation scans the entire chain, and is expected to be time intensive. It is imperative @@ -1531,23 +1571,22 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `start_height` - If provided, the height of the first block from which to start scanning. - /// The scan will start from block 1 if this is not provided. + /// The scan will start from block 1 if this is not provided. /// * `delete_unconfirmed` - if `false`, the scan process will be non-destructive, and - /// mostly limited to restoring missing outputs. It will leave unconfirmed transaction logs entries - /// and unconfirmed outputs intact. If `true`, the process will unlock all locked outputs, - /// restore all missing outputs, and mark any outputs that have been marked 'Spent' but are still - /// in the UTXO set as 'Unspent' (as can happen during a fork). It will also attempt to cancel any - /// transaction log entries associated with any locked outputs or outputs incorrectly marked 'Spent'. - /// Note this completely removes all outstanding transactions, so users should be very aware what - /// will happen if this flag is set. Note that if transactions/outputs are removed that later - /// confirm on the chain, another call to this function will restore them. + /// mostly limited to restoring missing outputs. It will leave unconfirmed transaction logs entries + /// and unconfirmed outputs intact. If `true`, the process will unlock all locked outputs, + /// restore all missing outputs, and mark any outputs that have been marked 'Spent' but are still + /// in the UTXO set as 'Unspent' (as can happen during a fork). It will also attempt to cancel any + /// transaction log entries associated with any locked outputs or outputs incorrectly marked 'Spent'. + /// Note this completely removes all outstanding transactions, so users should be very aware what + /// will happen if this flag is set. Note that if transactions/outputs are removed that later + /// confirm on the chain, another call to this function will restore them. /// /// # Returns /// * `Ok(())` if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. - /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. /// ``` @@ -1565,7 +1604,6 @@ where /// // ... /// } /// ``` - pub fn scan( &self, keychain_mask: Option<&SecretKey>, @@ -1587,10 +1625,10 @@ where /// Retrieves the last known height known by the wallet. This is determined as follows: /// * If the wallet can successfully contact its configured node, the reported node - /// height is returned, and the `updated_from_node` field in the response is `true` + /// height is returned, and the `updated_from_node` field in the response is `true` /// * If the wallet cannot contact the node, this function returns the maximum height - /// of all outputs contained within the wallet, and the `updated_from_node` fields - /// in the response is set to false. + /// of all outputs contained within the wallet, and the `updated_from_node` fields + /// in the response is set to false. /// /// Clients should generally ensure the `updated_from_node` field is returned as /// `true` before assuming the height for any operation. @@ -1598,12 +1636,12 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// /// # Returns /// * Ok with a [`NodeHeightResult`](../grin_wallet_libwallet/types/struct.NodeHeightResult.html) - /// if successful. If the height result was obtained from the configured node, - /// `updated_from_node` will be set to `true` + /// if successful. If the height result was obtained from the configured node, + /// `updated_from_node` will be set to `true` /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -1622,7 +1660,6 @@ where /// //... /// } /// ``` - pub fn node_height( &self, keychain_mask: Option<&SecretKey>, @@ -1652,7 +1689,7 @@ where /// The top level directory defaults to (in order of precedence): /// /// 1) The current directory, from which `grin-wallet` or the main process was run, if it - /// contains a `grin-wallet.toml` file. + /// contains a `grin-wallet.toml` file. /// 2) ~/.grin// otherwise /// /// # Arguments @@ -1660,7 +1697,7 @@ where /// * None /// /// # Returns - /// * Ok with a String value representing the full path to the top level wallet dierctory + /// * Ok with a String value representing the full path to the top level wallet directory /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -1676,7 +1713,6 @@ where /// //... /// } /// ``` - pub fn get_top_level_directory(&self) -> Result { let mut w_lock = self.wallet_inst.lock(); let lc = w_lock.lc_provider()?; @@ -1694,12 +1730,12 @@ where /// 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. + /// Open the wallet again afterward to load its database from the new location. /// /// # Arguments /// /// * `dir`: The new top-level directory path (either relative to current directory or - /// absolute. + /// absolute. /// /// # Returns /// * Ok if successful @@ -1726,7 +1762,6 @@ where /// //... /// } /// ``` - pub fn set_top_level_directory(&self, dir: &str) -> Result<(), Error> { if self.updater_running.load(Ordering::Relaxed) { return Err(Error::Lifecycle( @@ -1794,7 +1829,6 @@ where /// //... /// } /// ``` - pub fn create_config( &self, chain_type: &global::ChainTypes, @@ -1827,9 +1861,11 @@ where /// /// * `name`: Reserved for future use, use `None` for the time being. /// * `mnemonic`: If present, restore the wallet seed from the given mnemonic instead of creating - /// a new random seed. - /// * `mnemonic_length`: Desired length of mnemonic in bytes (16 or 32, either 12 or 24 words). - /// Use 0 if mnemonic isn't being used. + /// a new random seed. + /// * `mnemonic_length`: Entropy length in bytes: 16, 20, 24, 28 or 32 + /// (12, 15, 18, 21 or 24 words). Ignored when `mnemonic` is provided. + /// For a new random seed, 0 is also accepted and defaults to 32 bytes. + /// All other values return an error. /// * `password`: The password used to encrypt/decrypt the `wallet.seed` file /// /// # Returns @@ -1868,7 +1904,6 @@ where /// //... /// } /// ``` - pub fn create_wallet( &self, name: Option<&str>, @@ -1890,15 +1925,15 @@ where /// `Opens` a wallet, populating the internal keychain with the encrypted seed, and optionally /// returning a `keychain_mask` token to the caller to provide in all future calls. /// If using a mask, the seed will be stored in-memory XORed against the `keychain_mask`, and - /// will not be useable if the mask is not provided. + /// will not be usable if the mask is not provided. /// /// # Arguments /// /// * `name`: Reserved for future use, use `None` for the time being. /// * `password`: The password to use to open the wallet - /// a new random seed. + /// a new random seed. /// * `use_mask`: Whether to create and return a mask which much be provided in all future - /// API calls. + /// API calls. /// /// # Returns /// * Ok if successful @@ -1927,7 +1962,7 @@ where /// // Create configuration /// let result = api_owner.create_config(&ChainTypes::Mainnet, None, None, None); /// - /// // create new wallet wirh random seed + /// // create new wallet with random seed /// let pw = ZeroingString::from("my_password"); /// let _ = api_owner.create_wallet(None, None, 0, pw.clone()); /// @@ -1938,7 +1973,6 @@ where /// let mask = m; /// } /// ``` - pub fn open_wallet( &self, name: Option<&str>, @@ -1986,7 +2020,6 @@ where /// // ... /// } /// ``` - pub fn close_wallet(&self, name: Option<&str>) -> Result<(), Error> { let mut w_lock = self.wallet_inst.lock(); let lc = w_lock.lc_provider()?; @@ -2003,7 +2036,7 @@ where /// * `password`: The password used to encrypt the seed file. /// /// # Returns - /// * Ok(BIP-39 mneminc) if successful + /// * Ok(BIP-39 mnemonic) if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -2110,7 +2143,6 @@ where /// // ... /// } /// ``` - pub fn delete_wallet(&self, name: Option<&str>) -> Result<(), Error> { let mut w_lock = self.wallet_inst.lock(); let lc = w_lock.lc_provider()?; @@ -2124,14 +2156,14 @@ where /// The updater process is as follows: /// /// * Reconcile the wallet outputs against the node's current UTXO set, confirming - /// transactions if needs be. + /// transactions if needs be. /// * Look up transactions by kernel in cases where it's necessary (for instance, when - /// there are no change outputs for a transaction and transaction status can't be - /// inferred from the output state. + /// there are no change outputs for a transaction and transaction status can't be + /// inferred from the output state. /// * Incrementally perform a scan of the UTXO set, correcting outputs and transactions - /// where their local state differs from what's on-chain. The wallet stores the last - /// position scanned, and will scan back 100 blocks worth of UTXOs on each update, to - /// correct any differences due to forks or otherwise. + /// where their local state differs from what's on-chain. The wallet stores the last + /// position scanned, and will scan back 100 blocks worth of UTXOs on each update, to + /// correct any differences due to forks or otherwise. /// /// Note that an update process can take a long time, particularly when the entire /// UTXO set is being scanned for correctness. The wallet status can be determined by @@ -2140,10 +2172,10 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `frequency`: The frequency at which to call the update process. Note this is - /// time elapsed since the last successful update process. If calling via the JSON-RPC - /// api, this represents milliseconds. + /// time elapsed since the last successful update process. If calling via the JSON-RPC + /// api, this represents milliseconds. /// /// # Returns /// * Ok if successful @@ -2167,7 +2199,6 @@ where /// // ... /// } /// ``` - pub fn start_updater( &self, keychain_mask: Option<&SecretKey>, @@ -2178,10 +2209,7 @@ where let t = self.status_tx.lock(); t.clone() }; - let keychain_mask = match keychain_mask { - Some(m) => Some(m.clone()), - None => None, - }; + let keychain_mask = keychain_mask.cloned(); let _ = thread::Builder::new() .name("wallet-updater".to_string()) .spawn(move || { @@ -2224,7 +2252,6 @@ where /// /// let res = api_owner.stop_updater(); /// ``` - pub fn stop_updater(&self) -> Result<(), Error> { self.updater_running.store(false, Ordering::Relaxed); Ok(()) @@ -2267,7 +2294,6 @@ where /// } /// /// ``` - pub fn get_updater_messages(&self, count: usize) -> Result, Error> { let mut q = self.updater_messages.lock(); let index = q.len().saturating_sub(count); @@ -2306,7 +2332,7 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// * `derivation_index` - The index along the derivation path to retrieve an address for + /// * `derivation_index` - The index along the derivation path to retrieve an address for, should be not higher than 2^31 - 1 /// /// # Returns /// * Ok with a SlatepackAddress representing the address @@ -2318,24 +2344,24 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// /// // Set up as above /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// - /// let res = api_owner.get_slatepack_address(None, 0); + /// let res = api_owner.get_slatepack_address(None, SlatepackAddressIndex(0)); /// /// if let Ok(_) = res { /// // ... /// } /// /// ``` - pub fn get_slatepack_address( &self, keychain_mask: Option<&SecretKey>, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result { owner::get_slatepack_address(self.wallet_inst.clone(), keychain_mask, derivation_index) } @@ -2345,9 +2371,8 @@ where /// /// # Arguments /// - /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// * `derivation_index` - The index along the derivation path to for which to retrieve the secret key - /// + /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using + /// * `derivation_index` - The index along the derivation path to for which to retrieve the secret key, should be not higher than 2^31 - 1 /// # Returns /// * Ok with an ed25519_dalek::SecretKey if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. @@ -2358,13 +2383,14 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// /// // Set up as above /// # 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); + /// let res = api_owner.get_slatepack_secret_key(None, SlatepackAddressIndex(0)); /// /// if let Ok(_) = res { /// // ... @@ -2374,7 +2400,7 @@ where pub fn get_slatepack_secret_key( &self, keychain_mask: Option<&SecretKey>, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result { owner::get_slatepack_secret_key(self.wallet_inst.clone(), keychain_mask, derivation_index) } @@ -2385,9 +2411,9 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// * `sender_index` - If Some(n), the index along the derivation path to include as the sender + /// * `sender_index` - If Some(n), the index along the derivation path to include as the sender, should be not higher than 2^31 - 1 /// * `recipients` - Optional recipients for which to encrypt the slatepack's payload (i.e. the - /// slate). The sender is also able to decrypt it. If empty, the payload remains unencrypted + /// slate). The sender is also able to decrypt it. If empty, the payload remains unencrypted /// /// # Returns /// * Ok with a String representing an armored slatepack if successful @@ -2399,6 +2425,7 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// @@ -2424,18 +2451,17 @@ where /// let slatepack = api_owner.create_slatepack_message( /// None, /// &slate, - /// Some(0), + /// Some(SlatepackAddressIndex(0)), /// vec![], /// ); /// } /// /// ``` - pub fn create_slatepack_message( &self, keychain_mask: Option<&SecretKey>, slate: &Slate, - sender_index: Option, + sender_index: Option, recipients: Vec, ) -> Result { owner::create_slatepack_message( @@ -2454,9 +2480,8 @@ where /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// * `slatepack` - A string representing an armored slatepack - /// * `secret_indices` - Indices along this wallet's deriviation path with which to attempt - /// decryption. This function will attempt to use secret keys at each index along this path - /// to attempt to decrypt the payload, returning an error if none of the keys match. + /// * `secret_indices` - Indices along this wallet's derivation path with which to attempt + /// decryption. This function will attempt to use secret keys at each index along this path to attempt to decrypt the payload, returning an error if none of the keys match. Should be not higher than 2^31 - 1 each. /// /// # Returns /// * Ok with a [Slate](../grin_wallet_libwallet/slate/struct.Slate.html) if successful @@ -2468,6 +2493,7 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// @@ -2478,15 +2504,14 @@ where /// let res = api_owner.slate_from_slatepack_message( /// None, /// slatepack_string, - /// vec![0, 1, 2], + /// vec![SlatepackAddressIndex(0), SlatepackAddressIndex(1), SlatepackAddressIndex(2)], /// ); /// ``` - pub fn slate_from_slatepack_message( &self, keychain_mask: Option<&SecretKey>, slatepack: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result { owner::slate_from_slatepack_message( self.wallet_inst.clone(), @@ -2497,16 +2522,15 @@ where } /// Decode an armored slatepack, returning a Slatepack object that can be - /// viewed, manipulated, output as json, etc. The resulting slatepack will be + /// viewed, manipulated, output as JSON, etc. The resulting slatepack will be /// decrypted by this wallet if possible /// /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using /// * `slatepack` - A string representing an armored slatepack - /// * `secret_indices` - Indices along this wallet's deriviation path with which to attempt - /// decryption. If this wallet can't decrypt this slatepack, the payload of the returned - /// Slatepack will remain encrypted. + /// * `secret_indices` - Indices along this wallet's derivation path with which to attempt + /// decryption. If this wallet can't decrypt this slatepack, the payload of the returned Slatepack will remain encrypted. Should be not higher than 2^31 - 1 each. /// /// # Returns /// * Ok with a [Slatepack](../grin_wallet_libwallet/slatepack/types/struct.Slatepack.html) if successful @@ -2518,6 +2542,7 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// @@ -2528,16 +2553,15 @@ where /// let res = api_owner.decode_slatepack_message( /// None, /// slatepack_string, - /// vec![0, 1, 2], + /// vec![SlatepackAddressIndex(0), SlatepackAddressIndex(1), SlatepackAddressIndex(2)], /// ); /// /// ``` - pub fn decode_slatepack_message( &self, keychain_mask: Option<&SecretKey>, slatepack: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result { owner::decode_slatepack_message( self.wallet_inst.clone(), @@ -2558,22 +2582,22 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain transaction information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain transaction information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `tx_id` - If `Some(i)` return the proof associated with the transaction with id `i` /// * `tx_slate_id` - If `Some(uuid)`, return the proof associated with the transaction with the - /// given `uuid` + /// given `uuid` /// /// # Returns /// * Ok([PaymentProof](../grin_wallet_libwallet/api_impl/types/struct.PaymentProof.html)) if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered - /// or the proof is not present or complete + /// or the proof is not present or complete /// /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. @@ -2592,7 +2616,6 @@ where /// //... /// } /// ``` - pub fn retrieve_payment_proof( &self, keychain_mask: Option<&SecretKey>, @@ -2650,9 +2673,9 @@ where /// * Ensuring the kernel identified by the proof's stored excess commitment exists in the kernel set /// * Reproducing the signed message `amount|kernel_commitment|sender_address` /// * Validating the proof's `recipient_sig` against the message using the recipient's - /// address as the public key and + /// address as the public key and /// * Validating the proof's `sender_sig` against the message using the senders's - /// address as the public key + /// address as the public key /// /// This function also checks whether the sender or recipient address belongs to the currently /// open wallet, and returns 2 booleans indicating whether the address belongs to the sender and @@ -2660,15 +2683,15 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `proof` A [PaymentProof](../grin_wallet_libwallet/api_impl/types/struct.PaymentProof.html)) /// /// # Returns /// * Ok((bool, bool)) if the proof is valid. The first boolean indicates whether the sender - /// address belongs to this wallet, the second whether the recipient address belongs to this - /// wallet + /// address belongs to this wallet, the second whether the recipient address belongs to this + /// wallet /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered - /// or the proof is not present or complete + /// or the proof is not present or complete /// /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. @@ -2692,7 +2715,6 @@ where /// } /// } /// ``` - pub fn verify_payment_proof( &self, keychain_mask: Option<&SecretKey>, @@ -2715,21 +2737,22 @@ where // MWIXNET - /// Creates an mwixnet request [SwapReq](../grin_wallet_libwallet/api_impl/types/struct.SwapReq.html) + /// Creates a mwixnet request [SwapReq](grin_wallet_libwallet::mwixnet::SwapReq) /// from a given output commitment under this wallet's control. /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. - /// * `params` - A [MixnetReqCreationParams](../grin_wallet_libwallet/api_impl/types/struct.MixnetReqCreationParams.html) - /// struct containing the parameters for the request, which include: - /// `server_keys` - The public keys of the servers participating in the mixnet (each encoded internally as a `SecretKey`) - /// `fee_per_hop` - The fee to be paid to each server for each hop in the mixnet + /// being used. + /// * `params` - A [MixnetReqCreationParams] + /// struct containing the parameters for the request, which include: + /// `server_keys` - Published X25519 onion keys in route order, not Ed25519 identity keys + /// or private keys + /// `fee_per_hop` - Optional fee per hop with the swap minimum as default /// * `commitment` - The commitment of the output to be mixed /// * `lock_output` - Whether to lock the referenced output after creating the request /// /// # Returns - /// * Ok([SwapReq](../grin_wallet_libwallet/api_impl/types/struct.SwapReq.html)) if successful + /// * Ok([MwixnetReqCreationResult](../grin_wallet_libwallet/mwixnet/struct.MwixnetReqCreationResult.html)) if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered /// /// # Example @@ -2740,8 +2763,10 @@ where /// 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 - /// fee_per_hop: 100, + /// server_keys: vec![libwallet::mwixnet::MwixnetServerPublicKey::from_hex( + /// "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + /// ).unwrap()], + /// fee_per_hop: None, /// }; /// /// let commitment = Commitment::from_vec(vec![0; 32]); @@ -2754,20 +2779,18 @@ where /// lock_output, /// ); /// - /// if let Ok(req) = result { + /// if let Ok(result) = result { /// //... /// } /// ``` - pub fn create_mwixnet_req( &self, keychain_mask: Option<&SecretKey>, params: &MixnetReqCreationParams, commitment: &Commitment, lock_output: bool, // use_test_rng: bool, - ) -> Result { - let mut w_lock = self.wallet_inst.lock(); - let w = w_lock.lc_provider()?.wallet_inst()?; + ) -> Result { + wallet_lock!(self.wallet_inst, w); owner::create_mwixnet_req( w, keychain_mask, @@ -2777,6 +2800,81 @@ where self.doctest_mode, ) } + + /// Sends a mwixnet request [SwapReq](grin_wallet_libwallet::mwixnet::SwapReq) + /// to provided onion server. + /// + /// # Arguments + /// * `req` - A [SwapReq] + /// struct containing the parameters for the request, which include: + /// `comsig` - [ComSignature](grin_wallet_libwallet::mwixnet::ComSignature) signature with a pedersen commitment value & blinding factors as the keys + /// `onion` - [Onion](grin_wallet_libwallet::mwixnet::Onion) encrypted route payload + /// * `server` - Onion server address + /// + /// # Returns + /// * `Ok(None)` if the server accepted the request + /// * `Ok(Some(message))` if the server rejected the request + /// * `Err` for configuration, transport, or invalid-response failures + /// + /// Leaves output locks unchanged + /// + /// # Example + /// Set up as in [`new`](struct.Owner.html#method.new) method above. + /// ``` + /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); + /// + /// 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![libwallet::mwixnet::MwixnetServerPublicKey::from_hex( + /// "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + /// ).unwrap()], + /// fee_per_hop: None, + /// }; + /// + /// let commitment = Commitment::from_vec(vec![0; 32]); + /// let lock_output = true; + /// + /// let result = api_owner.create_mwixnet_req( + /// keychain_mask, + /// ¶ms, + /// &commitment, + /// lock_output, + /// ); + /// + /// if let Ok(result) = result { + /// let server = "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion".try_into().unwrap(); + /// let result = api_owner.send_mwixnet_req(&result.request, server); + /// if let Ok(result) = result { + /// //.. + /// } + /// } + /// ``` + pub fn send_mwixnet_req( + &self, + req: &SwapReq, + server: OnionV3Address, + ) -> Result, Error> { + let url = format!("{}/v1", server.to_http_str()); + let rpc_params = serde_json::json!([req]); + let rpc_request = json_rpc::build_request("swap", &rpc_params); + let tor_config = crate::tor_config::load(&self.config_path())?; + let response = match tor_post(&tor_config, &rpc_request, &url) { + Ok(response) => response, + Err(e) => { + return Err(Error::GenericError(format!( + "Could not determine whether mwixnet accepted the request: {}", + e, + ))); + } + }; + match parse_mwixnet_response(&response).map_err(|e| { + Error::GenericError(format!("Could not confirm the mwixnet response: {}", e)) + })? { + MwixnetResponse::Accepted => Ok(None), + MwixnetResponse::Rejected(message) => Ok(Some(message)), + } + } } /// attempt to send slate synchronously with TOR @@ -2788,28 +2886,23 @@ pub fn try_slatepack_sync_workflow( send_to_finalize: bool, ) -> Result { let mut ret_slate = Slate::blank(2, false); - 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) - } - }; + let mut send_sync = |mut sender: TorSlateSender, method_str: &str| 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) + } }; - let tor_addr = OnionV3Address::try_from(dest).map_err(|_| { - Error::SlatepackAddress(format!( - "Destination {} is not a valid Onion address.", - dest - )) - })?; + let tor_addr = OnionV3Address::from(dest); let sender = match tor_sender { None => { if let Some(tc) = tor_config { @@ -2909,6 +3002,7 @@ fn output_slatepack_file( keychain_mask: Option<&SecretKey>, slate: &Slate, dest: Option, + sender_index: Option, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, @@ -2920,7 +3014,7 @@ where Some(a) => vec![a], None => vec![], }; - let message = api.create_slatepack_message(keychain_mask, &slate, Some(0), recipients)?; + let message = api.create_slatepack_message(keychain_mask, slate, sender_index, recipients)?; let tld = api.get_top_level_directory()?; // Create a directory to which files will be output. @@ -2929,7 +3023,7 @@ where 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.write_all(message.as_bytes())?; output.sync_all()?; Ok(()) } diff --git a/api/src/owner_rpc.rs b/api/src/owner_rpc.rs index 9aeff2b..76d232a 100644 --- a/api/src/owner_rpc.rs +++ b/api/src/owner_rpc.rs @@ -14,7 +14,7 @@ //! JSON-RPC Stub generation for the Owner API use grin_wallet_libwallet::RetrieveTxQueryArgs; -use libwallet::mwixnet::SwapReq; +use libwallet::mwixnet::MwixnetReqCreationResult; use uuid::Uuid; use crate::config::{TorConfig, WalletConfig}; @@ -25,18 +25,19 @@ use crate::libwallet::contract::types::{ ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI, ContractView, }; use crate::libwallet::{ - mwixnet::MixnetReqCreationParams, AcctPathMapping, Amount, BuiltOutput, Error, InitTxArgs, - IssueInvoiceTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, - SlateVersion, Slatepack, SlatepackAddress, StatusMessage, TxLogEntry, VersionedSlate, - ViewWallet, WalletInfo, WalletLCProvider, + mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey}, + AcctPathMapping, Amount, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, + NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, SlateVersion, Slatepack, + SlatepackAddress, StatusMessage, TxLogEntry, VersionedSlate, ViewWallet, WalletInfo, + WalletLCProvider, }; use crate::util::logger::LoggingConfig; use crate::util::secp::key::{PublicKey, SecretKey}; use crate::util::secp::pedersen::Commitment; use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString}; use crate::{ECDHPubkey, Ed25519SecretKey, Owner, Token}; -use easy_jsonrpc_mw; use grin_wallet_util::OnionV3Address; +use libwallet::slatepack::SlatepackAddressIndex; use rand::thread_rng; use std::convert::TryFrom; use std::path::PathBuf; @@ -51,7 +52,7 @@ use std::time::Duration; #[easy_jsonrpc_mw::rpc] pub trait OwnerRpc { /** - Networked version of [Owner::accounts](struct.Owner.html#method.accounts). + Networked version of [Owner::accounts](struct.Owner.html#method.accounts). Returns account mappings without balances. # Json rpc example @@ -75,7 +76,9 @@ pub trait OwnerRpc { "Ok": [ { "label": "default", - "path": "0200000000000000000000000000000000" + "path": "0200000000000000000000000000000000", + "info": null, + "current": true } ] }, @@ -87,6 +90,60 @@ pub trait OwnerRpc { */ fn accounts(&self, token: Token) -> Result, Error>; + /** + Networked version of [Owner::accounts_info](struct.Owner.html#method.accounts_info). Returns balances from locally stored state without refreshing from the node. + + # Json rpc example + + ``` + # grin_wallet_api::doctest_helper_json_rpc_owner_assert_response!( + # r#" + { + "jsonrpc": "2.0", + "method": "accounts_info", + "params": { + "token": "d202964900000000d302964900000000d402964900000000d502964900000000", + "minimum_confirmations": 1 + }, + "id": 1 + } + # "# + # , + # r#" + { + "jsonrpc": "2.0", + "result": { + "Ok": [ + { + "label": "default", + "path": "0200000000000000000000000000000000", + "info": { + "amount_awaiting_confirmation": "0", + "amount_awaiting_finalization": "0", + "amount_currently_spendable": "60000000000", + "amount_immature": "180000000000", + "amount_locked": "0", + "amount_reverted": "0", + "last_confirmed_height": "4", + "minimum_confirmations": "1", + "total": "240000000000" + }, + "current": true + } + ] + }, + "id": 1 + } + # "# + # , 4, false, false, false, false); + ``` + */ + fn accounts_info( + &self, + token: Token, + minimum_confirmations: u64, + ) -> Result, Error>; + /** Networked version of [Owner::create_account_path](struct.Owner.html#method.create_account_path). @@ -118,10 +175,12 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ + #[allow(clippy::ptr_arg)] fn create_account_path(&self, token: Token, label: &String) -> Result; /** Networked version of [Owner::set_active_account](struct.Owner.html#method.set_active_account). + The account selection is saved across wallet restarts # Json rpc example @@ -151,6 +210,7 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ + #[allow(clippy::ptr_arg)] fn set_active_account(&self, token: Token, label: &String) -> Result<(), Error>; /** @@ -222,7 +282,6 @@ pub trait OwnerRpc { # , 2, false, false, false, false); ``` */ - fn retrieve_outputs( &self, token: Token, @@ -268,7 +327,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn estimate_max_sendable( &self, token: Token, @@ -306,6 +364,7 @@ pub trait OwnerRpc { true, [ { + "address_index": null, "amount_credited": "60000000000", "amount_debited": "0", "confirmation_ts": "2019-01-15T16:01:26Z", @@ -327,6 +386,7 @@ pub trait OwnerRpc { "tx_type": "ConfirmedCoinbase" }, { + "address_index": null, "amount_credited": "60000000000", "amount_debited": "0", "confirmation_ts": "2019-01-15T16:01:26Z", @@ -355,7 +415,6 @@ pub trait OwnerRpc { # , 2, false, false, false, false); ``` */ - fn retrieve_txs( &self, token: Token, @@ -399,6 +458,7 @@ pub trait OwnerRpc { true, [ { + "address_index": null, "amount_credited": "60000000000", "amount_debited": "0", "confirmation_ts": "2019-01-15T16:01:26Z", @@ -420,6 +480,7 @@ pub trait OwnerRpc { "tx_type": "ConfirmedCoinbase" }, { + "address_index": null, "amount_credited": "60000000000", "amount_debited": "0", "confirmation_ts": "2019-01-15T16:01:26Z", @@ -449,7 +510,6 @@ pub trait OwnerRpc { ``` */ - fn query_txs( &self, token: Token, @@ -500,7 +560,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn retrieve_summary_info( &self, token: Token, @@ -548,7 +607,7 @@ pub trait OwnerRpc { "id": "0436430c-2b02-624c-2032-570501212b00", "proof": { "raddr": "32cdd63928854f8b2628b1dce4626ddcdf35d56cb7cfdf7d64cca5822b78d4d3", - "saddr": "32cdd63928854f8b2628b1dce4626ddcdf35d56cb7cfdf7d64cca5822b78d4d3" + "saddr": "4b2adcc4efc1d547c08ed7c9f7d987ff085f1788d62805e73c8f632e4b065039" }, "sigs": [ { @@ -565,7 +624,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn init_send_tx(&self, token: Token, args: InitTxArgs) -> Result; /** @@ -875,7 +933,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn issue_invoice_tx( &self, token: Token, @@ -959,7 +1016,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn process_invoice_tx( &self, token: Token, @@ -1164,7 +1220,6 @@ pub trait OwnerRpc { # , 5, true, true, true, false); ``` */ - fn post_tx(&self, token: Token, slate: VersionedSlate, fluff: bool) -> Result<(), Error>; /** @@ -1486,7 +1541,6 @@ pub trait OwnerRpc { ``` */ - fn init_secure_api(&self, ecdh_pubkey: ECDHPubkey) -> Result; /** @@ -1516,7 +1570,6 @@ pub trait OwnerRpc { # , 5, false, false, false, false); ``` */ - fn get_top_level_directory(&self) -> Result; /** @@ -1549,7 +1602,6 @@ pub trait OwnerRpc { # , 5, false, false, false, false); ``` */ - fn set_top_level_directory(&self, dir: String) -> Result<(), Error>; /** @@ -1652,7 +1704,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn create_wallet( &self, name: Option, @@ -1689,7 +1740,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn open_wallet(&self, name: Option, password: String) -> Result; /** @@ -1719,7 +1769,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn close_wallet(&self, name: Option) -> Result<(), Error>; /** @@ -1750,7 +1799,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn get_mnemonic(&self, name: Option, password: String) -> Result; /** @@ -1841,7 +1889,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn start_updater(&self, token: Token, frequency: u32) -> Result<(), Error>; /** @@ -1898,7 +1945,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn get_updater_messages(&self, count: u32) -> Result, Error>; /** @@ -1929,11 +1975,10 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn get_slatepack_address( &self, token: Token, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result; /** @@ -1964,11 +2009,10 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn get_slatepack_secret_key( &self, token: Token, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result; /** @@ -2014,12 +2058,11 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn create_slatepack_message( &self, token: Token, slate: VersionedSlate, - sender_index: Option, + sender_index: Option, recipients: Vec, ) -> Result; @@ -2069,12 +2112,11 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn slate_from_slatepack_message( &self, token: Token, message: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result; /** @@ -2111,12 +2153,11 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn decode_slatepack_message( &self, token: Token, message: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result; /** @@ -2148,6 +2189,7 @@ pub trait OwnerRpc { "recipient_address": "tgrin10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqq6t83r", "recipient_sig": "02868f2d2b983981f8f98043701687a8531ed2de564ea3df48e9e7e0229ccbe8359efe506896df2efbe3528e977252c50e4a41ca3cc9896e7c5a30bbb1d33604", "sender_address": "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp", + "sender_address_path": 0, "sender_sig": "c511764f3f61ed3d1cbca9514df8bc6811fad5662b1cb0e0587b9c9e49db9f33183cce71af6cb24b507fabf525a2bc405c6e84e63a60334edff0b451ae5e6102" } } @@ -2156,7 +2198,6 @@ pub trait OwnerRpc { # , 5, true, true, true, true); ``` */ - fn retrieve_payment_proof( &self, token: Token, @@ -2181,6 +2222,7 @@ pub trait OwnerRpc { "recipient_address": "tgrin10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqq6t83r", "recipient_sig": "02868f2d2b983981f8f98043701687a8531ed2de564ea3df48e9e7e0229ccbe8359efe506896df2efbe3528e977252c50e4a41ca3cc9896e7c5a30bbb1d33604", "sender_address": "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp", + "sender_address_path": 0, "sender_sig": "c511764f3f61ed3d1cbca9514df8bc6811fad5662b1cb0e0587b9c9e49db9f33183cce71af6cb24b507fabf525a2bc405c6e84e63a60334edff0b451ae5e6102" } }, @@ -2203,7 +2245,6 @@ pub trait OwnerRpc { # , 5, true, true, true, true); ``` */ - fn verify_payment_proof( &self, token: Token, @@ -2288,7 +2329,11 @@ pub trait OwnerRpc { ) -> Result; /** - Networked version of [Owner::build_output](struct.Owner.html#method.create_mwixnet_req). + Networked version of [Owner::create_mwixnet_req](struct.Owner.html#method.create_mwixnet_req). + + server_keys accepts public X25519 onion keys as hex, in route order, replacing secret keys + fee_per_hop accepts a nanogrin string or null for the swap minimum + ``` # grin_wallet_api::doctest_helper_json_rpc_owner_assert_response!( # r#" @@ -2298,12 +2343,12 @@ pub trait OwnerRpc { "params": { "token": "d202964900000000d302964900000000d402964900000000d502964900000000", "commitment": "08e1da9e6dc4d6e808a718b2f110a991dd775d65ce5ae408a4e1f002a4961aa9e7", - "fee_per_hop": "5000000", + "fee_per_hop": null, "lock_output": true, "server_keys": [ - "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332", - "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e", - "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5" + "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + "3ab3b7d1fb643393897a0b942934d34be9cb823621cd49c09b12fdfa69598d71", + "80f2ceadcc5a767961772f4ae04826c70b0ae497f4f50d782241ff056b71df45" ] }, "id": 1 @@ -2325,24 +2370,24 @@ pub trait OwnerRpc { "62ea6b8369686a0415e1e752b9b4d6e66cf5b6066a2d3c60d8818890a55f3adff4601466f4c6e6b646568b99ae93549a3595b7a7b4be815ced87d9297cabbd69518d7b2ed6edd14007528fd346aaea765a1165fe886666627ebcab9588b8ee1c9e98395ae67913c48eb6e924581b40182fce807f97312fb07fd5e216d99941f2b488babce4078a50cd66b28b30a66c4f54fcc127437408a99b30ffd6c3d0d8c7d39e864fc04e321b8c10138c8852d4cad0a4f2780412b9dadcc6e0f2657b7803a81bccb809ca392464be2e01755be7377d0e815698ad6ea51d4617cc92c3ccf852f038e33cc9c90992438ba5c49cca7cc188b682da684e2f4c9733a84a7b64ac5c2216ebf5926f0ee67b664fb5bab799109cbee755ce1aebc8cd352fea51cd84c333cb958093c53544c3f3ab05dba64d8f041c3b179796b476ec04b11044e39db6994ab767315e52cc0ef023432ec88ade2911612db7e74e0923889f765b58b00e3869c5072a4e882c1b721913f63bda986b8c97b7ae575f0d4be596a1ac3cd0db96ce6074ee000b32018b3bda16d7dba34a13ba9c3ce983946414c16e278351a3411cb8ef2cb8ef5b6e1667c4c58bc797c0324ae4fec8960d684e561c0e833ee4c3331c6c439b59042a62993535e23cc8a8a4cf705c0f9b1d62db4e3d76c22c01138800414b143ddff471e4df4413e842a1b41f43cc9647e47145fd6c86d4d1a34fb2f62f5a55b31c9353ee34743c548eff955f2d2143c1a86cbcb452104f96d0142db31153021bbeed995c71a92de8fb1f97269533a508085c543fcb3ee57000bb265e74187b858403aa97b6c7b085e5d5b6025cbfe5f6926d33c835f90e60fc62013e80bbe0a855da5938b4b8f83ac29c5e8251827795356222079a6d1612e2fdf93bd7836d1613c7a353ada48ce256f880bbbb3108e037e3b5647101bd4d549101b0ee73d2248a932a802a3b1beb0b69d777c4285d57e91d83e96fe2f8a1a2f182fe2c6ca37b18460cf8d7f56c201147b9be19f1d01f8ad305c1e9c4dd79b5d8719d6550432352cf737082b1e9de7a083ffbe1" ], "pubkey": "e7ee7d51b11d09f268ade98bc9d7ae9be3c4ac124ce1c3a40e50d34460fa5f08" - } + }, + "tx_id": 5 } } } # "# - # , 5, true, true, false, false); + # , 5, true, false, false, false); ``` * */ - fn create_mwixnet_req( &self, token: Token, commitment: String, - fee_per_hop: String, + fee_per_hop: Option, lock_output: bool, server_keys: Vec, - ) -> Result; + ) -> Result; } fn versioned_output(slate: Slate) -> Result { @@ -2357,15 +2402,23 @@ where K: Keychain + 'static, { fn accounts(&self, token: Token) -> Result, Error> { - Owner::accounts(self, (&token.keychain_mask).as_ref()) + Owner::accounts(self, token.keychain_mask.as_ref()) + } + + fn accounts_info( + &self, + token: Token, + minimum_confirmations: u64, + ) -> Result, Error> { + Owner::accounts_info(self, token.keychain_mask.as_ref(), minimum_confirmations) } fn create_account_path(&self, token: Token, label: &String) -> Result { - Owner::create_account_path(self, (&token.keychain_mask).as_ref(), label) + Owner::create_account_path(self, token.keychain_mask.as_ref(), label) } fn set_active_account(&self, token: Token, label: &String) -> Result<(), Error> { - Owner::set_active_account(self, (&token.keychain_mask).as_ref(), label) + Owner::set_active_account(self, token.keychain_mask.as_ref(), label) } fn retrieve_outputs( @@ -2377,7 +2430,7 @@ where ) -> Result<(bool, Vec), Error> { Owner::retrieve_outputs( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), include_spent, refresh_from_node, tx_id, @@ -2392,7 +2445,7 @@ where ) -> Result<(bool, u64, u64, u32), Error> { Owner::estimate_max_sendable( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, minimum_confirmations, ) @@ -2407,7 +2460,7 @@ where ) -> Result<(bool, Vec), Error> { Owner::retrieve_txs( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, tx_id, tx_slate_id, @@ -2423,7 +2476,7 @@ where ) -> Result<(bool, Vec), Error> { Owner::retrieve_txs( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, None, None, @@ -2439,14 +2492,14 @@ where ) -> Result<(bool, WalletInfo), Error> { Owner::retrieve_summary_info( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, minimum_confirmations, ) } fn init_send_tx(&self, token: Token, args: InitTxArgs) -> Result { - let slate = Owner::init_send_tx(self, (&token.keychain_mask).as_ref(), args)?; + let slate = Owner::init_send_tx(self, token.keychain_mask.as_ref(), args)?; versioned_output(slate) } @@ -2455,7 +2508,7 @@ where token: Token, args: ContractNewArgsAPI, ) -> Result { - let slate = Owner::contract_new(self, (&token.keychain_mask).as_ref(), &args)?; + let slate = Owner::contract_new(self, token.keychain_mask.as_ref(), &args)?; versioned_output(slate) } @@ -2467,7 +2520,7 @@ where ) -> Result { let slate = Owner::contract_sign( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), &Slate::from(in_slate), &args, )?; @@ -2475,7 +2528,7 @@ where } fn contract_view(&self, token: Token, slate: VersionedSlate) -> Result { - Owner::contract_view(self, (&token.keychain_mask).as_ref(), &Slate::from(slate)) + Owner::contract_view(self, token.keychain_mask.as_ref(), &Slate::from(slate)) } fn contract_revoke( @@ -2483,7 +2536,7 @@ where token: Token, args: ContractRevokeArgsAPI, ) -> Result, Error> { - let slate_opt = Owner::contract_revoke(self, (&token.keychain_mask).as_ref(), &args)?; + let slate_opt = Owner::contract_revoke(self, token.keychain_mask.as_ref(), &args)?; // We return a slate only when we had to perform a self-spend safe cancel if let Some(slate) = slate_opt { return Ok(Some(versioned_output(slate)?)); @@ -2496,7 +2549,7 @@ where token: Token, args: IssueInvoiceTxArgs, ) -> Result { - let slate = Owner::issue_invoice_tx(self, (&token.keychain_mask).as_ref(), args)?; + let slate = Owner::issue_invoice_tx(self, token.keychain_mask.as_ref(), args)?; versioned_output(slate) } @@ -2508,7 +2561,7 @@ where ) -> Result { let out_slate = Owner::process_invoice_tx( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), &Slate::from(in_slate), args, )?; @@ -2516,26 +2569,19 @@ where } fn tx_lock_outputs(&self, token: Token, in_slate: VersionedSlate) -> Result<(), Error> { - Owner::tx_lock_outputs( - self, - (&token.keychain_mask).as_ref(), - &Slate::from(in_slate), - ) + Owner::tx_lock_outputs(self, token.keychain_mask.as_ref(), &Slate::from(in_slate)) } fn finalize_tx(&self, token: Token, in_slate: VersionedSlate) -> Result { - let out_slate = Owner::finalize_tx( - self, - (&token.keychain_mask).as_ref(), - &Slate::from(in_slate), - )?; + let out_slate = + Owner::finalize_tx(self, token.keychain_mask.as_ref(), &Slate::from(in_slate))?; versioned_output(out_slate) } fn post_tx(&self, token: Token, slate: VersionedSlate, fluff: bool) -> Result<(), Error> { Owner::post_tx( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), &Slate::from(slate), fluff, ) @@ -2547,7 +2593,7 @@ where tx_id: Option, tx_slate_id: Option, ) -> Result<(), Error> { - Owner::cancel_tx(self, (&token.keychain_mask).as_ref(), tx_id, tx_slate_id) + Owner::cancel_tx(self, token.keychain_mask.as_ref(), tx_id, tx_slate_id) } fn get_stored_tx( @@ -2556,12 +2602,8 @@ where id: Option, slate_id: Option, ) -> Result, Error> { - let out_slate = Owner::get_stored_tx( - self, - (&token.keychain_mask).as_ref(), - id, - (&slate_id).as_ref(), - )?; + let out_slate = + Owner::get_stored_tx(self, token.keychain_mask.as_ref(), id, slate_id.as_ref())?; match out_slate { Some(s) => { let version = SlateVersion::V4; @@ -2572,7 +2614,7 @@ where } fn get_rewind_hash(&self, token: Token) -> Result { - Owner::get_rewind_hash(self, (&token.keychain_mask).as_ref()) + Owner::get_rewind_hash(self, token.keychain_mask.as_ref()) } fn scan_rewind_hash( @@ -2591,14 +2633,14 @@ where ) -> Result<(), Error> { Owner::scan( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), start_height, delete_unconfirmed, ) } fn node_height(&self, token: Token) -> Result { - Owner::node_height(self, (&token.keychain_mask).as_ref()) + Owner::node_height(self, token.keychain_mask.as_ref()) } fn init_secure_api(&self, ecdh_pubkey: ECDHPubkey) -> Result { @@ -2650,16 +2692,13 @@ where mnemonic_length: u32, password: String, ) -> Result<(), Error> { - let n = name.as_ref().map(|s| s.as_str()); - let m = match mnemonic { - Some(s) => Some(ZeroingString::from(s)), - None => None, - }; + let n = name.as_deref(); + let m = mnemonic.map(ZeroingString::from); Owner::create_wallet(self, n, m, mnemonic_length, ZeroingString::from(password)) } fn open_wallet(&self, name: Option, password: String) -> Result { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); let sec_key = Owner::open_wallet(self, n, ZeroingString::from(password), true)?; Ok(Token { keychain_mask: sec_key, @@ -2667,30 +2706,30 @@ where } fn close_wallet(&self, name: Option) -> Result<(), Error> { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); Owner::close_wallet(self, n) } fn get_mnemonic(&self, name: Option, password: String) -> Result { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); let res = Owner::get_mnemonic(self, n, ZeroingString::from(password))?; - Ok((&*res).to_string()) + Ok((*res).to_string()) } fn change_password(&self, name: Option, old: String, new: String) -> Result<(), Error> { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); Owner::change_password(self, n, ZeroingString::from(old), ZeroingString::from(new)) } fn delete_wallet(&self, name: Option) -> Result<(), Error> { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); Owner::delete_wallet(self, n) } fn start_updater(&self, token: Token, frequency: u32) -> Result<(), Error> { Owner::start_updater( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), Duration::from_millis(frequency as u64), ) } @@ -2706,21 +2745,18 @@ where fn get_slatepack_address( &self, token: Token, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result { - Owner::get_slatepack_address(self, (&token.keychain_mask).as_ref(), derivation_index) + Owner::get_slatepack_address(self, token.keychain_mask.as_ref(), derivation_index) } fn get_slatepack_secret_key( &self, token: Token, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result { - let key = Owner::get_slatepack_secret_key( - self, - (&token.keychain_mask).as_ref(), - derivation_index, - )?; + let key = + Owner::get_slatepack_secret_key(self, token.keychain_mask.as_ref(), derivation_index)?; Ok(Ed25519SecretKey { key }) } @@ -2728,12 +2764,12 @@ where &self, token: Token, slate: VersionedSlate, - sender_index: Option, + sender_index: Option, recipients: Vec, ) -> Result { let res = Owner::create_slatepack_message( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), &Slate::from(slate), sender_index, recipients, @@ -2745,11 +2781,11 @@ where &self, token: Token, message: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result { let slate = Owner::slate_from_slatepack_message( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), message, secret_indices, )?; @@ -2761,14 +2797,9 @@ where &self, token: Token, message: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result { - Owner::decode_slatepack_message( - self, - (&token.keychain_mask).as_ref(), - message, - secret_indices, - ) + Owner::decode_slatepack_message(self, token.keychain_mask.as_ref(), message, secret_indices) } fn retrieve_payment_proof( @@ -2780,7 +2811,7 @@ where ) -> Result { Owner::retrieve_payment_proof( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, tx_id, tx_slate_id, @@ -2792,7 +2823,7 @@ where token: Token, proof: PaymentProof, ) -> Result<(bool, bool), Error> { - Owner::verify_payment_proof(self, (&token.keychain_mask).as_ref(), &proof) + Owner::verify_payment_proof(self, token.keychain_mask.as_ref(), &proof) } fn set_tor_config(&self, tor_config: Option) -> Result<(), Error> { @@ -2806,41 +2837,34 @@ where features: OutputFeatures, amount: Amount, ) -> Result { - Owner::build_output(self, (&token.keychain_mask).as_ref(), features, amount.0) + Owner::build_output(self, token.keychain_mask.as_ref(), features, amount.0) } fn create_mwixnet_req( &self, token: Token, commitment: String, - fee_per_hop: String, + fee_per_hop: Option, lock_output: bool, server_keys: Vec, - ) -> Result { - let commit = - Commitment::from_vec(from_hex(&commitment).map_err(|e| Error::CommitDeser(e))?); - - let secp_inst = static_secp_instance(); - let secp = secp_inst.lock(); + ) -> Result { + let commit = Commitment::from_vec(from_hex(&commitment).map_err(Error::CommitDeser)?); let mut keys = vec![]; for key in server_keys { - keys.push(SecretKey::from_slice( - &secp, - &grin_util::from_hex(&key).map_err(|e| Error::ServerKeyDeser(e))?, - )?) + keys.push(MwixnetServerPublicKey::from_hex(&key).map_err(Error::ServerKeyDeser)?) } let req_params = MixnetReqCreationParams { server_keys: keys, fee_per_hop: fee_per_hop - .parse::() - .map_err(|_| Error::U64Deser(fee_per_hop))?, + .map(|fee| fee.parse::().map_err(|_| Error::U64Deser(fee))) + .transpose()?, }; Owner::create_mwixnet_req( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), &req_params, &commit, lock_output, @@ -2875,6 +2899,7 @@ pub fn run_doctest_owner( /// Set up an owner doctest and run several requests against the same wallet #[doc(hidden)] +#[allow(clippy::too_many_arguments)] pub fn run_doctest_owner_with( test_dir: &str, blocks_to_mine: u64, @@ -3002,19 +3027,14 @@ where let _ = test_framework::award_blocks_to_wallet( &chain, wallet1.clone(), - (&mask1).as_ref(), - 1 as usize, + mask1.as_ref(), + 1_usize, false, ); //update local outputs after each block, so transaction IDs stay consistent - let (wallet_refreshed, _) = api_impl::owner::retrieve_summary_info( - wallet1.clone(), - (&mask1).as_ref(), - &None, - true, - 1, - ) - .unwrap(); + let (wallet_refreshed, _) = + api_impl::owner::retrieve_summary_info(wallet1.clone(), mask1.as_ref(), &None, true, 1) + .unwrap(); assert!(wallet_refreshed); } @@ -3041,25 +3061,24 @@ where payment_proof_recipient_address: proof_address, ..Default::default() }; - let mut slate = api_impl::owner::init_send_tx(w, (&mask1).as_ref(), args, true).unwrap(); + let mut slate = api_impl::owner::init_send_tx(w, mask1.as_ref(), args, true).unwrap(); println!("INITIAL SLATE"); println!("{}", serde_json::to_string_pretty(&slate).unwrap()); { let mut w_lock = wallet2.lock(); let w2 = w_lock.lc_provider().unwrap().wallet_inst().unwrap(); - slate = - api_impl::foreign::receive_tx(w2, (&mask2).as_ref(), &slate, None, true).unwrap(); + slate = api_impl::foreign::receive_tx(w2, mask2.as_ref(), &slate, None, true).unwrap(); w2.close().unwrap(); } // Spit out slate for input to finalize_tx if lock_tx { println!("LOCKING TX"); - api_impl::owner::tx_lock_outputs(w, (&mask1).as_ref(), &slate).unwrap(); + api_impl::owner::tx_lock_outputs(w, mask1.as_ref(), &slate).unwrap(); } println!("RECEIPIENT SLATE"); println!("{}", serde_json::to_string_pretty(&slate).unwrap()); if finalize_tx { - slate = api_impl::owner::finalize_tx(w, (&mask1).as_ref(), &slate).unwrap(); + slate = api_impl::owner::finalize_tx(w, mask1.as_ref(), &slate).unwrap(); error!("FINALIZED TX SLATE"); println!("{}", serde_json::to_string_pretty(&slate).unwrap()); } @@ -3075,8 +3094,8 @@ where let _ = test_framework::award_blocks_to_wallet( &chain, wallet1.clone(), - (&mask1).as_ref(), - 3 as usize, + mask1.as_ref(), + 3_usize, false, ); } diff --git a/api/src/types.rs b/api/src/types.rs index 797901a..d2503dc 100644 --- a/api/src/types.rs +++ b/api/src/types.rs @@ -18,7 +18,6 @@ use crate::util::secp::key::{PublicKey, SecretKey}; use crate::util::{from_hex, ToHex}; use ed25519_dalek::SigningKey as DalekSecretKey; -use base64; use rand::{thread_rng, Rng}; use ring::aead; use serde_json::{self, Value}; @@ -90,8 +89,10 @@ impl EncryptedBody { aad, &mut to_encrypt, ); - if let Err(_) = res { - return Err(Error::APIEncryption("EncryptedBody: encryption failed".to_owned()).into()); + if res.is_err() { + return Err(Error::APIEncryption( + "EncryptedBody: encryption failed".to_owned(), + )); } Ok(EncryptedBody { @@ -129,8 +130,7 @@ impl EncryptedBody { if nonce.len() < 12 { return Err(Error::APIEncryption( "EncryptedBody Dec: Invalid Nonce length".to_string(), - ) - .into()); + )); } let mut n = [0u8; 12]; n.copy_from_slice(&nonce[0..12]); @@ -139,8 +139,10 @@ impl EncryptedBody { let aad = aead::Aad::from(&[]); let res = opening_key.open_in_place(aead::Nonce::assume_unique_for_key(n), aad, &mut to_decrypt); - if let Err(_) = res { - return Err(Error::APIEncryption("EncryptedBody: decryption failed".to_owned()).into()); + if res.is_err() { + return Err(Error::APIEncryption( + "EncryptedBody: decryption failed".to_owned(), + )); } for _ in 0..aead::AES_256_GCM.tag_len() { to_decrypt.pop(); @@ -148,8 +150,8 @@ impl EncryptedBody { let decrypted = String::from_utf8(to_decrypt) .map_err(|_| Error::APIEncryption("EncryptedBody Dec: Invalid UTF-8".to_string()))?; - Ok(serde_json::from_str(&decrypted) - .map_err(|_| Error::APIEncryption("EncryptedBody Dec: Invalid JSON".to_string()))?) + serde_json::from_str(&decrypted) + .map_err(|_| Error::APIEncryption("EncryptedBody Dec: Invalid JSON".to_string())) } } @@ -275,9 +277,9 @@ impl EncryptionErrorResponse { pub fn new(id: u64, code: i32, message: &str) -> Self { EncryptionErrorResponse { jsonrpc: "2.0".to_owned(), - id: id, + id, error: EncryptionError { - code: code, + code, message: message.to_owned(), }, } diff --git a/api/tests/slate_versioning.rs b/api/tests/slate_versioning.rs index ede8453..83e0d25 100644 --- a/api/tests/slate_versioning.rs +++ b/api/tests/slate_versioning.rs @@ -15,7 +15,6 @@ //use grin_wallet_api::foreign_rpc_client; use grin_wallet_api::run_doctest_foreign; //use grin_wallet_libwallet::VersionedSlate; -use serde_json; use serde_json::Value; use tempfile::tempdir; //use grin_wallet_libwallet::slate_versions::v1::SlateV1; diff --git a/config/Cargo.toml b/config/Cargo.toml index 5d7e339..c58fbc4 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_config" -version = "5.5.0" +version = "5.5.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" @@ -20,8 +20,8 @@ lazy_static = "1" ##### Grin Imports -grin_core = { path = "../grin/core"} -grin_util = { path = "../grin/util"} +grin_core = { workspace = true } +grin_util = { workspace = true } ##### diff --git a/config/src/config.rs b/config/src/config.rs index e4f3778..4eef1ff 100644 --- a/config/src/config.rs +++ b/config/src/config.rs @@ -170,13 +170,13 @@ pub fn get_wallet_path( // A - Detect grin-wallet.toml in working dir let mut config_path = env::current_dir()?; config_path.push(WALLET_CONFIG_FILE_NAME); - if create_path == false && config_path.exists() { + if !create_path && config_path.exists() { config_path.pop(); println!("Detected 'grin-wallet.toml' in working dir - opening associated wallet"); return Ok(config_path); }; // B - Select home directory - let mut wallet_path = dirs::home_dir().unwrap_or_else(|| PathBuf::new()); + let mut wallet_path = dirs::home_dir().unwrap_or_default(); wallet_path.push(GRIN_HOME); wallet_path.push(chain_type.shortname()); // Create if the default path doesn't exist @@ -199,7 +199,7 @@ pub fn get_node_path( data_path: Option, chain_type: &global::ChainTypes, ) -> Result { - let node_path = match data_path { + match data_path { // 1) A If top dir provided and api_secret exist, return top dir Some(path) => { let mut node_path = path; @@ -211,7 +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 = dirs::home_dir().unwrap_or_else(|| PathBuf::new()); + let mut node_path = dirs::home_dir().unwrap_or_default(); node_path.push(GRIN_HOME); node_path.push(chain_type.shortname()); Ok(node_path) @@ -219,13 +219,12 @@ pub fn get_node_path( } // 2) If there is no top_dir provided, always return home dir None => { - let mut node_path = dirs::home_dir().unwrap_or_else(|| PathBuf::new()); + let mut node_path = dirs::home_dir().unwrap_or_default(); node_path.push(GRIN_HOME); node_path.push(chain_type.shortname()); Ok(node_path) } - }; - node_path + } } /// Checks if config in current working dir @@ -297,10 +296,10 @@ 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 this order: -/// a) current dir as template, -/// b) in top path, or -/// c) .grin home +/// 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 @@ -371,7 +370,7 @@ pub fn initial_setup_wallet( // Return config if not run with init true => { // If run with init and seed do not yet exists, continue, else throw error - if data_dir.exists() && create_path == true { + if data_dir.exists() && create_path { let msg = format!( "{} already exists in the target directory ({}). Please remove it first", config_path.to_str().unwrap(), @@ -409,9 +408,9 @@ impl Default for GlobalWalletConfigMembers { 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, file_path: &PathBuf) -> GlobalWalletConfig { + pub fn for_chain(chain_type: &global::ChainTypes, file_path: &Path) -> GlobalWalletConfig { let mut defaults_conf = GlobalWalletConfig { - config_file_path: file_path.clone(), + config_file_path: file_path.to_path_buf(), members: GlobalWalletConfigMembers::default(), }; let defaults = &mut defaults_conf.members.wallet; @@ -484,7 +483,7 @@ impl GlobalWalletConfig { } /// Update paths - pub fn update_paths(&mut self, wallet_home: &PathBuf, node_home: &Path) { + pub fn update_paths(&mut self, wallet_home: &Path, node_home: &Path) { let mut data_file_dir = wallet_home.to_path_buf(); let mut node_secret_path = node_home.to_path_buf(); let mut secret_path = wallet_home.to_path_buf(); diff --git a/config/src/types.rs b/config/src/types.rs index ec6894c..891be21 100644 --- a/config/src/types.rs +++ b/config/src/types.rs @@ -118,7 +118,7 @@ impl WalletConfig { /// Accept fee base pub fn accept_fee_base(&self) -> u64 { self.accept_fee_base - .unwrap_or_else(|| WalletConfig::default_accept_fee_base()) + .unwrap_or_else(WalletConfig::default_accept_fee_base) } /// Node API requests timeout. @@ -270,7 +270,7 @@ impl TorConfig { } /// Tor Bridge Config -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct TorBridgeConfig { /// Path to bridge binary to use with integrated Tor library pub bridge_bin_path: Option, @@ -280,16 +280,6 @@ pub struct TorBridgeConfig { pub client_option: Option, } -impl Default for TorBridgeConfig { - fn default() -> TorBridgeConfig { - TorBridgeConfig { - bridge_bin_path: None, - bridge_line: None, - client_option: None, - } - } -} - impl fmt::Display for TorBridgeConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) @@ -297,7 +287,7 @@ impl fmt::Display for TorBridgeConfig { } /// Tor Proxy configuration (useful for protocols such as shadowsocks) -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct TorProxyConfig { /// socks4 |socks5 | http(s) pub transport: Option, @@ -311,18 +301,6 @@ pub struct TorProxyConfig { pub allowed_port: Option>, } -impl Default for TorProxyConfig { - fn default() -> TorProxyConfig { - TorProxyConfig { - transport: None, - address: None, - username: None, - password: None, - allowed_port: None, - } - } -} - impl fmt::Display for TorProxyConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) diff --git a/controller/Cargo.toml b/controller/Cargo.toml index 5de94f2..2db9e57 100644 --- a/controller/Cargo.toml +++ b/controller/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_controller" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Controllers for grin wallet instantiation" license = "Apache-2.0" @@ -25,21 +25,21 @@ lazy_static = "1" thiserror = "1" qr_code = "1.1.0" -grin_wallet_util = { path = "../util", version = "5.5.0" } -grin_wallet_api = { path = "../api", version = "5.5.0" } -grin_wallet_impls = { path = "../impls", version = "5.5.0" } -grin_wallet_libwallet = { path = "../libwallet", version = "5.5.0" } -grin_wallet_config = { path = "../config", version = "5.5.0" } +grin_wallet_util = { path = "../util", version = "5.5.1" } +grin_wallet_api = { path = "../api", version = "5.5.1" } +grin_wallet_impls = { path = "../impls", version = "5.5.1" } +grin_wallet_libwallet = { path = "../libwallet", version = "5.5.1" } +grin_wallet_config = { path = "../config", version = "5.5.1" } ##### Grin Imports -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 = { workspace = true } +grin_keychain = { workspace = true } +grin_util = { workspace = true } +grin_api = { workspace = true } +grin_chain = { workspace = true } ##### [dev-dependencies] -ed25519-dalek = "2" \ No newline at end of file +ed25519-dalek = "2" diff --git a/controller/src/command.rs b/controller/src/command.rs index e6f1a89..af71ec1 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -18,21 +18,28 @@ use crate::apiwallet::{try_slatepack_sync_workflow, Owner}; use crate::config::{TorConfig, WalletConfig, WALLET_CONFIG_FILE_NAME}; use crate::core::{core, global}; use crate::error::Error; -use crate::impls::PathToSlatepack; use crate::keychain; +use crate::libwallet::api_impl::owner::{self, decrypt_slatepack}; use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::contract::types::{ ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI, OutputSelectionArgs, PaymentMemo, ProofArgs, ProofType, }; use crate::libwallet::contract::{can_finalize, initial_net_change}; +use crate::libwallet::mwixnet::MixnetReqCreationParams; +use crate::libwallet::slatepack::get_slatepack_file_contents; +use crate::libwallet::slatepack::SlatepackAddressIndex; +use crate::libwallet::OutputCommitMapping; use crate::libwallet::{ self, EarlyPaymentProof, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, - SlateState, SlatepackAddress, Slatepacker, SlatepackerArgs, WalletLCProvider, + SlateState, Slatepack, SlatepackAddress, WalletLCProvider, }; +use crate::libwallet::{wallet_lock, WalletHandle}; use crate::util::secp::key::SecretKey; -use crate::util::{Mutex, ZeroingString}; +use crate::util::secp::pedersen::Commitment; +use crate::util::{Mutex, ToHex, ZeroingString}; use crate::{controller, display}; +use grin_wallet_util::OnionV3Address; use qr_code::QrCode; use serde::{Deserialize, Serialize}; @@ -59,7 +66,7 @@ fn show_recovery_phrase(phrase: ZeroingString) { /// Arguments common to all wallet commands #[derive(Clone)] pub struct GlobalArgs { - pub account: String, + pub account: Option, pub api_secret: Option, pub node_api_secret: Option, pub show_spent: bool, @@ -126,7 +133,7 @@ where Ok(()) } -pub fn rewind_hash<'a, L, C, K>( +pub fn rewind_hash( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, ) -> Result<(), Error> @@ -165,7 +172,7 @@ where 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), + None => args.start_height.unwrap_or(1), }; warn!( "Starting view wallet output scan from height {} ...", @@ -190,6 +197,7 @@ where } } +#[allow(clippy::too_many_arguments)] pub fn listen( owner_api: &mut Owner, keychain_mask: Arc>>, @@ -228,7 +236,7 @@ where if let Ok(t) = api_thread { if !cli_mode { let r = t.join(); - if let Err(_) = r { + if r.is_err() { error!("Error starting listener"); return Err(Error::ListenerError); } @@ -270,6 +278,8 @@ where /// Arguments for account command pub struct AccountArgs { pub create: Option, + pub minimum_confirmations: u64, + pub active: Option, } pub fn account( @@ -282,20 +292,7 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - if args.create.is_none() { - 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(); + if let Some(label) = args.create { let res = { owner_api.create_account_path(keychain_mask, &label)?; thread::sleep(Duration::from_millis(200)); @@ -307,6 +304,31 @@ where error!("Error creating account '{}': {}", label, e); return Err(Error::LibWallet(e)); } + } else if let Some(label) = args.active { + let res = { + owner_api.set_active_account(keychain_mask, &label)?; + thread::sleep(Duration::from_millis(200)); + info!("Account: '{}' set as active!", label); + Ok(()) + }; + if let Err(e) = res { + thread::sleep(Duration::from_millis(200)); + error!("Error setting account '{}' as active: {}", label, e); + return Err(Error::LibWallet(e)); + } + } else { + let res = { + let acct_mappings = + owner_api.accounts_info(keychain_mask, args.minimum_confirmations)?; + // 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)); + } } Ok(()) } @@ -332,6 +354,7 @@ pub struct SendArgs { pub outfile: Option, pub bridge: Option, pub slatepack_qr: bool, + pub address_index: Option, } fn max_retry_args(mut init_args: InitTxArgs, amount: u64, max_inputs: u32) -> InitTxArgs { @@ -379,12 +402,15 @@ where true, args.minimum_confirmations, )?; - if args.use_max_amount { - amount = wallet_info.amount_currently_spendable; - } if !info_updated && !update_skipped { warn!("Wallet info update failed: node connection error"); } + if args.use_max_amount { + amount = wallet_info.amount_currently_spendable; + if amount == 0 { + return Err(Error::GenericError("No spendable funds".to_string())); + } + } if args.estimate_selection_strategies { let strategies = estimate_strategies(args.use_max_amount) .iter() @@ -400,6 +426,7 @@ where selection_strategy_is_use_all: strategy == "all", refresh_outputs_from_node: !info_updated, estimate_only: Some(true), + address_index: args.address_index, ..Default::default() }; let result = owner_api.init_send_tx(keychain_mask, init_args.clone()); @@ -413,11 +440,11 @@ where init_args = max_retry_args(init_args, amount, max_inputs); owner_api.init_send_tx(keychain_mask, init_args)? } else { - return Err(grin_wallet_libwallet::Error::from(e)); + return Err(e); } } _ => { - return Err(grin_wallet_libwallet::Error::from(e)); + return Err(e); } }, }; @@ -443,26 +470,21 @@ where target_slate_version: args.target_slate_version, payment_proof_recipient_address, ttl_blocks: args.ttl_blocks, - send_args: None, late_lock: Some(args.late_lock), + address_index: args.address_index, ..Default::default() }; let init_send_tx = |init_args: InitTxArgs| -> Result { let result = owner_api.init_send_tx(keychain_mask, init_args.clone()); - let slate = match result { - Ok(s) => { - info!( - "Tx created: {} grin to {} (strategy '{}')", - core::amount_to_hr_string(init_args.amount, false), - dest.as_ref() - .map(ToString::to_string) - .unwrap_or_else(|| "no destination".to_string()), - args.selection_strategy, - ); - s - } - Err(e) => return Err(e), - }; + let slate = result?; + info!( + "Tx created: {} grin to {} (strategy '{}')", + core::amount_to_hr_string(init_args.amount, false), + dest.as_ref() + .map(ToString::to_string) + .unwrap_or_else(|| "no destination".to_string()), + args.selection_strategy, + ); Ok(slate) }; slate = match init_send_tx(init_args.clone()) { @@ -498,22 +520,32 @@ where tor_config.bridge.bridge_line = Some(b); } - let output_sp = || -> Result<(), Error> { + let output_sp = |owner_api: &mut Owner, lock_outputs: bool| -> Result<(), Error> { + let sender_index = { + wallet_lock!(owner_api.wallet_inst, w); + let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?; + context.payment_proof_derivation_index + }; Ok(output_slatepack( owner_api, keychain_mask, &slate, dest.clone(), args.outfile, - true, + lock_outputs, false, args.slatepack_qr, + sender_index, )?) }; let can_send = tor_config.send_tor(args.skip_tor); if test_mode || !can_send || dest.is_none() { - return output_sp(); + return output_sp(owner_api, !args.late_lock); + } + + if !args.late_lock { + owner_api.tx_lock_outputs(keychain_mask, &slate)?; } let dest = dest.as_ref().unwrap(); @@ -521,7 +553,6 @@ where match res { 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 { @@ -536,7 +567,13 @@ where } Err(e) => { error!("Error sending slate sync: {}", e); - output_sp()?; + output_sp(owner_api, false)?; + if !args.late_lock { + println!( + "Outputs are locked. To unlock them, cancel with `cancel -t {}`.", + slate.id + ); + } } } Ok(()) @@ -548,6 +585,7 @@ fn slatepack_message( slate: &Slate, dest: Option, out_file_override: Option, + sender_index: Option, ) -> Result<(String, String), libwallet::Error> where L: WalletLCProvider<'static, C, K> + 'static, @@ -555,7 +593,8 @@ where K: keychain::Keychain + 'static, { let recipients = dest.into_iter().collect(); - let message = owner_api.create_slatepack_message(keychain_mask, slate, Some(0), recipients)?; + let message = + owner_api.create_slatepack_message(keychain_mask, slate, sender_index, recipients)?; let tld = owner_api.get_top_level_directory()?; let slate_dir = format!("{}/{}", tld, "slatepack"); let _ = std::fs::create_dir_all(&slate_dir); @@ -572,6 +611,7 @@ fn write_slatepack(message: &str, out_file: &str) -> io::Result<()> { output.sync_all() } +#[allow(clippy::too_many_arguments)] pub fn output_slatepack( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, @@ -581,6 +621,7 @@ pub fn output_slatepack( lock: bool, finalizing: bool, show_qr: bool, + sender_index: Option, ) -> Result<(), libwallet::Error> where L: WalletLCProvider<'static, C, K> + 'static, @@ -593,6 +634,7 @@ where slate, dest.clone(), out_file_override, + sender_index, )?; if lock { @@ -604,7 +646,18 @@ where println!(); if !finalizing { - println!("Slatepack data follows. Please provide this output to the other party"); + let cancel_hint = if lock { + format!( + " or cancel it manually with `cancel -t {}` command", + slate.id + ) + } else { + "".to_string() + }; + println!( + "Slatepack data follows. Please provide this output to the other party{}.", + cancel_hint + ); } else { println!("Slatepack data follows."); } @@ -725,6 +778,7 @@ where slate, dest.clone(), out_file_override, + Some(SlatepackAddressIndex(0)), )?; message.truncate(message.trim_end().len()); write_slatepack(&message, &out_file_name)?; @@ -753,28 +807,25 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - let mut slatepack = match filename { - Some(f) => { - let pts = PathToSlatepack::new(f.into(), &packer, true); - pts.get_slatepack(false)? - } - None => match message { - Some(message) => packer.deser_slatepack(message.trim_start().as_bytes(), false)?, - None => { - let msg = "No slate provided via file or direct input"; - return Err(Error::GenericError(msg.into())); - } - }, + let data = match filename { + Some(f) => get_slatepack_file_contents(&f.into())?, + None => message + .ok_or_else(|| { + Error::GenericError("No slate provided via file or direct input".into()) + })? + .trim_start() + .as_bytes() + .to_vec(), }; + let mut slatepack = libwallet::api_impl::owner::parse_slatepack(&data)?; let was_encrypted = slatepack.is_encrypted(); if was_encrypted { - let dec_key = owner_api.get_slatepack_secret_key(keychain_mask, 0)?; - if let Err(e) = slatepack.try_decrypt_payload(Some(&dec_key)) { + if let Err(e) = decrypt_slatepack( + &mut slatepack, + owner_api.wallet_inst.clone(), + keychain_mask, + vec![SlatepackAddressIndex(0)], + ) { // tell the user which account can decrypt it let account = libwallet::api_impl::owner::slatepack_account( owner_api.wallet_inst.clone(), @@ -791,7 +842,7 @@ where }); } } - let slate = packer.get_slate(&slatepack)?; + let slate = slatepack.get_slate()?; Ok((slate, slatepack.sender, was_encrypted)) } @@ -826,7 +877,6 @@ pub struct ReceiveArgs { pub fn receive( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, - g_args: &GlobalArgs, args: ReceiveArgs, mut tor_config: TorConfig, test_mode: bool, @@ -862,10 +912,7 @@ where _ => {} } - let km = match keychain_mask.as_ref() { - None => None, - Some(&m) => Some(m.to_owned()), - }; + let km = keychain_mask.as_ref().map(|&m| m.to_owned()); if let Some(b) = args.bridge { tor_config.bridge.bridge_line = Some(b); @@ -876,7 +923,7 @@ where owner_api.config_path(), km, |api| { - slate = api.receive_tx(&slate, Some(&g_args.account), None)?; + slate = api.receive_tx(&slate, None, None)?; Ok(()) }, )?; @@ -891,6 +938,7 @@ where false, false, args.slatepack_qr, + None, )?) }; @@ -906,8 +954,7 @@ where Ok(s) => { // Update slate state. { - let mut w_lock = owner_api.wallet_inst.lock(); - let w = w_lock.lc_provider()?.wallet_inst()?; + wallet_lock!(owner_api.wallet_inst, w); let parent_key_id = w.parent_key_id(); match update_tx_slate_state(w, keychain_mask, &parent_key_id, &s) { Ok(_) => {} @@ -929,65 +976,59 @@ where Ok(()) } +pub fn read_slatepack(args: ReceiveArgs) -> Result { + let data = match args.input_file { + Some(f) => get_slatepack_file_contents(&f.into())?, + None => match args.input_slatepack_message { + Some(message) => message.into_bytes(), + None => return Err(Error::ArgumentError("Invalid Slatepack Input".into())), + }, + }; + Ok(owner::parse_slatepack(&data)?) +} + pub fn unpack( - owner_api: &mut Owner, + wallet_inst: WalletHandle<'static, L, C, K>, keychain_mask: Option<&SecretKey>, - args: ReceiveArgs, + mut slatepack: Slatepack, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let mut slatepack = match args.input_file { - Some(f) => { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - PathToSlatepack::new(f.into(), &packer, true).get_slatepack(false)? - } - None => match args.input_slatepack_message { - Some(mes) => owner_api.decode_slatepack_message(keychain_mask, mes, vec![])?, - None => { - return Err(Error::ArgumentError("Invalid Slatepack Input".into()).into()); - } - }, - }; println!(); println!("SLATEPACK CONTENTS"); println!("------------------"); println!("{}", slatepack); println!("------------------"); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - if slatepack.is_encrypted() { - let dec_key = owner_api.get_slatepack_secret_key(keychain_mask, 0)?; - match slatepack.try_decrypt_payload(Some(&dec_key)) { - Ok(_) => { + match decrypt_slatepack( + &mut slatepack, + wallet_inst, + keychain_mask, + vec![SlatepackAddressIndex(0)], + ) + .and_then(|_| slatepack.get_slate()) + { + Ok(s) => { 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); + println!("{}", s); } Err(_) => { println!("Slatepack payload cannot be decrypted by this wallet"); } } } else { - let slate = packer.get_slate(&slatepack)?; + let slate = slatepack.get_slate()?; println!("Slatepack is not encrypted"); println!(); println!("SLATE"); @@ -1018,7 +1059,7 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let (mut slate, _ret_address) = parse_slatepack( + let (mut slate, _) = parse_slatepack( owner_api, keychain_mask, args.input_file.clone(), @@ -1050,10 +1091,7 @@ where let is_invoice = slate.state == SlateState::Invoice2; if is_invoice { - let km = match keychain_mask.as_ref() { - None => None, - Some(&m) => Some(m.to_owned()), - }; + let km = keychain_mask.as_ref().map(|&m| m.to_owned()); controller::foreign_single_use( owner_api.wallet_inst.clone(), owner_api.config_path(), @@ -1092,6 +1130,7 @@ where false, true, args.slatepack_qr, + None, )?; Ok(()) @@ -1101,11 +1140,11 @@ where pub struct IssueInvoiceArgs { /// Slatepack address pub dest: Option, - /// issue invoice tx args + /// Issue invoice tx args pub issue_args: IssueInvoiceTxArgs, - /// output file override + /// Output file override pub outfile: Option, - /// show slatepack as QR code + /// Show slatepack as QR code pub slatepack_qr: bool, } @@ -1126,8 +1165,13 @@ where .transpose()?; let issue_args = args.issue_args.clone(); - let slate = owner_api.issue_invoice_tx(keychain_mask, issue_args)?; + let slate = owner_api.issue_invoice_tx(keychain_mask, issue_args.clone())?; + let sender_index = { + wallet_lock!(owner_api.wallet_inst, w); + let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?; + context.payment_proof_derivation_index + }; output_slatepack( owner_api, keychain_mask, @@ -1137,6 +1181,7 @@ where false, false, args.slatepack_qr, + sender_index, )?; Ok(()) } @@ -1217,7 +1262,6 @@ where selection_strategy_is_use_all: args.selection_strategy == "all", refresh_outputs_from_node: !info_updated, ttl_blocks: args.ttl_blocks, - send_args: None, ..Default::default() }; let result = owner_api.process_invoice_tx(keychain_mask, &slate, init_args); @@ -1251,6 +1295,7 @@ where true, false, args.slatepack_qr, + None, )?) }; @@ -1297,7 +1342,6 @@ pub struct InfoArgs { pub fn info( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, - g_args: &GlobalArgs, args: InfoArgs, dark_scheme: bool, ) -> Result<(), Error> @@ -1309,8 +1353,9 @@ where let updater_running = owner_api.updater_running.load(Ordering::Relaxed); let (validated, wallet_info) = owner_api.retrieve_summary_info(keychain_mask, true, args.minimum_confirmations)?; + let account = account_label(owner_api)?; display::info( - &g_args.account, + &account, &wallet_info, validated || updater_running, dark_scheme, @@ -1333,8 +1378,9 @@ where let res = owner_api.node_height(keychain_mask)?; let (validated, outputs) = owner_api.retrieve_outputs(keychain_mask, g_args.show_spent, true, None)?; + let account = account_label(owner_api)?; display::outputs( - &g_args.account, + &account, res.height, validated || updater_running, outputs, @@ -1353,7 +1399,6 @@ pub struct TxsArgs { pub fn txs( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, - g_args: &GlobalArgs, args: TxsArgs, dark_scheme: bool, ) -> Result<(), Error> @@ -1367,13 +1412,14 @@ where // 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(); + let include_status = args.id.is_none() && args.tx_slate_id.is_none(); // 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)); + let account = account_label(owner_api)?; display::txs( - &g_args.account, + &account, res.height, validated || updater_running, &txs[first_tx..], @@ -1399,7 +1445,7 @@ where if id.is_some() { let (_, outputs) = owner_api.retrieve_outputs(keychain_mask, true, false, id)?; display::outputs( - &g_args.account, + &account, res.height, validated || updater_running, outputs, @@ -1431,7 +1477,7 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let (slate, _ret_address) = parse_slatepack( + let (slate, _) = parse_slatepack( owner_api, keychain_mask, args.input_file, @@ -1563,7 +1609,7 @@ where 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), + None => args.start_height.unwrap_or(1), }; warn!("Starting output scan from height {} ...", start_height); let result = owner_api.scan(keychain_mask, Some(start_height), args.delete_unconfirmed); @@ -1579,10 +1625,9 @@ where } } -/// Payment Proof Address +/// Show wallet's slatepack address. pub fn address( owner_api: &mut Owner, - g_args: &GlobalArgs, keychain_mask: Option<&SecretKey>, ) -> Result<(), Error> where @@ -1590,16 +1635,30 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - // Just address at derivation index 0 for now - let address = owner_api.get_slatepack_address(keychain_mask, 0)?; + // Just address at derivation index 0 for now, + // cause sender encrypts message for address, + // and we don't know its derivation path index. + let address = owner_api.get_slatepack_address(keychain_mask, SlatepackAddressIndex(0))?; + let account = account_label(owner_api)?; println!(); - println!("Address for account - {}", g_args.account); + println!("Address for account - {}", account); println!("-------------------------------------"); println!("{}", address); println!(); Ok(()) } +/// Get current account label. +fn account_label(owner_api: &mut Owner) -> Result +where + L: WalletLCProvider<'static, C, K> + 'static, + C: NodeClient + 'static, + K: keychain::Keychain + 'static, +{ + wallet_lock!(owner_api.wallet_inst, w); + Ok(w.active_account().label) +} + /// Proof Export Args pub struct ProofExportArgs { pub output_file: String, @@ -1765,7 +1824,9 @@ where error!("Proof not valid: {}", e); return Err(Error::from(e)); } - let my_address = owner_api.get_slatepack_address(keychain_mask, 0)?.pub_key; + let my_address = owner_api + .get_slatepack_address(keychain_mask, SlatepackAddressIndex(0))? + .pub_key; print_proof_verified( file.proof.sender_address == my_address, file.recipient_address.pub_key == my_address, @@ -1982,7 +2043,7 @@ impl ContractSetupArgs { } } -fn read_slatepack(reader: &mut impl BufRead) -> io::Result { +fn read_contract_slatepack(reader: &mut impl BufRead) -> io::Result { let mut message = String::new(); let mut periods = 0; // Header, payload and footer each end with a period @@ -2019,7 +2080,7 @@ where { let recipient = slatepack_recipient(args.counterparty_addr.as_deref())?; display::print_status("Paste slatepack:", args.as_json); - let slatepack_msg = read_slatepack(&mut io::stdin().lock()) + let slatepack_msg = read_contract_slatepack(&mut io::stdin().lock()) .map_err(|e| libwallet::Error::GenericError(format!("Failed to read from stdin: {}", e)))?; let (slate, sender, _) = parse_slatepack_with_mode(owner_api, keychain_mask, None, Some(slatepack_msg))?; @@ -2155,11 +2216,6 @@ mod contract_tests { use libwallet::{Slatepack, SlatepackArmor}; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); for size in [32, 4096] { let mut slatepack = Slatepack::default(); slatepack.payload = vec![1; size]; @@ -2173,10 +2229,10 @@ mod contract_tests { format!("{}\n", serde_json::to_string_pretty(&slatepack).unwrap()), ] { let mut input = io::Cursor::new(format!("\n \t\n{}next input\n", encoded)); - let message = read_slatepack(&mut input).unwrap(); + let message = read_contract_slatepack(&mut input).unwrap(); assert_eq!(message, encoded); assert_eq!( - packer.deser_slatepack(message.as_bytes(), false).unwrap(), + owner::parse_slatepack(message.as_bytes()).unwrap(), slatepack ); let mut remaining = String::new(); @@ -2186,15 +2242,15 @@ mod contract_tests { } let mut input = io::Cursor::new("{invalid}\nnext input\n"); - assert_eq!(read_slatepack(&mut input).unwrap(), "{invalid}\n"); + assert_eq!(read_contract_slatepack(&mut input).unwrap(), "{invalid}\n"); let incomplete_json = "{\n\"payload\":"; assert_eq!( - read_slatepack(&mut io::Cursor::new(incomplete_json)).unwrap(), + read_contract_slatepack(&mut io::Cursor::new(incomplete_json)).unwrap(), incomplete_json ); let incomplete = "BEGINSLATEPACK.\nunfinished"; - let message = read_slatepack(&mut io::Cursor::new(incomplete)).unwrap(); + let message = read_contract_slatepack(&mut io::Cursor::new(incomplete)).unwrap(); assert_eq!(message, incomplete); assert!(SlatepackArmor::decode(message.as_bytes()).is_err()); } @@ -2226,34 +2282,17 @@ mod contract_tests { let address = SlatepackAddress::new(&VerifyingKey::from(&key)); let slate = Slate::blank(2, false); - let plain = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }) - .create_slatepack(&slate) - .unwrap(); + let plain = slate.create_slatepack(None, vec![]).unwrap(); assert!(!plain.is_encrypted()); - let encrypted = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![address], - dec_key: None, - }) - .create_slatepack(&slate) - .unwrap(); + let encrypted = slate.create_slatepack(None, vec![address]).unwrap(); assert!(encrypted.is_encrypted()); let mut invalid = serde_json::to_value(&plain).unwrap(); invalid["mode"] = serde_json::json!(2); let data = serde_json::to_vec(&invalid).unwrap(); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); assert!(matches!( - packer.deser_slatepack(&data, false), + owner::parse_slatepack(&data), Err(libwallet::Error::SlatepackDeser(message)) if message.contains("Unsupported Slatepack mode: 2") )); @@ -2416,3 +2455,120 @@ mod contract_tests { )); } } + +pub struct MwixnetArgs { + pub server: OnionV3Address, + pub output: MwixnetOutput, + pub minimum_confirmations: u64, + pub params: MixnetReqCreationParams, +} + +pub enum MwixnetOutput { + Commitment(Commitment), + MinimumAmount(u64), + Max, +} + +fn confirm_mwixnet_response( + response: Result, libwallet::Error>, + tx_id: u32, +) -> Result<(), Error> { + let message = match response { + Ok(None) => { + println!("MWixnet request accepted (transaction {})", tx_id); + return Ok(()); + } + Ok(Some(message)) => format!("MWixnet rejected the request: {}", message), + Err(error) => error.to_string(), + }; + // The server may already have accepted the request + Err(Error::GenericError(format!( + "{}. Output remains locked as transaction {}. The server may already have accepted \ + the request. To cancel manually, use `cancel -i {}`.", + message, tx_id, tx_id + ))) +} + +pub fn mwixnet( + owner_api: &mut Owner, + keychain_mask: Option<&SecretKey>, + args: MwixnetArgs, +) -> Result<(), Error> +where + L: WalletLCProvider<'static, C, K> + 'static, + C: NodeClient + 'static, + K: keychain::Keychain + 'static, +{ + let height = owner_api.node_height(keychain_mask)?.height; + let (refreshed, outputs) = owner_api.retrieve_outputs(keychain_mask, false, true, None)?; + if !refreshed { + return Err(Error::GenericError( + "Could not refresh wallet outputs. MWixnet request was not created".to_string(), + )); + } + let eligible = |output: &&OutputCommitMapping| { + output + .output + .eligible_to_spend(height, args.minimum_confirmations.max(1)) + }; + let output = match &args.output { + MwixnetOutput::Commitment(commitment) => outputs + .iter() + .find(|output| output.commit == *commitment && eligible(output)), + MwixnetOutput::MinimumAmount(amount) => outputs + .iter() + .filter(eligible) + .filter(|output| output.output.value >= *amount) + .min_by_key(|output| output.output.value), + MwixnetOutput::Max => outputs + .iter() + .filter(eligible) + .max_by_key(|output| output.output.value), + } + .ok_or_else(|| Error::GenericError("No eligible MWixnet output was found".to_string()))?; + let commitment = output.commit; + println!( + "Selected MWixnet output {} with value {}", + commitment.to_hex(), + core::amount_to_hr_string(output.output.value, false) + ); + + let creation = owner_api.create_mwixnet_req(keychain_mask, &args.params, &commitment, true)?; + match creation.tx_id { + None => Err(Error::GenericError( + "MWixnet request was created without locking its output".to_string(), + )), + Some(tx_id) => { + let res = owner_api.send_mwixnet_req(&creation.request, args.server); + confirm_mwixnet_response(res, tx_id) + } + } +} + +#[cfg(test)] +mod tests { + use super::confirm_mwixnet_response; + + #[test] + fn mwixnet_response_reports_uncertain_transactions_as_locked() { + assert!(confirm_mwixnet_response(Ok(None), 3).is_ok()); + let error = + confirm_mwixnet_response(Ok(Some("invalid response".to_string())), 3).unwrap_err(); + assert!(error + .to_string() + .contains("remains locked as transaction 3")); + assert!(error.to_string().contains("cancel -i 3")); + let error = confirm_mwixnet_response( + Err(super::libwallet::Error::GenericError( + "transport failed".into(), + )), + 4, + ) + .unwrap_err() + .to_string(); + assert!(error.contains("transport failed")); + assert!(error.contains("remains locked as transaction 4")); + assert!(error.contains("cancel -i 4")); + assert!(error.contains("may already have accepted")); + } +} diff --git a/controller/src/controller.rs b/controller/src/controller.rs index ea941da..1ced4d8 100644 --- a/controller/src/controller.rs +++ b/controller/src/controller.rs @@ -21,8 +21,8 @@ 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, - WalletLCProvider, GRIN_BLOCK_HEADER_VERSION, + address, Error, NodeClient, NodeVersionInfo, Slate, SlatepackAddress, WalletLCProvider, + GRIN_BLOCK_HEADER_VERSION, }; use crate::util::secp::key::SecretKey; use crate::util::{from_hex, static_secp_instance, to_base64, Mutex}; @@ -55,6 +55,7 @@ use grin_wallet_config::config::{ }; use grin_wallet_impls::tor::arti::{start_tor_service, stop_tor_service}; use grin_wallet_impls::tor::process::TorProcess; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; use http_body_util::{BodyExt, Full}; use hyper::body::Incoming; use tokio::sync::mpsc; @@ -102,29 +103,23 @@ fn init_tor_listener( let mut hm_tor_bridge: HashMap = HashMap::new(); 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()))?; + .map_err(|e| Error::TorConfig(format!("{}", e)))?; hm_tor_bridge = bridge_config .to_hashmap() - .map_err(|e| Error::TorConfig(format!("{}", e).into()))?; + .map_err(|e| Error::TorConfig(format!("{}", e)))?; } let mut hm_tor_poxy: HashMap = HashMap::new(); 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()))?; + .map_err(|e| Error::TorConfig(format!("{}", e)))?; hm_tor_poxy = proxy_config .to_hashmap() - .map_err(|e| Error::TorConfig(format!("{}", e).into()))?; + .map_err(|e| Error::TorConfig(format!("{}", e)))?; } - tor_config::output_tor_listener_config( - &tor_dir, - addr, - &vec![sec_key], - hm_tor_bridge, - hm_tor_poxy, - ) - .map_err(|e| Error::TorConfig(format!("{:?}", e).into()))?; + tor_config::output_tor_listener_config(&tor_dir, addr, &[sec_key], hm_tor_bridge, hm_tor_poxy) + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; // Start TOR process process .torrc_path(&format!("{}/torrc", tor_dir)) @@ -136,27 +131,10 @@ fn init_tor_listener( 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: Arc>>>, - keychain_mask: Option<&SecretKey>, - config_path: PathBuf, - f: F, -) -> Result<(), Error> -where - L: WalletLCProvider<'static, C, K> + 'static, - F: FnOnce(&mut Owner, Option<&SecretKey>) -> Result<(), Error>, - C: NodeClient + 'static, - K: Keychain + 'static, -{ - 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>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, config_path: PathBuf, keychain_mask: Option, f: F, @@ -196,9 +174,9 @@ where K: Keychain + 'static, { let mut router = Router::new(); - if api_secret.is_some() { + if let Some(api_secret) = api_secret { let api_basic_auth = - "Basic ".to_string() + &to_base64(&("grin:".to_string() + &api_secret.unwrap())); + "Basic ".to_string() + &to_base64(&("grin:".to_string() + &api_secret)); let basic_auth_middleware = Arc::new(BasicAuthMiddleware::new( api_basic_auth, &GRIN_OWNER_BASIC_REALM, @@ -250,8 +228,9 @@ where /// Listener version, providing same API but listening for requests on a /// port and wrapping the calls +#[allow(clippy::too_many_arguments)] pub fn foreign_listener( - wallet: Arc + 'static>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, config_path: PathBuf, bridge: Option, use_tor: Option, @@ -277,10 +256,11 @@ where 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 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 sec_key = + address::address_from_derivation_path(&k, &parent_key_id, SlatepackAddressIndex(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)))?; @@ -419,7 +399,7 @@ where K: Keychain + 'static, { /// Wallet instance - pub wallet: Arc + 'static>>>, + pub wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, /// Handle to Owner API owner_api: Arc>, @@ -481,7 +461,7 @@ impl OwnerV3Helpers { val: &serde_json::Value, new_key: Option, ) { - if let Some(_) = val["result"]["Ok"].as_str() { + if val["result"]["Ok"].as_str().is_some() { let mut share_key_ref = key.lock(); *share_key_ref = new_key; } @@ -522,7 +502,7 @@ impl OwnerV3Helpers { .as_json_value() })?; let id = enc_req.id.clone(); - let res = enc_req.decrypt(&shared_key).map_err(|e| { + let res = enc_req.decrypt(shared_key).map_err(|e| { EncryptionErrorResponse::new(1, -32002, &format!("Decryption error: {}", e)) .as_json_value() })?; @@ -537,7 +517,7 @@ impl OwnerV3Helpers { ) -> Result { let share_key_ref = key.lock(); let shared_key = share_key_ref.as_ref().unwrap(); - let enc_res = EncryptedResponse::from_json(id, res, &shared_key).map_err(|e| { + let enc_res = EncryptedResponse::from_json(id, res, shared_key).map_err(|e| { EncryptionErrorResponse::new(1, -32003, &format!("EncryptionError: {}", e)) .as_json_value() })?; @@ -595,10 +575,7 @@ impl OwnerV3Helpers { retval } else if val["result"]["Err"].is_string() { let parsed = serde_json::from_value::(val["result"]["Err"].clone()); - match parsed { - Ok(p) => Some(p), - Err(_) => None, - } + parsed.ok() } else { None }; @@ -756,7 +733,7 @@ where K: Keychain + 'static, { /// Wallet instance. - pub wallet: Arc + 'static>>>, + pub wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, /// Wallet configuration path. pub config_path: ConfigPath, /// Keychain mask @@ -773,7 +750,7 @@ where { /// Create a new foreign API handler for GET methods pub fn new( - wallet: Arc + 'static>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, config_path: ConfigPath, keychain_mask: Arc>>, test_mode: bool, @@ -804,7 +781,7 @@ where async fn handle_post_request( req: Request, mask: Option, - wallet: Arc + 'static>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, config_path: ConfigPath, test_mode: bool, ) -> Result, Error> { diff --git a/controller/src/display.rs b/controller/src/display.rs index 2f8dd4f..061e6e5 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -12,17 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::core::core::amount_to_hr_string; use crate::core::core::FeeFields; -use crate::core::core::{self, amount_to_hr_string, Inputs, OutputFeatures}; +use crate::core::core::{self, Inputs, OutputFeatures}; use crate::core::global; use crate::libwallet::contract::types::{ContractView, OwnCommitmentStatus}; use crate::libwallet::{ - AcctPathMapping, Error, OutputCommitMapping, OutputStatus, Slate, SlatepackAddress, TxLogEntry, - ViewWallet, WalletInfo, + address, AcctPathMapping, Error, OutputCommitMapping, OutputStatus, Slate, SlatepackAddress, + TxLogEntry, TxLogEntryType, ViewWallet, WalletInfo, }; use crate::util::secp::pedersen::Commitment; use crate::util::ToHex; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; use prettytable; +use prettytable::format::{FormatBuilder, LinePosition, LineSeparator}; use std::io::prelude::Write; use term; @@ -53,9 +56,9 @@ pub fn outputs( return Ok(()); } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let mut table = table!(); @@ -72,7 +75,7 @@ pub fn outputs( ]); for m in outputs { - let commit = format!("{}", m.commit.as_ref().to_hex()); + let commit = m.commit.as_ref().to_hex(); let index = match m.output.mmr_index { None => "None".to_owned(), Some(t) => t.to_string(), @@ -88,7 +91,7 @@ pub fn outputs( }; let num_confirmations = format!("{}", m.output.num_confirmations(cur_height)); - let value = format!("{}", core::amount_to_hr_string(m.output.value, false)); + let value = amount_to_hr_string(m.output.value, false); let tx = match m.output.tx_log_entry { None => "".to_owned(), Some(t) => t.to_string(), @@ -128,7 +131,7 @@ pub fn outputs( if !validated { println!( "\nWARNING: Wallet failed to verify data. \ - The above is from local cache and possibly invalid! \ + The above is from local cache and possibly invalid! \ (is your `grin server` offline or broken?)" ); } @@ -154,73 +157,93 @@ pub fn txs( return Ok(()); } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let mut table = table!(); - table.set_titles(row![ - bMG->"Id", - bMG->"Type", - bMG->"State", - bMG->"Shared Transaction Id", - bMG->"Creation Time", - bMG->"TTL Cutoff Height", - bMG->"Confirmed?", - bMG->"Confirmation Time", - bMG->"Num. \nInputs", - bMG->"Num. \nOutputs", - bMG->"Amount \nCredited", - bMG->"Amount \nDebited", - bMG->"Fee", - bMG->"Net \nDifference", - bMG->"Payment \nProof", - bMG->"Kernel", - bMG->"Tx \nData", - ]); + table.set_titles(if dark_background_color_scheme { + row![ + bMG->"Id", + bMG->"Type (State)", + bMG->"Shared Transaction Id \nKernel", + bMG->"Creation Time \nConfirmation Time", + bMG->"Payment Proof \nTTL Cutoff Height", + bMG->"Inputs \nOutputs", + bMG->"Credited \nDebited", + bMG->"Fee \nDifference", + ] + } else { + row![ + bFD ->"Id", + bFD->"Type (State)", + bFD->"Shared Transaction Id \nKernel", + bFD->"Creation Time \nConfirmation Time", + bFD->"Payment Proof \nTTL Cutoff Height", + bFD->"Inputs \nOutputs", + bFD->"Credited \nDebited", + bFD->"Fee \nDifference", + ] + }); - for t in txs { + for (i, t) in txs.iter().enumerate() { let id = format!("{}", t.id); let slate_id = match t.tx_slate_id { Some(m) => format!("{}", m), None => "None".to_owned(), }; - let slate_state = match t.tx_slate_state.as_ref() { - Some(m) => format!("{}", m), - None => "None".to_owned(), + + let entry_type = (match t.tx_type { + TxLogEntryType::ConfirmedCoinbase => "Coinbase", + TxLogEntryType::TxReceived => "Received Tx", + TxLogEntryType::TxSent => "Sent Tx", + TxLogEntryType::TxReceivedCancelled => "Received Tx", + TxLogEntryType::TxSentCancelled => "Sent Tx", + TxLogEntryType::TxReverted => "Received Tx", + TxLogEntryType::TxSelfSpend | TxLogEntryType::TxSelfSpendCancelled => "Self Spend", + }) + .to_string(); + let entry_type_state = match t.tx_slate_state.as_ref() { + None => entry_type.to_string(), + Some(s) => format!("{} ({})", entry_type, s), }; - let entry_type = format!("{}", t.tx_type); + let entry_type_desc = (match t.tx_type { + TxLogEntryType::ConfirmedCoinbase => "Confirmed", + TxLogEntryType::TxReceived => "", + TxLogEntryType::TxSent => "", + TxLogEntryType::TxReceivedCancelled => "Cancelled", + TxLogEntryType::TxSentCancelled => "Cancelled", + TxLogEntryType::TxReverted => "Reverted", + TxLogEntryType::TxSelfSpend => "", + TxLogEntryType::TxSelfSpendCancelled => "Cancelled", + }) + .to_string(); let creation_ts = format!("{}", t.creation_ts.format("%Y-%m-%d %H:%M:%S")); let ttl_cutoff_height = match t.ttl_cutoff_height { - Some(b) => format!("{}", b), + Some(b) => b.to_string(), None => "None".to_owned(), }; let confirmation_ts = match t.confirmation_ts { Some(m) => format!("{}", m.format("%Y-%m-%d %H:%M:%S")), None => "None".to_owned(), }; - let confirmed = format!("{}", t.confirmed); let num_inputs = format!("{}", t.num_inputs); let num_outputs = format!("{}", t.num_outputs); - let amount_debited_str = core::amount_to_hr_string(t.amount_debited, true); - let amount_credited_str = core::amount_to_hr_string(t.amount_credited, true); + let amount_debited_str = amount_to_hr_string(t.amount_debited, true); + let amount_credited_str = amount_to_hr_string(t.amount_credited, true); let fee = match t.fee { - Some(f) => format!("{}", core::amount_to_hr_string(f.fee(), true)), + Some(f) => amount_to_hr_string(f.fee(), true), None => "None".to_owned(), }; let net_diff = if t.amount_credited >= t.amount_debited { - core::amount_to_hr_string(t.amount_credited - t.amount_debited, true) + amount_to_hr_string(t.amount_credited - t.amount_debited, true) } else { format!( "-{}", - core::amount_to_hr_string(t.amount_debited - t.amount_credited, true) + amount_to_hr_string(t.amount_debited - t.amount_credited, true) ) }; - let tx_data = match t.stored_tx { - Some(_) => "Yes".to_owned(), - None => "None".to_owned(), - }; let kernel_excess = match t.kernel_excess { Some(e) => { let excess: &[u8] = e.0.as_ref(); @@ -235,96 +258,76 @@ pub fn txs( if dark_background_color_scheme { table.add_row(row![ bFC->id, - bFC->entry_type, - bFC->slate_state, + bFC->entry_type_state, bFC->slate_id, bFB->creation_ts, - bFB->ttl_cutoff_height, - bFC->confirmed, - bFB->confirmation_ts, + bFC->payment_proof, bFC->num_inputs, - bFC->num_outputs, bFG->amount_credited_str, - bFR->amount_debited_str, bFR->fee, - bFY->net_diff, - bfG->payment_proof, + ]); + table.add_row(row![ + bFD->"", + bFC->entry_type_desc, bFB->kernel_excess, - bFb->tx_data, + bFB->confirmation_ts, + bFB->ttl_cutoff_height, + bFC->num_outputs, + bFR->amount_debited_str, + bFY->net_diff, ]); } else { - if t.confirmed { - table.add_row(row![ - bFD->id, - bFb->entry_type, - bFD->slate_id, - bFB->creation_ts, - bFg->confirmed, - bFB->confirmation_ts, - bFD->num_inputs, - bFD->num_outputs, - bFG->amount_credited_str, - bFD->amount_debited_str, - bFD->fee, - bFG->net_diff, - bfG->payment_proof, - bFB->kernel_excess, - bFB->tx_data, - ]); - } else { - table.add_row(row![ - bFD->id, - bFb->entry_type, - bFD->slate_id, - bFB->creation_ts, - bFR->confirmed, - bFB->confirmation_ts, - bFD->num_inputs, - bFD->num_outputs, - bFG->amount_credited_str, - bFD->amount_debited_str, - bFD->fee, - bFG->net_diff, - bfG->payment_proof, - bFB->kernel_excess, - bFB->tx_data, - ]); - } + table.add_row(row![ + bFD->id, + bFb->entry_type_state, + bFD->slate_id, + bFB->creation_ts, + bFD->payment_proof, + bFD->num_inputs, + bFG->amount_credited_str, + bFR->fee, + ]); + table.add_row(row![ + bFD->"", + bFb->entry_type_desc, + bFB->kernel_excess, + bFB->confirmation_ts, + bFB->ttl_cutoff_height, + bFD->num_outputs, + bFR->amount_debited_str, + bFG->net_diff, + ]); + } + if i != txs.len() - 1 { + table.add_empty_row(); } } - table.set_format(*prettytable::format::consts::FORMAT_NO_COLSEP); + table.set_format(*prettytable::format::consts::FORMAT_NO_LINESEP_WITH_TITLE); table.printstd(); println!(); if !validated && include_status { println!( "\nWARNING: Wallet failed to verify data. \ - The above is from local cache and possibly invalid! \ + The above is from local cache and possibly invalid! \ (is your `grin server` offline or broken?)" ); } Ok(()) } -pub fn view_wallet_balance(w: ViewWallet, cur_height: u64, dark_background_color_scheme: bool) { +pub fn view_wallet_balance(w: ViewWallet, cur_height: u64, _dark_background_color_scheme: bool) { println!( "\n____ View Wallet Summary Info - Block Height: {} ____\n Rewind Hash - {}\n", cur_height, w.rewind_hash ); let mut table = table!(); - if dark_background_color_scheme { - table.add_row(row![ - bFG->"Total Balance", - FG->amount_to_hr_string(w.total_balance, false) - ]); - } else { - table.add_row(row![ - bFG->"Total Balance", - FG->amount_to_hr_string(w.total_balance, false) - ]); - }; + table.add_row(row![ + bFG->"Total Balance", + FG->amount_to_hr_string(w.total_balance, false) + ]); table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); table.printstd(); println!(); @@ -344,9 +347,9 @@ pub fn view_wallet_output( } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let mut table = table!(); @@ -361,13 +364,13 @@ pub fn view_wallet_output( ]); for m in view_wallet.output_result { - let commit = format!("{}", m.commit); + let commit = m.commit.as_str(); let index = m.mmr_index; let height = format!("{}", m.height); let lock_height = format!("{}", m.lock_height); let is_coinbase = format!("{}", m.is_coinbase); let num_confirmations = format!("{}", m.num_confirmations(cur_height)); - let value = format!("{}", core::amount_to_hr_string(m.value, false)); + let value = amount_to_hr_string(m.value, false); if dark_background_color_scheme { table.add_row(row![ @@ -419,11 +422,11 @@ pub fn info( ]); if wallet_info.amount_reverted > 0 { table.add_row(row![ - Fr->format!("Reverted"), + Fr->"Reverted", Fr->amount_to_hr_string(wallet_info.amount_reverted, false) ]); } - // Only dispay "Immature Coinbase" if we have related outputs in the wallet. + // Only display "Immature Coinbase" if we have related outputs in the wallet. // This row just introduces confusion if the wallet does not receive coinbase rewards. if wallet_info.amount_immature > 0 { table.add_row(row![ @@ -436,7 +439,7 @@ pub fn info( FY->amount_to_hr_string(wallet_info.amount_awaiting_confirmation, false) ]); table.add_row(row![ - bFB->format!("Awaiting Finalization"), + bFB->"Awaiting Finalization", FB->amount_to_hr_string(wallet_info.amount_awaiting_finalization, false) ]); table.add_row(row![ @@ -458,11 +461,11 @@ pub fn info( ]); if wallet_info.amount_reverted > 0 { table.add_row(row![ - Fr->format!("Reverted"), + Fr->"Reverted", Fr->amount_to_hr_string(wallet_info.amount_reverted, false) ]); } - // Only dispay "Immature Coinbase" if we have related outputs in the wallet. + // Only display "Immature Coinbase" if we have related outputs in the wallet. // This row just introduces confusion if the wallet does not receive coinbase rewards. if wallet_info.amount_immature > 0 { table.add_row(row![ @@ -493,7 +496,7 @@ pub fn info( if !validated { println!( "\nWARNING: Wallet failed to verify data against a live chain. \ - The above is from local cache and only valid up to the given height! \ + The above is from local cache and only valid up to the given height! \ (is your `grin server` offline or broken?)" ); } @@ -543,48 +546,71 @@ pub fn estimate( /// Display list of wallet accounts in a pretty way pub fn accounts(acct_mappings: Vec) { - println!("\n____ Wallet Accounts ____\n",); + println!("\n____ Wallet Accounts ____\n"); let mut table = table!(); table.set_titles(row![ mMG->"Name", - bMG->"Parent BIP-32 Derivation Path", + bMG->"Parent Output Key", + bMG->"Slatepack Address (Index 0)", + bMG->"Spendable balance", ]); for m in acct_mappings { + let slatepack_path = + address::address_derivation_path(&m.path, SlatepackAddressIndex(0)).to_bip_32_string(); + let spendable = if let Some(info) = m.info { + amount_to_hr_string(info.amount_currently_spendable, true) + } else { + "-".to_string() + }; table.add_row(row![ bFC->m.label, bGC->m.path.to_bip_32_string(), + bGC->slatepack_path, + bGC->spendable, ]); } - table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); + table.set_format( + FormatBuilder::new() + .column_separator('|') + .separators( + &[LinePosition::Top, LinePosition::Title], + LineSeparator::new('-', '+', '+', '+'), + ) + .padding(1, 1) + .build(), + ); + let width = table.to_string().find('\n').unwrap_or(0); + println!("{:^1$}", "BIP-32 Derivation Path", width); table.printstd(); + println!("Balances use local data and may be out of date."); println!(); } /// Display individual Payment Proof pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { - let title = format!("Payment Proof - Transaction '{}'", tx.id,); + let title = format!("Payment Proof - Transaction '{}'", tx.id); println!(); if term::stdout().is_none() { println!("Could not open terminal"); return Ok(()); } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let pp = match &tx.payment_proof { None => { - writeln!(t, "None").unwrap(); - t.reset().unwrap(); + writeln!(t, "None")?; + let _ = t.reset(); return Ok(()); } Some(p) => p.clone(), }; - t.fg(term::color::WHITE).unwrap(); - writeln!(t).unwrap(); + let _ = t.fg(term::color::WHITE); + writeln!(t)?; let receiver_signature = match pp.receiver_signature { Some(s) => { let sig_bytes = s.to_bytes(); @@ -615,20 +641,18 @@ pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { t, "Receiver Address: {}", SlatepackAddress::new(&pp.receiver_address) - ) - .unwrap(); - writeln!(t, "Receiver Signature: {}", receiver_signature).unwrap(); - writeln!(t, "Amount: {}", amount).unwrap(); - writeln!(t, "Kernel Excess: {}", kernel_excess).unwrap(); + )?; + writeln!(t, "Receiver Signature: {}", receiver_signature)?; + writeln!(t, "Amount: {}", amount)?; + writeln!(t, "Kernel Excess: {}", kernel_excess)?; writeln!( t, "Sender Address: {}", SlatepackAddress::new(&pp.sender_address) - ) - .unwrap(); - writeln!(t, "Sender Signature: {}", sender_signature).unwrap(); + )?; + writeln!(t, "Sender Signature: {}", sender_signature)?; - t.reset().unwrap(); + let _ = t.reset(); println!(); diff --git a/controller/tests/accounts.rs b/controller/tests/accounts.rs index 9a47e41..6b1f421 100644 --- a/controller/tests/accounts.rs +++ b/controller/tests/accounts.rs @@ -19,7 +19,6 @@ 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}; @@ -49,10 +48,11 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -62,10 +62,11 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -79,183 +80,196 @@ 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( - 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(()) - }, - )?; + { + let accounts = api1.accounts_info(mask1, 2)?; + assert_eq!(accounts[0].label, "default"); + assert_eq!(accounts[0].path, ExtKeychain::derive_key_id(2, 0, 0, 0, 0)); + } // add some accounts - 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(()) - }, - )?; + { + let new_path = api1.create_account_path(mask1, "account1").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); + let new_path = api1.create_account_path(mask1, "account2").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); + let new_path = api1.create_account_path(mask1, "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 = api1.create_account_path(mask1, "account1"); + assert!(res.is_err()); + // Check missing flags and temporary account changes + for saved in [None, Some(true)] { + { + wallet_inst!(wallet1, w); + let mut account = w.get_acct_path("default".to_owned())?.unwrap(); + account.current = saved; + let mut batch = w.batch(mask1)?; + batch.save_acct_path(account)?; + batch.commit()?; + } + for active in ["default", "account1"] { + { + wallet_inst!(wallet1, w); + w.set_account_by_name(active)?; + } + for accounts in [api1.accounts(mask1)?, api1.accounts_info(mask1, 2)?] { + assert_eq!(accounts.len(), 4); + assert_eq!(accounts[0].label, active); + for account in accounts { + assert_eq!(account.current, Some(account.label == active)); + } + } + // Keep the saved selection unchanged + wallet_inst!(wallet1, w); + for account in w.acct_path_iter()? { + let expected = if account.label == "default" { + saved + } else { + None + }; + assert_eq!(account.current, expected); + } + } + } + // Restore the saved account on reopen + api1.set_active_account(mask1, "account1")?; + { + wallet_inst!(wallet1, w); + w.set_account_by_name("default")?; + assert_eq!(w.active_account().label, "default"); + } + api1.close_wallet(None)?; + api1.open_wallet(None, "".into(), false)?; + { + wallet_inst!(wallet1, w); + assert_eq!(w.active_account().label, "account1"); + } + } // add account to wallet 2 - 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(()) - }, - )?; + { + let new_path = api2.create_account_path(mask2, "listener_account").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); + } // Default wallet 2 to listen on that account { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("listener_account")?; + w.set_account_by_name("listener_account")?; } // Mine into two different accounts in the same wallet { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; assert_eq!(w.parent_key_id(), ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); } let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 7, false); { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account2")?; + w.set_account_by_name("account2")?; assert_eq!(w.parent_key_id(), ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); } 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( - 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(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 5); + } // now check second account { - // let mut w_lock = wallet1.lock(); - // let lc = w_lock.lc_provider()?; - // let w = lc.wallet_inst()?; wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } - 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(()) - }, - )?; + { + let labels: Vec<_> = api1 + .accounts_info(mask1, 2)? + .into_iter() + .map(|a| a.label) + .collect(); + assert_eq!(labels, ["account1", "default", "account2", "account3"]); + assert!(api1.accounts(mask1)?.iter().all(|a| a.info.is_none())); + for confirmations in [0, 1, 2, 10] { + let accounts = api1.accounts_info(mask1, confirmations)?; + assert_eq!(accounts[0].info.as_ref().unwrap().last_confirmed_height, 0); + assert_eq!(accounts[2].info.as_ref().unwrap().last_confirmed_height, 12); + for account in accounts { + api1.set_active_account(mask1, &account.label)?; + let (_, summary) = api1.retrieve_summary_info(mask1, false, confirmations)?; + assert_eq!(account.info.unwrap(), summary); + } + api1.set_active_account(mask1, "account1")?; + } + // check last confirmed height on this account is different from above (should be 0) + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 7); + } // should be nothing in default account { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("default")?; + w.set_account_by_name("default")?; + } + { + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 0); } - 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")?; + w.set_account_by_name("account1")?; + } + { + 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 = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, false)?; } - 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( - 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(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 9); + } // Use the requested account's stored height { wallet_inst!(wallet1, w); @@ -268,61 +282,43 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // other account should be untouched { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account2")?; + w.set_account_by_name("account2")?; + } + { + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 12); + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + println!("{:?}", txs); + assert_eq!(txs.len(), 5); } - 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( - 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(()) - }, - )?; + { + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 13); + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + } // Default account on wallet 2 should be untouched { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("default")?; + w.set_account_by_name("default")?; + } + { + let (_, wallet2_info) = api2.retrieve_summary_info(mask2, false, 1)?; + assert_eq!(wallet2_info.last_confirmed_height, 0); + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, 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) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 0); } - 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 7120e44..35fa286 100644 --- a/controller/tests/build_chain.rs +++ b/controller/tests/build_chain.rs @@ -21,9 +21,8 @@ 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 self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; use rand::Rng; use std::sync::atomic::Ordering; @@ -48,9 +47,10 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); debug!("Mask1: {:?}", mask1); create_wallet_and_add!( client2, @@ -60,9 +60,10 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); debug!("Mask2: {:?}", mask2); // Set the wallet proxy listener running @@ -74,25 +75,8 @@ 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; + api1.stop_updater()?; + api2.stop_updater()?; // few values to keep things shorter let reward = core::consensus::REWARD; @@ -105,22 +89,14 @@ 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( - 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 (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 spendable - {}", + wallet1_info.amount_currently_spendable + ); + if wallet1_info.amount_currently_spendable > reward { + wallet_1_has_funds = true; + } // 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; @@ -134,30 +110,21 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal let num_txs = rng.gen_range(0, 3); for _ in 0..num_txs { let amount: u64 = rng.gen_range(1, 10_000_000_001); - let mut slate = Slate::blank(1, false); debug!("Creating TX for {}", amount); - 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: 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)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + api1.finalize_tx(mask1, &slate)?; } } // let logging finish diff --git a/controller/tests/build_output.rs b/controller/tests/build_output.rs index 491e916..eaf6bd6 100644 --- a/controller/tests/build_output.rs +++ b/controller/tests/build_output.rs @@ -25,7 +25,6 @@ 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; @@ -37,7 +36,7 @@ use common::{clean_output_dir, create_wallet_proxy, setup}; fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Generate seed so we can verify the blinding factor is derived correctly let seed: [u8; 32] = thread_rng().gen(); - let keychain = ExtKeychain::from_seed(&seed, false).unwrap(); + let keychain = ExtKeychain::from_seed(&seed, false)?; let mnemonic = mnemonic::from_entropy(&seed).unwrap(); // Create a new proxy to simulate server and wallet responses @@ -52,10 +51,11 @@ fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error "wallet1", Some(ZeroingString::from(mnemonic)), &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -67,28 +67,19 @@ 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let built_output = sender_api.build_output(m, features, amount)?; + let built_output = api1.build_output(mask1, 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()?; - - Ok(()) - }, - )?; + let output = built_output.output; + assert_eq!(output.features(), features); + assert_eq!(output.commitment(), secp.commit(amount, key)?); + output.verify_proof()?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/check.rs b/controller/tests/check.rs index d526335..4d172e2 100644 --- a/controller/tests/check.rs +++ b/controller/tests/check.rs @@ -27,7 +27,6 @@ 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; @@ -66,9 +65,10 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -77,9 +77,10 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -89,34 +90,22 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { }); // few values to keep things shorter - let reward = core::consensus::REWARD; - let cm = global::coinbase_maturity() as u64; // assume all testing precedes soft fork height + let reward = consensus::REWARD; + let cm = global::coinbase_maturity(); // assume all testing precedes soft fork height // add some accounts - 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(()) - }, - )?; + { + api1.create_account_path(mask1, "named_account_1")?; + api1.create_account_path(mask1, "account_2")?; + api1.create_account_path(mask1, "account_3")?; + api1.set_active_account(mask1, "named_account_1")?; + } // add account to wallet 2 - 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(()) - }, - )?; + { + api2.create_account_path(mask2, "account_1")?; + api2.set_active_account(mask2, "account_1")?; + } // Do some mining let bh = 20u64; @@ -124,36 +113,21 @@ 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( - 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(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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) = api1.retrieve_txs(mask1, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_eq!(wallet1_info.total, c); + assert_eq!(txs.len(), bh as usize); + } // Accidentally delete some outputs - let mut w1_outputs_commits = vec![]; - 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_commits = api1.retrieve_outputs(mask1, false, true, None)?.1; let w1_outputs: Vec = w1_outputs_commits.into_iter().map(|m| m.output).collect(); { @@ -170,108 +144,54 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { } // check we have a problem now - 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(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_ne!(wallet1_info.total, c); // this should restore our missing outputs - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; // check our outputs match again - 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(()) - }, - )?; - + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.total, bh * reward); + // And check account names haven't been splatted + let accounts = api1.accounts(mask1)?; + assert_eq!(accounts.len(), 4); + assert!(api1.set_active_account(mask1, "account_1").is_err()); + assert!(api1.set_active_account(mask1, "named_account_1").is_ok()); + } // perform a transaction, but don't let it finish - 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(()) - }, - )?; + { + // 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 = api1.init_send_tx(mask1, args)?; + // output tx file + let send_file = format!("{}/part_tx_1.tx", test_dir); + PathToSlate(send_file.into()).put_tx(&slate, false)?; + api1.tx_lock_outputs(mask1, &slate)?; + } // check we're all locked - 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(()) - }, - )?; - + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.amount_currently_spendable, 0); // unlock/restore - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; // check spendable amount again - 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 (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -300,9 +220,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "miner", None, &mut wallet_proxy, - false + false, + _m_api ); - let miner_mask = (&miner_mask_i).as_ref(); + let miner_mask = miner_mask_i.as_ref(); // non-mining recipient wallets create_wallet_and_add!( @@ -313,9 +234,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet1", seed_phrase, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -324,9 +246,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet2", seed_phrase, &mut wallet_proxy, - false + false, + _api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // we'll restore into here create_wallet_and_add!( client3, @@ -336,9 +259,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet3", seed_phrase, &mut wallet_proxy, - false + false, + api3 ); - let mask3 = (&mask3_i).as_ref(); + let mask3 = mask3_i.as_ref(); // also restore into here create_wallet_and_add!( client4, @@ -348,9 +272,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet4", seed_phrase, &mut wallet_proxy, - false + false, + api4 ); - let mask4 = (&mask4_i).as_ref(); + let mask4 = mask4_i.as_ref(); // Simulate a recover from seed without restore into here create_wallet_and_add!( client5, @@ -360,10 +285,11 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet5", seed_phrase, &mut wallet_proxy, - false + false, + api5 ); //simulate a recover from seed without restore into here - let mask5 = (&mask5_i).as_ref(); + let mask5 = mask5_i.as_ref(); create_wallet_and_add!( client6, wallet6, @@ -372,9 +298,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet6", seed_phrase, &mut wallet_proxy, - false + false, + api6 ); - let mask6 = (&mask6_i).as_ref(); + let mask6 = mask6_i.as_ref(); create_wallet_and_add!( client7, @@ -384,9 +311,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet7", seed_phrase, &mut wallet_proxy, - false + false, + api7 ); - let mask7 = (&mask7_i).as_ref(); + let mask7 = mask7_i.as_ref(); create_wallet_and_add!( client8, wallet8, @@ -395,9 +323,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet8", seed_phrase, &mut wallet_proxy, - false + false, + api8 ); - let mask8 = (&mask8_i).as_ref(); + let mask8 = mask8_i.as_ref(); create_wallet_and_add!( client9, wallet9, @@ -406,9 +335,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet9", seed_phrase, &mut wallet_proxy, - false + false, + api9 ); - let mask9 = (&mask9_i).as_ref(); + let mask9 = mask9_i.as_ref(); create_wallet_and_add!( client10, wallet10, @@ -417,9 +347,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet10", seed_phrase, &mut wallet_proxy, - false + false, + api10 ); - let mask10 = (&mask10_i).as_ref(); + let mask10 = mask10_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -449,7 +380,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er miner_mask, m_client.clone(), "wallet1", - base_amount * 1 + base_amount )?; send_to_dest!( miner.clone(), @@ -468,18 +399,10 @@ 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( - 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(()) - }, - )?; + api1.scan(mask1, None, true)?; + let info = wallet_info!(wallet1.clone(), mask1)?; + assert_eq!(info.amount_currently_spendable, base_amount * 6); + assert_eq!(info.total, base_amount * 6); // send some funds to wallet 2 send_to_dest!( @@ -523,53 +446,21 @@ 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( - wallet3.clone(), - mask3, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, false)?; - Ok(()) - }, - )?; + api3.scan(mask3, None, false)?; - 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(()) - }, - )?; + let info = wallet_info!(wallet3.clone(), mask3)?; + let outputs = api3.retrieve_outputs(mask3, 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); // 2) scan should recover them into a single wallet - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; - 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(()) - }, - )?; + let info = wallet_info!(wallet1.clone(), mask1)?; + let outputs = api1.retrieve_outputs(mask1, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); // 3) If I recover from seed and start using the wallet without restoring, // scan should restore the older outputs @@ -601,41 +492,17 @@ 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( - 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(()) - }, - )?; + let info = wallet_info!(wallet4.clone(), mask4)?; + let outputs = api4.retrieve_outputs(mask4, true, false, None)?.1; + assert_eq!(outputs.len(), 9); + assert_eq!(info.amount_currently_spendable, base_amount * 45); - wallet::controller::owner_single_use( - wallet5.clone(), - mask5, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, false)?; - Ok(()) - }, - )?; + api5.scan(mask5, None, false)?; - 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(()) - }, - )?; + let info = wallet_info!(wallet5.clone(), mask5)?; + let outputs = api5.retrieve_outputs(mask5, true, false, None)?.1; + assert_eq!(outputs.len(), 9); + assert_eq!(info.amount_currently_spendable, base_amount * (45)); // 4) If I recover from seed and start using the wallet without restoring, // scan should restore the older outputs @@ -662,50 +529,20 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er )?; bh += 3; - let _ = test_framework::award_blocks_to_wallet( - &chain, - miner.clone(), - miner_mask, - cm as usize, - false, - ); + let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); bh += cm as u64; - 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(()) - }, - )?; + let info = wallet_info!(wallet6.clone(), mask6)?; + let outputs = api6.retrieve_outputs(mask6, true, false, None)?.1; + assert_eq!(outputs.len(), 12); + assert_eq!(info.amount_currently_spendable, base_amount * 78); - wallet::controller::owner_single_use( - wallet6.clone(), - mask6, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api6.scan(mask6, None, true)?; - 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(()) - }, - )?; + let info = wallet_info!(wallet6.clone(), mask6)?; + let outputs = api6.retrieve_outputs(mask6, true, false, None)?.1; + assert_eq!(outputs.len(), 12); + assert_eq!(info.amount_currently_spendable, base_amount * (78)); // 5) Start using same seed with a different account, amounts should // be distinct and restore should return funds from other account @@ -734,23 +571,15 @@ 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( - wallet7.clone(), - mask7, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - }, - )?; + api7.create_account_path(mask7, "account_1")?; + api7.set_active_account(mask7, "account_1")?; send_to_dest!( miner.clone(), miner_mask, m_client.clone(), "wallet7", - base_amount * 1 + base_amount )?; send_to_dest!( miner.clone(), @@ -772,57 +601,33 @@ 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( - 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(()) - }, - )?; + let info = wallet_info!(wallet7.clone(), mask7)?; + let outputs = api7.retrieve_outputs(mask7, true, false, None)?.1; + assert_eq!(outputs.len(), 3); + assert_eq!(info.amount_currently_spendable, base_amount * 6); + api7.set_active_account(mask7, "default")?; + let info = wallet_info!(wallet7.clone(), mask7)?; + let outputs = api7.retrieve_outputs(mask7, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); - 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(()) - }, - )?; + api8.scan(mask8, None, false)?; + let info = wallet_info!(wallet8.clone(), mask8)?; + let outputs = api8.retrieve_outputs(mask8, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); + api8.set_active_account(mask8, "account_1")?; + let info = wallet_info!(wallet8.clone(), mask8)?; + let outputs = api8.retrieve_outputs(mask8, true, false, None)?.1; + assert_eq!(outputs.len(), 3); + assert_eq!(info.amount_currently_spendable, base_amount * 6); // 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( - wallet9.clone(), - mask9, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - }, - )?; + api9.create_account_path(mask9, "account_1")?; + api9.set_active_account(mask9, "account_1")?; send_to_dest!( miner.clone(), @@ -848,53 +653,37 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; let _bh = bh; - 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); + let info = wallet_info!(wallet9.clone(), mask9)?; + let outputs = api9.retrieve_outputs(mask9, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); + api9.scan(mask9, None, true)?; + let info = wallet_info!(wallet9.clone(), mask9)?; + let outputs = api9.retrieve_outputs(mask9, 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(()) - }, - )?; + api9.set_active_account(mask9, "default")?; + let info = wallet_info!(wallet9.clone(), mask9)?; + let outputs = api9.retrieve_outputs(mask9, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); 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( - 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); + api10.scan(mask10, None, true)?; + api10.set_active_account(mask10, "account_1")?; + let info = wallet_info!(wallet10.clone(), mask10)?; + let outputs = api10.retrieve_outputs(mask10, 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(()) - }, - )?; + api10.set_active_account(mask10, "default")?; + let info = wallet_info!(wallet10.clone(), mask10)?; + let outputs = api10.retrieve_outputs(mask10, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -918,9 +707,10 @@ fn output_scanning_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + _api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); thread::spawn(move || { if let Err(e) = wallet_proxy.run() { error!("Wallet Proxy error: {}", e); @@ -952,7 +742,7 @@ fn output_scanning_impl(test_dir: &'static str) -> Result<(), libwallet::Error> ); assert_eq!(outputs.2.len(), 14); - // mid range + // mid-range let ranges = client1.height_range_to_pmmr_indices(5, Some(14))?; assert_eq!(ranges, (8, 25)); let outputs = client1.get_outputs_by_pmmr_index(ranges.0, Some(ranges.1), 1000)?; @@ -1002,9 +792,10 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); thread::spawn(move || { if let Err(e) = wallet_proxy.run() { @@ -1017,19 +808,10 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let mut output_commits = vec![]; - 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(()) - }, - )?; + let (_, info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, bh * reward); + let output_commits = api1.retrieve_outputs(mask1, false, true, None)?.1; { wallet_inst!(wallet1, w); @@ -1076,18 +858,10 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } assert!(batches > 1); - 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(()) - }, - )?; + let (_, restored_outputs) = api1.retrieve_outputs(mask1, false, true, None)?; + let (_, info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(info.total, bh * reward); + assert_eq!(restored_outputs.len(), bh as usize); stopper.store(false, Ordering::Relaxed); thread::sleep(Duration::from_millis(200)); @@ -1109,9 +883,10 @@ fn restore_corrupted_outputs_across_batches_impl( "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); thread::spawn(move || { if let Err(e) = wallet_proxy.run() { @@ -1124,18 +899,9 @@ fn restore_corrupted_outputs_across_batches_impl( let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let mut output_commits = vec![]; - 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(()) - }, - )?; + let (_, info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(info.total, bh * reward); + let output_commits = api1.retrieve_outputs(mask1, false, true, None)?.1; { wallet_inst!(wallet1, w); @@ -1173,30 +939,22 @@ fn restore_corrupted_outputs_across_batches_impl( assert_eq!(last_scanned.hash, ""); } - 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 (_, outputs_after_first_batch) = api1.retrieve_outputs(mask1, 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) = api1.retrieve_summary_info(mask1, true, 1)?; + let (_, restored_outputs) = api1.retrieve_outputs(mask1, 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)); 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 47e6db6..be3269e 100644 --- a/controller/tests/common/mod.rs +++ b/controller/tests/common/mod.rs @@ -21,6 +21,7 @@ use grin_chain as chain; use grin_core as core; use grin_keychain as keychain; use grin_util as util; +use std::env; use self::core::core::{FeeFields, Inputs, KernelFeatures, OutputFeatures}; use self::core::global; @@ -28,6 +29,8 @@ use self::core::global::ChainTypes; use self::keychain::{ExtKeychain, Keychain}; use self::libwallet::WalletInst; use chain::Chain; +use grin_wallet_api::Owner; +use grin_wallet_config::{initial_setup_wallet, GRIN_WALLET_DIR}; use grin_wallet_controller::Error; use impls::test_framework::{self, LocalWalletClient, WalletProxy}; use impls::{DefaultLCProvider, DefaultWalletImpl}; @@ -49,9 +52,9 @@ macro_rules! wallet_inst { #[macro_export] macro_rules! create_wallet_and_add { - ($client:ident, $wallet: ident, $mask: ident, $test_dir: expr, $name: expr, $seed_phrase: expr, $proxy: expr, $create_mask: expr) => { + ($client:ident, $wallet: ident, $mask: ident, $test_dir: expr, $name: expr, $seed_phrase: expr, $proxy: expr, $create_mask: expr, $owner_api: ident) => { let $client = LocalWalletClient::new($name, $proxy.tx.clone()); - let ($wallet, $mask) = common::create_local_wallet( + let ($wallet, $mask, $owner_api) = common::create_local_wallet( $test_dir, $name, $seed_phrase.clone(), @@ -121,12 +124,7 @@ pub fn roundtrip_slate( slate: &libwallet::Slate, version: u16, ) -> Result { - let packer = libwallet::Slatepacker::new(libwallet::SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - let slate = packer.get_slate(&packer.create_slatepack(slate)?)?; + let slate = slate.create_slatepack(None, vec![])?.get_slate()?; assert_eq!(slate.version_info.version, version); Ok(slate) } @@ -260,6 +258,7 @@ pub fn create_wallet_proxy( WalletProxy::new(test_dir) } +#[allow(clippy::type_complexity)] pub fn create_local_wallet( test_dir: &str, name: &str, @@ -267,20 +266,25 @@ pub fn create_local_wallet( client: LocalWalletClient, create_mask: bool, ) -> ( - Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, >, Option, + Owner, LocalWalletClient, ExtKeychain>, ) { + let mut current_dir; + current_dir = env::current_dir().unwrap_or_else(|e| { + panic!("Error creating config file: {}", e); + }); + current_dir.push(test_dir); + current_dir.push(name); + let config = + initial_setup_wallet(&ChainTypes::AutomatedTesting, Some(current_dir), true).unwrap(); + let mut wallet_config = config.clone().members.wallet; + let mut wallet = Box::new(DefaultWalletImpl::::new(client).unwrap()) as Box< dyn WalletInst< @@ -290,13 +294,25 @@ pub fn create_local_wallet( >, >; let lc = wallet.lc_provider().unwrap(); - let _ = lc.set_top_level_directory(&format!("{}/{}", test_dir, name)); + // legacy hack to avoid the need for changes in existing grin-wallet.toml files + // remove `wallet_data` from end of path as + // new lifecycle provider assumes grin_wallet.toml is in root of data directory + let mut top_level_wallet_dir = PathBuf::from(wallet_config.clone().data_file_dir); + if top_level_wallet_dir.ends_with(GRIN_WALLET_DIR) { + top_level_wallet_dir.pop(); + wallet_config.data_file_dir = top_level_wallet_dir.to_str().unwrap().into(); + } + let _ = lc.set_top_level_directory(&wallet_config.data_file_dir); lc.create_wallet(None, mnemonic, 32, ZeroingString::from(""), false) .unwrap(); let mask = lc .open_wallet(None, ZeroingString::from(""), create_mask, false) .unwrap(); - (Arc::new(Mutex::new(wallet)), mask) + + let wallet = Arc::new(Mutex::new(wallet)); + let owner_api = Owner::new(wallet.clone(), None, config.config_file_path.clone()); + + (wallet, mask, owner_api) } #[allow(dead_code)] @@ -306,17 +322,11 @@ pub fn open_local_wallet( client: LocalWalletClient, create_mask: bool, ) -> ( - Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, >, Option, ) { @@ -337,7 +347,7 @@ pub fn open_local_wallet( } // Creates the given number of wallets and spawns a thread that runs the wallet proxy -#[allow(dead_code)] +#[allow(dead_code, clippy::type_complexity)] pub fn create_wallets( wallets_def: Vec>, // a vector of boolean that represent whether we mine into a wallet test_dir: &'static str, @@ -373,7 +383,7 @@ pub fn create_wallets( for i in 0..wallets_def.len() { let name = format!("wallet{}", i + 1); let wclient = LocalWalletClient::new(&name, wallet_proxy.tx.clone()); - let (wallet1, mask1) = create_local_wallet( + let (wallet1, mask1, _) = create_local_wallet( test_dir, &name, None, @@ -407,20 +417,15 @@ pub fn create_wallets( for (acc_idx, (acc_name, num_mined_blocks)) in accs.iter().enumerate() { // create the account - if acc_name.to_string() != "default" { - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let new_path = api.create_account_path(m, acc_name)?; - assert_eq!( - new_path, - ExtKeychain::derive_key_id(2, acc_idx as u32, 0, 0, 0) // NOTE: default should always be at 0 and is already created - ); - Ok(()) - }, - )?; + if *acc_name != "default" { + owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + let new_path = api.create_account_path(m, acc_name)?; + assert_eq!( + new_path, + ExtKeychain::derive_key_id(2, acc_idx as u32, 0, 0, 0) // NOTE: default should always be at 0 and is already created + ); + Ok(()) + })?; } // Get some mining done @@ -429,7 +434,7 @@ pub fn create_wallets( } { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name(acc_name)?; + w.set_account_by_name(acc_name)?; } let _ = test_framework::award_blocks_to_wallet( &chain, @@ -441,38 +446,43 @@ pub fn create_wallets( bh += num_mined_blocks; // Sanity check wallet 1 contents - 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(()) - }, - )?; + 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let accounts = api.accounts(m)?; - assert_eq!(accounts.len(), accs.len()); - Ok(()) - }, - )?; + 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); - w.set_parent_key_id_by_name("default")?; + w.set_account_by_name("default")?; } } Ok((wallets, chain, stopper, bh)) } + +#[allow(dead_code)] +pub fn owner_single_use( + wallet: libwallet::WalletHandle<'static, L, C, K>, + keychain_mask: Option<&SecretKey>, + config_path: PathBuf, + f: F, +) -> Result<(), libwallet::Error> +where + L: libwallet::WalletLCProvider<'static, C, K> + 'static, + F: FnOnce(&mut Owner, Option<&SecretKey>) -> Result<(), libwallet::Error>, + C: libwallet::NodeClient + 'static, + K: Keychain + 'static, +{ + f(&mut Owner::new(wallet, None, config_path), keychain_mask) +} diff --git a/controller/tests/config_api.rs b/controller/tests/config_api.rs index 5936a7f..6d1ac20 100644 --- a/controller/tests/config_api.rs +++ b/controller/tests/config_api.rs @@ -21,9 +21,9 @@ 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; +use std::{env, fs}; mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; @@ -63,7 +63,8 @@ fn tor_disable() { "wallet", None, &mut wallet_proxy, - false + false, + _api ); let path = PathBuf::from(test_dir).join("grin-wallet.toml"); let mut config = @@ -94,6 +95,7 @@ fn tor_disable() { ); assert_eq!(cached, stored); + drop(_api); drop(owner); drop(wallet); drop(wallet_proxy); @@ -113,7 +115,8 @@ fn send_preflight() { "wallet", None, &mut wallet_proxy, - false + false, + _api ); let owner = api::Owner::new( wallet.clone(), @@ -144,6 +147,7 @@ fn send_preflight() { assert!(after_txs.is_empty()); assert_eq!(snapshot(&wallet_data), before_data); + drop(_api); drop(owner); drop(wallet); drop(wallet_proxy); @@ -163,9 +167,13 @@ fn directory_change() { "wallet", None, &mut wallet_proxy, - false + false, + _api ); - let old_dir = PathBuf::from(test_dir).join("wallet"); + let old_dir = env::current_dir().unwrap_or_else(|e| { + panic!("Error creating config file: {}", e); + }); + let old_dir = old_dir.join(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()); diff --git a/controller/tests/contract_accounts.rs b/controller/tests/contract_accounts.rs index e028f97..6938dd5 100644 --- a/controller/tests/contract_accounts.rs +++ b/controller/tests/contract_accounts.rs @@ -63,259 +63,210 @@ fn contract_accounts_impl(test_dir: &'static str) -> Result<(), libwallet::Error // Default wallet 2 to listen on that account { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("listener_account")?; + w.set_account_by_name("listener_account")?; } // Mine into two different accounts in the same wallet { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; assert_eq!(w.parent_key_id(), ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); } let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 7, false); { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account2")?; + w.set_account_by_name("account2")?; assert_eq!(w.parent_key_id(), ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); } 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( - 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(()) - }, - )?; + common::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 { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } - 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(()) - }, - )?; + common::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")?; + w.set_account_by_name("default")?; } - 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); + common::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); - // Do not fall back to another account when the active account has no funds - let progress = common::wallet_progress(api, m)?; - let err = api - .contract_new( - m, - &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - net_change: Some(-(reward as i64)), - selection_args: common::contract_selection_args(), - ..Default::default() - }, + // Do not fall back to another account when the active account has no funds + let progress = common::wallet_progress(api, m)?; + let err = api + .contract_new( + m, + &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + net_change: Some(-(reward as i64)), + selection_args: common::contract_selection_args(), ..Default::default() }, - ) - .unwrap_err(); - assert!(matches!(err, libwallet::Error::NotEnoughFunds { .. })); - assert_eq!(common::wallet_progress(api, m)?, progress); - Ok(()) - }, - )?; + ..Default::default() + }, + ) + .unwrap_err(); + assert!(matches!(err, libwallet::Error::NotEnoughFunds { .. })); + assert_eq!(common::wallet_progress(api, m)?, progress); + Ok(()) + })?; // Send a tx from wallet1::account1 -> wallet2::listener_account { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } let mut slate = Slate::blank(0, true); // this gets overriden below let mut sender_address = None; - 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 { - selection_args: common::contract_selection_args(), - net_change: Some(-5_000_000_000), - ..Default::default() - }, + common::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 { + selection_args: common::contract_selection_args(), + net_change: Some(-5_000_000_000), ..Default::default() - }; - slate = api.contract_new(m, args)?; - sender_address = Some(api.get_slatepack_address(mask1, 0)?.pub_key); - Ok(()) - }, - )?; + }, + ..Default::default() + }; + slate = api.contract_new(m, args)?; + sender_address = Some( + api.get_slatepack_address(mask1, libwallet::slatepack::SlatepackAddressIndex(0))? + .pub_key, + ); + Ok(()) + })?; assert_eq!(slate.state, SlateState::Standard1); let mut recipient_address = None; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Receive wallet calls --receive=5 - let args = &mut ContractSetupArgsAPI { - selection_args: common::contract_selection_args(), - 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(()) - }, - )?; + common::owner_single_use(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { + // Receive wallet calls --receive=5 + let args = &mut ContractSetupArgsAPI { + selection_args: common::contract_selection_args(), + 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, libwallet::slatepack::SlatepackAddressIndex(0))? + .pub_key, + ); + Ok(()) + })?; assert_eq!(slate.state, SlateState::Standard2); // Send wallet finalizes and posts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = &ContractSetupArgsAPI { - selection_args: common::contract_selection_args(), - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - }, - )?; + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + let args = &ContractSetupArgsAPI { + selection_args: common::contract_selection_args(), + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + })?; assert_eq!(slate.state, SlateState::Standard3); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + api.post_tx(m, &slate, false)?; + 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(()) - }, - )?; + common::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")?; + w.set_account_by_name("account2")?; } - 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)?; - assert_eq!(txs.len(), 5); - Ok(()) - }, - )?; + common::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)?; + assert_eq!(txs.len(), 5); + Ok(()) + })?; // wallet 2 should only have this tx on the listener account - 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(()) - }, - )?; + common::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")?; + w.set_account_by_name("default")?; } - 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(()) - }, - )?; + common::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); @@ -341,11 +292,8 @@ 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { + let res = + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { let args = &ContractNewArgsAPI { setup_args: ContractSetupArgsAPI { selection_args: common::contract_selection_args(), @@ -357,8 +305,7 @@ fn contract_unknown_account_impl(test_dir: &'static str) -> Result<(), libwallet }; api.contract_new(m, args)?; Ok(()) - }, - ); + }); assert!(res.is_err(), "expected an error for an unknown account"); stopper.store(false, Ordering::Relaxed); @@ -383,11 +330,8 @@ 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { + let res = + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { let args = &ContractNewArgsAPI { setup_args: ContractSetupArgsAPI { selection_args: common::contract_selection_args(), @@ -398,8 +342,7 @@ fn contract_missing_net_change_impl(test_dir: &'static str) -> Result<(), libwal }; 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 0ac0193..946d792 100644 --- a/controller/tests/contract_accounts_switch.rs +++ b/controller/tests/contract_accounts_switch.rs @@ -52,210 +52,165 @@ fn contract_accounts_switch_impl(test_dir: &'static str) -> Result<(), libwallet // wallet1::account1 should have 1 in account1 (1 spendable) { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } - 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, reward); - assert_eq!(wallet1_info.amount_currently_spendable, reward); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - Ok(()) - }, - )?; + common::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, reward); + assert_eq!(wallet1_info.amount_currently_spendable, 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")?; + w.set_account_by_name("account2")?; } - 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(()) - }, - )?; + common::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 { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } let mut slate = Slate::blank(0, true); // this gets overriden below - 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 { - ttl_blocks: Some(20), - setup_args: ContractSetupArgsAPI { - selection_args: common::contract_selection_args(), - net_change: Some(-5_000_000_000), - ..Default::default() - }, - }; - slate = api.contract_new(m, args)?; - Ok(()) - }, - )?; + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + // Send wallet inititates a standard transaction with --send=5 + let args = &ContractNewArgsAPI { + ttl_blocks: Some(20), + setup_args: ContractSetupArgsAPI { + selection_args: common::contract_selection_args(), + net_change: Some(-5_000_000_000), + ..Default::default() + }, + }; + slate = api.contract_new(m, args)?; + Ok(()) + })?; assert_eq!(slate.state, SlateState::Standard1); assert_eq!(slate.ttl_cutoff_height, bh + 20); // Receiver gets their coins on account2 where they can payjoin { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("account2")?; + w.set_account_by_name("account2")?; } - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Receive wallet calls --receive=5 - let args = &mut ContractSetupArgsAPI { - selection_args: common::contract_selection_args(), - net_change: Some(5_000_000_000), - ..Default::default() - }; - args.proof_args.suppress_proof = true; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - }, - )?; + common::owner_single_use(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { + // Receive wallet calls --receive=5 + let args = &mut ContractSetupArgsAPI { + selection_args: common::contract_selection_args(), + 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 accounts and finish the transaction (should use account1 to complete) { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("default")?; + w.set_account_by_name("default")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet_info.last_confirmed_height, 0); - let mut expired = slate.clone(); - expired.ttl_cutoff_height = bh; - assert!(matches!( - api.contract_sign(m, &expired, &ContractSetupArgsAPI::default()), - Err(libwallet::Error::TransactionExpired) - )); - let args = &ContractSetupArgsAPI { - selection_args: common::contract_selection_args(), - ..Default::default() - }; - slate = api.contract_sign(m, &slate, args)?; - Ok(()) - }, - )?; + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + let (_, wallet_info) = api.retrieve_summary_info(m, false, 1)?; + assert_eq!(wallet_info.last_confirmed_height, 0); + let mut expired = slate.clone(); + expired.ttl_cutoff_height = bh; + assert!(matches!( + api.contract_sign(m, &expired, &ContractSetupArgsAPI::default()), + Err(libwallet::Error::TransactionExpired) + )); + let args = &ContractSetupArgsAPI { + selection_args: common::contract_selection_args(), + ..Default::default() + }; + slate = api.contract_sign(m, &slate, args)?; + Ok(()) + })?; assert_eq!(slate.state, SlateState::Standard3); { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account2")?; + w.set_account_by_name("account2")?; } // post tx and mine a block to wallet1::account2 - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + common::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( - 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(()) - }, - )?; + common::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")?; + w.set_account_by_name("account1")?; } - 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, - 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(()) - }, - )?; + common::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, + 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")?; + w.set_account_by_name("account2")?; } - 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(()) - }, - )?; + common::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 41bf7b3..7f54978 100644 --- a/controller/tests/contract_early_lock.rs +++ b/controller/tests/contract_early_lock.rs @@ -44,7 +44,7 @@ fn contract_early_lock_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: let recv_mask = wallets[1].1.as_ref(); // Confirm all our outputs are unspent - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -60,7 +60,7 @@ fn contract_early_lock_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: let mut slate = Slate::blank(0, false); // this gets overriden below // Call contract 'new' with --add-outputs - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -83,7 +83,7 @@ fn contract_early_lock_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: assert_eq!(slate.state, SlateState::Standard1); // Assert we locked 2 inputs and prepared an unconfirmed change output - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -107,7 +107,7 @@ fn contract_early_lock_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: )?; // The receiver signs without seeing the sender's locked commitments. - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -127,7 +127,7 @@ fn contract_early_lock_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: assert_eq!(slate.state, SlateState::Standard2); // Even a commitment reserved for this contract must not be present before we add it. - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -169,7 +169,7 @@ fn contract_early_lock_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: )?; // The sender adds the reserved commitments and completes the contract. - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), diff --git a/controller/tests/contract_early_proofs_rsr.rs b/controller/tests/contract_early_proofs_rsr.rs index 60d42a3..106fba2 100644 --- a/controller/tests/contract_early_proofs_rsr.rs +++ b/controller/tests/contract_early_proofs_rsr.rs @@ -55,18 +55,24 @@ fn contract_early_proofs_rsr_test_impl( let mut sender_address = None; // Get sender address explicitly - wallet::controller::owner_single_use( + common::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); + sender_address = Some( + api.get_slatepack_address( + send_mask, + libwallet::slatepack::SlatepackAddressIndex(0), + )? + .pub_key, + ); Ok(()) }, )?; let mut recipient_address = None; - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -79,7 +85,13 @@ fn contract_early_proofs_rsr_test_impl( args.setup_args.proof_args.memo = Some(PaymentMemo::new("RSR payment".into())?); 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); + recipient_address = Some( + api.get_slatepack_address( + recv_mask, + libwallet::slatepack::SlatepackAddressIndex(0), + )? + .pub_key, + ); Ok(()) }, )?; @@ -87,7 +99,7 @@ fn contract_early_proofs_rsr_test_impl( assert_eq!(slate.state, SlateState::Invoice1); slate = common::roundtrip_slate(&slate, 5)?; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -103,7 +115,7 @@ fn contract_early_proofs_rsr_test_impl( slate = common::roundtrip_slate(&slate, 5)?; // Send wallet finalizes and posts - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -116,7 +128,7 @@ fn contract_early_proofs_rsr_test_impl( assert_eq!(slate.state, SlateState::Invoice3); slate = common::roundtrip_slate(&slate, 5)?; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -132,7 +144,7 @@ fn contract_early_proofs_rsr_test_impl( bh += 3; // Assert changes in receive wallet - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -159,7 +171,7 @@ fn contract_early_proofs_rsr_test_impl( )?; // Assert changes in send wallet - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -182,7 +194,7 @@ fn contract_early_proofs_rsr_test_impl( let mut early_proof = None; // Now some time has passed, sender retrieves and verify the payment proof - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), diff --git a/controller/tests/contract_early_proofs_srs.rs b/controller/tests/contract_early_proofs_srs.rs index af0bb26..7697a7b 100644 --- a/controller/tests/contract_early_proofs_srs.rs +++ b/controller/tests/contract_early_proofs_srs.rs @@ -65,7 +65,7 @@ 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( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -73,7 +73,13 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib // Send wallet inititates a standard transaction with --send=5 let args = &common::contract_new_args(-5_000_000_000); slate = api.contract_new(m, args)?; - sender_address = Some(api.get_slatepack_address(send_mask, 0)?.pub_key); + sender_address = Some( + api.get_slatepack_address( + send_mask, + libwallet::slatepack::SlatepackAddressIndex(0), + )? + .pub_key, + ); Ok(()) }, )?; @@ -81,7 +87,7 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib slate = common::roundtrip_slate(&slate, 4)?; let mut recipient_address = None; - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -93,7 +99,13 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib args.proof_args.memo = Some(PaymentMemo::new("SRS payment".into())?); 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); + recipient_address = Some( + api.get_slatepack_address( + recv_mask, + libwallet::slatepack::SlatepackAddressIndex(0), + )? + .pub_key, + ); Ok(()) }, )?; @@ -102,7 +114,7 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib // Send wallet finalizes and posts //let mut sender_part_sig = None; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -120,7 +132,7 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib assert_eq!(slate.state, SlateState::Standard3); slate = common::roundtrip_slate(&slate, 5)?; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -136,7 +148,7 @@ 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( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -163,7 +175,7 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib )?; // Assert changes in send wallet - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -186,7 +198,7 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib let mut early_proof = None; // Now some time has passed, sender retrieves and verify the payment proof - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -243,7 +255,7 @@ fn contract_early_proofs_srs_test_impl(test_dir: &'static str) -> Result<(), lib // export and verify through the CLI let proof_file = format!("{}/early_proof.json", test_dir); let tampered_file = format!("{}/early_proof_tampered.json", test_dir); - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), diff --git a/controller/tests/contract_revoke.rs b/controller/tests/contract_revoke.rs index 36d5f03..652f07c 100644 --- a/controller/tests/contract_revoke.rs +++ b/controller/tests/contract_revoke.rs @@ -41,51 +41,10 @@ fn contract_revoke_other_account_impl(test_dir: &'static str) -> Result<(), libw let mask1 = wallets[0].1.as_ref(); // Create an early-locked contract in the default account. - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.contract_new( - m, - &ContractNewArgsAPI { - setup_args: ContractSetupArgsAPI { - selection_args: common::contract_selection_args(), - net_change: Some(-1_000_000_000), - num_participants: 2, - add_outputs: true, - ..Default::default() - }, - ..Default::default() - }, - )?; - Ok(()) - }, - )?; - let mut default_tx_id = 0; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - default_tx_id = txs.last().unwrap().id; - Ok(()) - }, - )?; - - // Create another early-locked contract in account1. - { - wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; - } - let mut slate = Slate::blank(0, true); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = &ContractNewArgsAPI { + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + api.contract_new( + m, + &ContractNewArgsAPI { setup_args: ContractSetupArgsAPI { selection_args: common::contract_selection_args(), net_change: Some(-1_000_000_000), @@ -94,96 +53,101 @@ fn contract_revoke_other_account_impl(test_dir: &'static str) -> Result<(), libw ..Default::default() }, ..Default::default() - }; - slate = api.contract_new(m, args)?; - Ok(()) - }, - )?; + }, + )?; + Ok(()) + })?; + let mut default_tx_id = 0; + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; + default_tx_id = txs.last().unwrap().id; + Ok(()) + })?; + + // Create another early-locked contract in account1. + { + wallet_inst!(wallet1, w); + w.set_account_by_name("account1")?; + } + let mut slate = Slate::blank(0, true); + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + let args = &ContractNewArgsAPI { + setup_args: ContractSetupArgsAPI { + selection_args: common::contract_selection_args(), + net_change: Some(-1_000_000_000), + num_participants: 2, + add_outputs: true, + ..Default::default() + }, + ..Default::default() + }; + 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( - 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(()) - }, - )?; + common::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(()) + })?; assert_eq!(tx_id, default_tx_id); // Switch the active account to "default" — different from the inputs' account. { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("default")?; + w.set_account_by_name("default")?; } // Revoke account1 while the default account is active. let mut revoked = None; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - revoked = api.contract_revoke( - m, - &ContractRevokeArgsAPI { - tx_id, - src_acct_name: Some("account1".to_string()), - }, - )?; - Ok(()) - }, - )?; + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + revoked = api.contract_revoke( + m, + &ContractRevokeArgsAPI { + tx_id, + src_acct_name: Some("account1".to_string()), + }, + )?; + Ok(()) + })?; assert!( revoked.is_some(), "revoke should produce a self-spend slate" ); // The default account's transaction is still locked. - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, outs) = api.retrieve_outputs(m, true, false, None)?; - assert!(outs.iter().any(|o| { - o.output.status == OutputStatus::Locked - && o.output.tx_log_entry == Some(default_tx_id) - })); - Ok(()) - }, - )?; + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + let (_, outs) = api.retrieve_outputs(m, true, false, None)?; + assert!(outs.iter().any(|o| { + o.output.status == OutputStatus::Locked && o.output.tx_log_entry == Some(default_tx_id) + })); + Ok(()) + })?; // 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")?; + w.set_account_by_name("account1")?; } - 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(()) - }, - )?; + common::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)); @@ -221,15 +185,10 @@ fn contract_revoke_resume_impl(test_dir: &'static str) -> Result<(), wallet::Err // Send (with early lock), locking an input under the contract tx. let mut slate = Slate::blank(0, true); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - slate = api.contract_new(m, &args)?; - Ok(()) - }, - )?; + common::owner_single_use(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { + slate = api.contract_new(m, &args)?; + Ok(()) + })?; assert_eq!(slate.state, SlateState::Standard1); { wallet_inst!(wallet1, w); @@ -248,34 +207,24 @@ fn contract_revoke_resume_impl(test_dir: &'static str) -> Result<(), wallet::Err } let mut tx_id = 0; - 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(()) - }, - )?; + common::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( - 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(()) - }, - )?; + common::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 through the command path and write the self-spend to the requested file. let outfile = format!("{}/revoke.slatepack", test_dir); diff --git a/controller/tests/contract_rsr.rs b/controller/tests/contract_rsr.rs index e18edcb..e5efa49 100644 --- a/controller/tests/contract_rsr.rs +++ b/controller/tests/contract_rsr.rs @@ -122,7 +122,7 @@ fn contract_rsr_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> }, ); - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -166,7 +166,7 @@ fn contract_rsr_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> ); // Receive wallet finalizes and posts - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -196,7 +196,7 @@ fn contract_rsr_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> ); // Send wallet posts so receive wallet doesn't get the mined amount - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -212,7 +212,7 @@ fn contract_rsr_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> bh += 3; // Assert changes in receive wallet - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -240,7 +240,7 @@ fn contract_rsr_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> )?; // Assert changes in send wallet - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), diff --git a/controller/tests/contract_self_spend.rs b/controller/tests/contract_self_spend.rs index ea480d0..fba6d71 100644 --- a/controller/tests/contract_self_spend.rs +++ b/controller/tests/contract_self_spend.rs @@ -42,7 +42,7 @@ 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( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -64,7 +64,7 @@ fn contract_self_spend_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: assert_eq!(slate.state, SlateState::Standard1); // Send wallet finalizes and posts - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -80,7 +80,7 @@ fn contract_self_spend_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: // 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( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -96,7 +96,7 @@ fn contract_self_spend_tx_impl(test_dir: &'static str) -> Result<(), libwallet:: bh += 3; // Assert changes in send wallet - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -148,7 +148,7 @@ fn contract_fee_floor_impl(test_dir: &'static str) -> Result<(), libwallet::Erro let wallet = wallets[0].0.clone(); let mask = wallets[0].1.as_ref(); - wallet::controller::owner_single_use(wallet, mask, PathBuf::from(test_dir), |api, m| { + common::owner_single_use(wallet, mask, PathBuf::from(test_dir), |api, m| { let slate = api.contract_new( m, &ContractNewArgsAPI { diff --git a/controller/tests/contract_self_spend_cancel.rs b/controller/tests/contract_self_spend_cancel.rs index f1274bf..dc9fef9 100644 --- a/controller/tests/contract_self_spend_cancel.rs +++ b/controller/tests/contract_self_spend_cancel.rs @@ -40,7 +40,7 @@ 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( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -62,7 +62,7 @@ fn contract_self_spend_cancel_impl(test_dir: &'static str) -> Result<(), libwall assert_eq!(slate.state, SlateState::Standard1); // Send wallet finalizes and posts - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -73,7 +73,7 @@ fn contract_self_spend_cancel_impl(test_dir: &'static str) -> Result<(), libwall )?; // Assert tx log has been cancelled - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -149,7 +149,7 @@ fn contract_self_spend_cancel_missing_stored_tx_impl( let send_mask = wallets[0].1.as_ref(); let mut slate = Slate::blank(0, true); - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -169,7 +169,7 @@ fn contract_self_spend_cancel_missing_stored_tx_impl( )?; // Signing a self-spend completes the slate, so the transaction is stored - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -186,7 +186,7 @@ fn contract_self_spend_cancel_missing_stored_tx_impl( // Signing locked our inputs, so the cancel below has something to release, and the // entry records where the transaction was stored, as a standard send does - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -208,7 +208,7 @@ fn contract_self_spend_cancel_missing_stored_tx_impl( std::fs::remove_file(&stored).unwrap(); // Cancelling still releases the inputs - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -218,7 +218,7 @@ fn contract_self_spend_cancel_missing_stored_tx_impl( }, )?; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), diff --git a/controller/tests/contract_self_spend_custom.rs b/controller/tests/contract_self_spend_custom.rs index ccc5ceb..93a9c53 100644 --- a/controller/tests/contract_self_spend_custom.rs +++ b/controller/tests/contract_self_spend_custom.rs @@ -45,7 +45,7 @@ fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libw let mut use_inputs = String::from(""); let mut plain_input = None; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -74,7 +74,7 @@ fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libw 15 * consensus::GRIN_BASE, ]), }; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -96,7 +96,7 @@ fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libw assert_eq!(slate.state, SlateState::Standard1); // Send wallet finalizes and posts - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -114,7 +114,7 @@ fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libw // 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( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -130,7 +130,7 @@ 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( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -151,7 +151,7 @@ fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libw }, )?; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -195,7 +195,7 @@ fn contract_self_spend_custom_tx_impl(test_dir: &'static str) -> Result<(), libw )?; let (plain_input, plain_commitment) = plain_input.expect("plain output was not found"); - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -270,7 +270,7 @@ fn contract_min_confirmations_impl(test_dir: &'static str) -> Result<(), libwall let recv_mask = wallets[1].1.as_ref(); let mut slate = Slate::blank(0, true); - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -294,55 +294,45 @@ fn contract_min_confirmations_impl(test_dir: &'static str) -> Result<(), libwall )?; assert_eq!(slate.state, SlateState::Standard1); - wallet::controller::owner_single_use( - recv_wallet, - recv_mask, - PathBuf::from(test_dir), - |api, m| { - let (_, outputs) = api.retrieve_outputs(m, true, false, None)?; - assert_eq!(outputs.len(), 1); - assert!(outputs[0].output.eligible_to_spend(bh, 1)); - assert!(!outputs[0].output.eligible_to_spend(bh, 10)); - slate = api.contract_sign( - m, - &slate, - &ContractSetupArgsAPI { - net_change: Some(consensus::GRIN_BASE as i64), - selection_args: OutputSelectionArgs { - minimum_confirmations: Some(10), - ..Default::default() - }, - ..Default::default() - }, - )?; - Ok(()) - }, - )?; - assert_eq!(slate.state, SlateState::Standard2); - assert_eq!(slate.tx_or_err()?.inputs().len(), 0); - - wallet::controller::owner_single_use( - send_wallet, - send_mask, - PathBuf::from(test_dir), - |api, m| { - let args = |minimum| ContractSetupArgsAPI { + common::owner_single_use(recv_wallet, recv_mask, PathBuf::from(test_dir), |api, m| { + let (_, outputs) = api.retrieve_outputs(m, true, false, None)?; + assert_eq!(outputs.len(), 1); + assert!(outputs[0].output.eligible_to_spend(bh, 1)); + assert!(!outputs[0].output.eligible_to_spend(bh, 10)); + slate = api.contract_sign( + m, + &slate, + &ContractSetupArgsAPI { + net_change: Some(consensus::GRIN_BASE as i64), selection_args: OutputSelectionArgs { - minimum_confirmations: minimum, + minimum_confirmations: Some(10), ..Default::default() }, ..Default::default() - }; - let err = api.contract_sign(m, &slate, &args(Some(12))).unwrap_err(); - assert!(matches!( - err, - libwallet::Error::GenericError(ref msg) - if msg == "Can't change minimum confirmations after contract setup. setup:10, current:12" - )); - slate = api.contract_sign(m, &slate, &args(None))?; - Ok(()) - }, - )?; + }, + )?; + Ok(()) + })?; + assert_eq!(slate.state, SlateState::Standard2); + assert_eq!(slate.tx_or_err()?.inputs().len(), 0); + + common::owner_single_use(send_wallet, send_mask, PathBuf::from(test_dir), |api, m| { + let args = |minimum| ContractSetupArgsAPI { + selection_args: OutputSelectionArgs { + minimum_confirmations: minimum, + ..Default::default() + }, + ..Default::default() + }; + let err = api.contract_sign(m, &slate, &args(Some(12))).unwrap_err(); + assert!(matches!( + err, + libwallet::Error::GenericError(ref msg) + if msg == "Can't change minimum confirmations after contract setup. setup:10, current:12" + )); + slate = api.contract_sign(m, &slate, &args(None))?; + Ok(()) + })?; assert_eq!(slate.state, SlateState::Standard3); stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/contract_srs.rs b/controller/tests/contract_srs.rs index 78cfe76..de267ca 100644 --- a/controller/tests/contract_srs.rs +++ b/controller/tests/contract_srs.rs @@ -82,7 +82,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let mut slate = Slate::blank(0, false); // this gets overriden below - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -99,14 +99,14 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let progress = common::wallet_progress(api, m)?; for count in [0, 3] { args.setup_args.num_participants = count; - let err = api.contract_new(m, &mut args).unwrap_err(); + let err = api.contract_new(m, &args).unwrap_err(); assert_participant_error(err, count); } assert_eq!(common::wallet_progress(api, m)?, progress); args.setup_args.num_participants = 2; args.ttl_blocks = Some(0); - let err = api.contract_new(m, &mut args).unwrap_err(); + let err = api.contract_new(m, &args).unwrap_err(); assert!(matches!( err, libwallet::Error::GenericError(ref msg) @@ -114,7 +114,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> )); args.ttl_blocks = Some(20); args.setup_args.fee_rate = Some(0); - let err = api.contract_new(m, &mut args).unwrap_err(); + let err = api.contract_new(m, &args).unwrap_err(); assert!(matches!( err, libwallet::Error::GenericError(ref msg) @@ -122,7 +122,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> )); args.setup_args.fee_rate = None; assert_eq!(common::wallet_progress(api, m)?, progress); - slate = api.contract_new(m, &mut args)?; + slate = api.contract_new(m, &args)?; let tx_log = common::tx_log_for_slate(api, m, &slate)?; assert_eq!(tx_log.ttl_cutoff_height, Some(ttl_cutoff)); Ok(()) @@ -144,7 +144,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> signatures: 0, }, ); - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -195,7 +195,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> }, )?; - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -303,7 +303,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> }, )?; - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -347,7 +347,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> signatures: 1, }, ); - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -362,7 +362,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> Ok(()) }, )?; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -383,7 +383,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> )?; // The sender must reject an unused commitment from its wallet if it was inserted by the receiver. - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -513,7 +513,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> )?; // Send wallet finalizes and posts - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -567,7 +567,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> signatures: 2, }, ); - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -577,7 +577,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> Ok(()) }, )?; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -603,7 +603,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> }, )?; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -619,7 +619,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> bh += 3; // Assert changes in receive wallet - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -646,7 +646,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> )?; // Assert changes in send wallet - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -721,7 +721,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let receiver_fee = my_fee_contribution(0, 1, 1, 2)?.fee(); let net = i64::try_from((receiver_fee + participant_fee) / 2).unwrap(); let mut small = Slate::blank(0, false); - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -734,7 +734,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> Ok(()) }, )?; - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -745,7 +745,7 @@ fn contract_srs_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> Ok(()) }, )?; - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), diff --git a/controller/tests/contract_srs_mwmixnet.rs b/controller/tests/contract_srs_mwmixnet.rs index 75d6692..7092c62 100644 --- a/controller/tests/contract_srs_mwmixnet.rs +++ b/controller/tests/contract_srs_mwmixnet.rs @@ -45,7 +45,7 @@ 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( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -65,7 +65,7 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: )?; assert_eq!(slate.state, SlateState::Standard1); - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -84,7 +84,7 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: assert_eq!(slate.state, SlateState::Standard2); // Send wallet finalizes and posts - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -100,7 +100,7 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: )?; assert_eq!(slate.state, SlateState::Standard3); - wallet::controller::owner_single_use( + common::owner_single_use( send_wallet.clone(), send_mask, PathBuf::from(test_dir), @@ -114,7 +114,7 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: test_framework::award_blocks_to_wallet(&chain, send_wallet.clone(), send_mask, 3, false); // Recipient wallet sends outputs to mwixnet - wallet::controller::owner_single_use( + common::owner_single_use( recv_wallet.clone(), recv_mask, PathBuf::from(test_dir), @@ -128,19 +128,23 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: let server_pubkey_str_3 = "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; let server_key_1 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap()) + 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()) + 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()) + SecretKey::from_slice(&secp, &grin_util::from_hex(server_pubkey_str_3).unwrap()) .unwrap(); + drop(secp); let params = MixnetReqCreationParams { - server_keys: vec![server_key_1, server_key_2, server_key_3], - fee_per_hop: 50_000_000, + server_keys: [server_key_1, server_key_2, server_key_3] + .iter() + .map(libwallet::mwixnet::MwixnetServerPublicKey::from_secret) + .collect(), + fee_per_hop: Some(50_000_000), }; - let outputs = api.retrieve_outputs(recv_mask, false, false, None)?; + let outputs = api.retrieve_outputs(recv_mask, false, true, None)?; // get last output let last_output = outputs.1[outputs.1.len() - 1].clone(); @@ -148,9 +152,12 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet: // 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); + let input = outputs + .1 + .iter() + .find(|output| output.commit == last_output.commit) + .unwrap(); + assert_eq!(input.output.status, libwallet::OutputStatus::Locked); Ok(()) }, diff --git a/controller/tests/file.rs b/controller/tests/file.rs index e313407..71509df 100644 --- a/controller/tests/file.rs +++ b/controller/tests/file.rs @@ -27,11 +27,12 @@ use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; -use grin_wallet_libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate}; +use grin_wallet_libwallet::{InitTxArgs, IssueInvoiceTxArgs}; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// self send impl fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), libwallet::Error> { @@ -50,9 +51,10 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -61,9 +63,10 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -76,33 +79,17 @@ 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // add some accounts - 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(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut bh = 10u64; let _ = @@ -122,37 +109,29 @@ 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( - 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(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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 = api1.init_send_tx(mask1, args)?; + // output tx file + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; + api1.tx_lock_outputs(mask1, &slate)?; // Get some mining done { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } let mut slate = PathToSlate((&send_file).into()).get_tx()?.0; @@ -169,52 +148,28 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }, )?; - // wallet 1 finalises and posts - 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(()) - }, - )?; + // wallet 1 finalizes and posts + let mut slate = PathToSlate(receive_file.into()).get_tx()?.0; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; + api1.post_tx(mask1, &slate, false)?; + bh += 1; 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( - 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(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'wallet 2' account - 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(()) - }, - )?; + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * reward); // Now other types of exchange, for reference // Invoice transaction @@ -231,44 +186,27 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), ), }; - let mut slate = Slate::blank(2, true); + let args = IssueInvoiceTxArgs { + amount: 1000000000, + ..Default::default() + }; + let mut slate = api2.issue_invoice_tx(mask2, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - 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(()) - }, - )?; + 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 = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; - 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), @@ -281,15 +219,8 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), Ok(()) }, )?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + + api1.post_tx(mask1, &slate, false)?; // Standard, with payment proof let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); @@ -305,40 +236,22 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), format!("{}/standard_pp_S3.txbin", test_dir), ), }; - let mut slate = Slate::blank(2, true); - let mut address = None; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - }, - )?; + let address = Some(api2.get_slatepack_address(mask2, SlatepackAddressIndex(0))?); - 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(()) - }, - )?; + // 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 mut slate = api1.init_send_tx(mask1, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; + api1.tx_lock_outputs(mask1, &slate)?; wallet::controller::foreign_single_use( wallet2.clone(), @@ -352,21 +265,12 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }, )?; - // wallet 1 finalises and posts - 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(()) - }, - )?; + // wallet 1 finalizes and posts + slate = PathToSlate(receive_file.into()).get_tx()?.0; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; + api1.post_tx(mask1, &slate, false)?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index 3713d5e..426306d 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -22,7 +22,7 @@ use grin_wallet_libwallet as libwallet; use std::path::PathBuf; use impls::test_framework::{self, LocalWalletClient}; -use libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate, SlateState}; +use libwallet::{InitTxArgs, IssueInvoiceTxArgs, SlateState}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -46,9 +46,10 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -57,9 +58,10 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - true + true, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -72,56 +74,41 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - 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(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut _bh = 10u64; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, _bh as usize, false); // Sanity check wallet 1 contents - 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 (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, _bh); + assert_eq!(wallet1_info.total, _bh * reward); - let mut slate = Slate::blank(2, true); - - 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, + let error = api2 + .issue_invoice_tx( + mask2, + IssueInvoiceTxArgs { + amount: 0, ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - }, - )?; + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); + + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + let mut slate = api2.issue_invoice_tx(mask2, args)?; assert_eq!(slate.state, SlateState::Invoice1); let receive_result = wallet::controller::foreign_single_use( @@ -131,16 +118,8 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { |api| api.receive_tx(&slate, None, None).map(|_| ()), ); assert_eq!(receive_result, Err(libwallet::Error::SlateState)); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, false, None, Some(slate.id), None)?; - assert!(txs.is_empty()); - Ok(()) - }, - )?; + let (_, txs) = api1.retrieve_txs(mask1, false, None, Some(slate.id), None)?; + assert!(txs.is_empty()); // receive must reject every slate state except S1 for state in [ @@ -162,28 +141,35 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { assert_eq!(res, Err(libwallet::Error::SlateState), "state {}", state); } - 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(()) - }, - )?; + // 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() + }; + let mut zero_amount_slate = slate.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api1.process_invoice_tx(mask1, &zero_amount_slate, args.clone()) + .unwrap_err(), + libwallet::Error::InvalidAmount + ); + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; assert_eq!(slate.state, SlateState::Invoice2); + assert_eq!( + api2.tx_lock_outputs(mask2, &slate), + Err(libwallet::Error::SlateState) + ); + let (_, txs) = api2.retrieve_txs(mask2, false, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + // wallet 2 finalizes and posts wallet::controller::foreign_single_use( wallet2.clone(), @@ -198,86 +184,54 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { assert_eq!(slate.state, SlateState::Invoice3); // wallet 1 posts so wallet 2 doesn't get the mined amount - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + api1.post_tx(mask1, &slate, false)?; _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( - 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(()) - }, - )?; + let (_, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), 1); + println!( + "last confirmed height: {}, bh: {}", + wallet2_info.last_confirmed_height, _bh + ); + assert!(refreshed); // Check transaction log for wallet 1, ensure only 1 entry // exists - 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(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (refreshed, txs) = api1.retrieve_txs(mask1, 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 + ); // Test self-sending - 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(()) - }, - )?; + // Wallet 1 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api1.issue_invoice_tx(mask1, 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 = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; println!("Self invoice slate after process: {}", slate); @@ -294,112 +248,66 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); - //bh += 3; - // As above, but use owner API to finalize - let mut slate = Slate::blank(2, true); - - 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(()) - }, - )?; + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api2.issue_invoice_tx(mask2, args)?; assert_eq!(slate.state, SlateState::Invoice1); - 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(()) - }, - )?; + // 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 = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; assert_eq!(slate.state, SlateState::Invoice2); - // wallet 2 finalizes via owner API - 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(()) - }, - )?; + // Wallet 2 receives and finalizes via owner API + slate = api2.finalize_tx(mask2, &slate)?; 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( - 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(()) - }, - )?; + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api2.issue_invoice_tx(mask2, args)?; assert_eq!(slate.state, SlateState::Invoice1); let orig_slate = slate.clone(); - 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 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 = api1.process_invoice_tx(mask1, &slate, args.clone())?; + api1.tx_lock_outputs(mask1, &slate)?; - // Wallet 1 cancels the invoice transaction - api.cancel_tx(m, None, Some(slate.id))?; + // Wallet 1 cancels the invoice transaction + api1.cancel_tx(mask1, None, Some(slate.id))?; - // Wallet 1 attempts to repay again - let res = api.process_invoice_tx(m, &orig_slate, args); - assert!(res.is_err()); - - Ok(()) - }, - )?; + // Wallet 1 attempts to repay again + let res = api1.process_invoice_tx(mask1, &orig_slate, args); + assert!(res.is_err()); assert_eq!(slate.state, SlateState::Invoice2); // let logging finish diff --git a/controller/tests/late_lock.rs b/controller/tests/late_lock.rs index 2d1ec29..dae59a4 100644 --- a/controller/tests/late_lock.rs +++ b/controller/tests/late_lock.rs @@ -18,9 +18,8 @@ extern crate grin_wallet_controller as wallet; extern crate grin_wallet_impls as impls; extern crate grin_wallet_libwallet as libwallet; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; -use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -28,6 +27,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use libwallet::InitTxSendArgs; /// self send impl fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -46,9 +46,10 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -57,9 +58,10 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -69,103 +71,90 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { }); // add some accounts - 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( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api2.create_account_path(mask2, "account1")?; // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false)?; - let mut slate = Slate::blank(2, false); let amount = 100_000_000_000; - 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); + 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 = api1.init_send_tx(mask1, args)?; + println!("S1 SLATE: {}", slate_i); + let mut 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 = api1.finalize_tx(mask1, &slate)?; + println!("S3 SLATE: {}", slate); - // Now post tx to our node for inclusion in the next block. - sender_api.post_tx(m, &slate, true)?; - - Ok(()) - }, - )?; + // Now post tx to our node for inclusion in the next block. + api1.post_tx(mask1, &slate, true)?; test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false)?; // update/test contents of both accounts - 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(()) - }, - )?; + let (wallet1_refreshed, wallet_info) = api1.retrieve_summary_info(mask1, 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); - 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(()) - }, - )?; + // Make sure outputs are not locked on failed send with arguments. + // Fail sending without starting Tor + api1.set_tor_config(Some(grin_wallet_config::TorConfig { + use_integrated: Some(false), + socks_proxy_addr: "invalid".into(), + ..Default::default() + }))?; + 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), + send_args: Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".into(), + post_tx: false, + fluff: false, + skip_tor: Some(false), + }), + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + let (_, txs) = api1.retrieve_txs(mask1, false, None, Some(slate.id), None)?; + assert!(txs.is_empty()); + // Make sure spendable balance not changed. + let (wallet1_refreshed, wallet_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(560_000_000_000, wallet_info.amount_currently_spendable); + + let (wallet2_refreshed, wallet_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(amount, wallet_info.amount_currently_spendable); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/mwixnet.rs b/controller/tests/mwixnet.rs index 60e4bd8..16b348d 100644 --- a/controller/tests/mwixnet.rs +++ b/controller/tests/mwixnet.rs @@ -18,13 +18,17 @@ extern crate grin_wallet_controller as wallet; extern crate grin_wallet_impls as impls; use grin_core as core; +use grin_core::core::FeeFields; 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}; -use libwallet::{mwixnet::MixnetReqCreationParams, InitTxArgs}; +use libwallet::{ + mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey, MAX_MWIXNET_HOPS}, + InitTxArgs, OutputStatus, TxLogEntryType, +}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -50,9 +54,10 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -65,144 +70,242 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - 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(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut bh = 10u64; let _ = 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( + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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 = api1.init_send_tx(mask1, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + // Send directly to self + wallet::controller::foreign_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; + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, Some("listener"), None)?; Ok(()) }, )?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, false)?; // mines a block + bh += 1; 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( - 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(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'listener' account { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("listener")?; + w.set_account_by_name("listener")?; } - 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 (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); // Recipient wallet creates a mwixnet request from the last output - wallet::controller::owner_single_use( - wallet1.clone(), + 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())?; + let server_key_2 = + SecretKey::from_slice(&secp, &grin_util::from_hex(server_pubkey_str_2).unwrap())?; + let server_key_3 = + SecretKey::from_slice(&secp, &grin_util::from_hex(server_pubkey_str_3).unwrap())?; + let params = MixnetReqCreationParams { + server_keys: vec![ + MwixnetServerPublicKey::from_secret(&server_key_1), + MwixnetServerPublicKey::from_secret(&server_key_2), + MwixnetServerPublicKey::from_secret(&server_key_3), + ], + fee_per_hop: None, + }; + let outputs = api1.retrieve_outputs(mask1, false, false, None)?; + // get last output + let last_output = outputs.1[outputs.1.len() - 1].clone(); + + // Store the output with an MMR index, like a restored output + let mmr_index = Some(chain.get_output_pos(&last_output.commit).unwrap()); + { + wallet_inst!(wallet1, w); + let mut batch = w.batch(mask1)?; + let mut output = last_output.output.clone(); + batch.delete(&output.key_id, &output.mmr_index)?; + output.mmr_index = mmr_index; + batch.save(output)?; + batch.commit()?; + } + + let empty_params = MixnetReqCreationParams { + server_keys: vec![], + fee_per_hop: params.fee_per_hop, + }; + assert!(api1 + .create_mwixnet_req(mask1, &empty_params, &last_output.commit, true) + .is_err()); + + let too_many_params = MixnetReqCreationParams { + server_keys: vec![params.server_keys[0]; MAX_MWIXNET_HOPS + 1], + fee_per_hop: params.fee_per_hop, + }; + assert!(api1 + .create_mwixnet_req(mask1, &too_many_params, &last_output.commit, true) + .is_err()); + + let oversized_fee_params = MixnetReqCreationParams { + server_keys: params.server_keys[..2].to_vec(), + fee_per_hop: Some(1 << 39), + }; + assert_eq!( + api1.create_mwixnet_req(mask1, &oversized_fee_params, &last_output.commit, true) + .unwrap_err(), + libwallet::Error::Fee("mwixnet total fee exceeds FeeFields limit".to_string()) + ); + + for fee in [0, 12_499_999] { + let invalid_params = MixnetReqCreationParams { + server_keys: params.server_keys.clone(), + fee_per_hop: Some(fee), + }; + assert_eq!( + api1.create_mwixnet_req(mask1, &invalid_params, &last_output.commit, true) + .unwrap_err(), + libwallet::Error::Fee("mwixnet fee is below the swap minimum 0.0125".to_string()) + ); + } + let custom_params = MixnetReqCreationParams { + server_keys: params.server_keys.clone(), + fee_per_hop: Some(25_000_000), + }; + let custom = api1.create_mwixnet_req(mask1, &custom_params, &last_output.commit, false)?; + let mut onion = custom.request.onion; + for server_key in [&server_key_1, &server_key_2, &server_key_3] { + let peeled = onion.peel_layer(server_key).unwrap(); + assert_eq!(peeled.payload.fee, FeeFields::try_from(25_000_000u64)?); + onion = peeled.onion; + } + + drop(secp); + + // Failed refresh must not create or lock a swap + let tx_count = api1.retrieve_txs(mask1, false, None, None, None)?.1.len(); + let (disconnected, receiver) = std::sync::mpsc::channel(); + drop(receiver); + let original_proxy = std::mem::replace(&mut *client1.proxy_tx.lock(), disconnected); + let mut api1 = api1; + let result = wallet::command::mwixnet( + &mut api1, 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)?; - - 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); - - Ok(()) + wallet::command::MwixnetArgs { + server: "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion".try_into()?, + output: wallet::command::MwixnetOutput::Commitment(last_output.commit), + minimum_confirmations: 1, + params: MixnetReqCreationParams { + server_keys: params.server_keys.clone(), + fee_per_hop: None, + }, }, - )?; + ); + *client1.proxy_tx.lock() = original_proxy; + assert!(result + .unwrap_err() + .to_string() + .contains("Could not refresh wallet outputs")); + assert_eq!( + api1.retrieve_txs(mask1, false, None, None, None)?.1.len(), + tx_count + ); + let outputs = api1.retrieve_outputs(mask1, false, false, None)?.1; + assert_eq!( + outputs + .iter() + .find(|o| o.commit == last_output.commit) + .unwrap() + .output + .status, + OutputStatus::Unspent + ); + + let creation = api1.create_mwixnet_req(mask1, ¶ms, &last_output.commit, true)?; + let creation_tx_id = creation.tx_id.unwrap(); + let fee_per_hop = 12_500_000; + let mut onion = creation.request.onion.clone(); + for server_key in [&server_key_1, &server_key_2, &server_key_3] { + let peeled = onion + .peel_layer(server_key) + .map_err(|e| libwallet::Error::GenericError(e.to_string()))?; + assert_eq!(peeled.payload.fee, FeeFields::try_from(fee_per_hop)?); + onion = peeled.onion; + } + + println!("MWIXNET REQ: {:?}", creation.request); + + // Check the input lock and expected output are tracked together. + let outputs = api1.retrieve_outputs(mask1, false, false, None)?; + let input = outputs + .1 + .iter() + .find(|o| o.commit == last_output.commit) + .unwrap(); + assert_eq!(input.output.status, OutputStatus::Locked); + assert_eq!(input.output.mmr_index, mmr_index); + let total_fee = fee_per_hop * params.server_keys.len() as u64; + let expected_amount = last_output.output.value - total_fee; + let expected_output = outputs + .1 + .iter() + .find(|o| o.output.status == OutputStatus::Unconfirmed && o.output.value == expected_amount) + .unwrap(); + assert_eq!( + input.output.tx_log_entry, + expected_output.output.tx_log_entry + ); + + let txs = api1.retrieve_txs(mask1, false, None, None, None)?.1; + let tx = txs.last().unwrap(); + assert_eq!(creation_tx_id, tx.id); + assert_eq!(tx.tx_type, TxLogEntryType::TxSent); + assert_eq!(tx.amount_debited, last_output.output.value); + assert_eq!(tx.amount_credited, expected_amount); + assert_eq!(tx.num_inputs, 1); + assert_eq!(tx.num_outputs, 1); + assert_eq!(tx.fee, Some(FeeFields::try_from(total_fee)?)); + + assert!(api1 + .create_mwixnet_req(mask1, ¶ms, &last_output.commit, false) + .is_err()); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/no_change.rs b/controller/tests/no_change.rs index 41c46e9..2186c6b 100644 --- a/controller/tests/no_change.rs +++ b/controller/tests/no_change.rs @@ -59,10 +59,11 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -72,10 +73,11 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -92,109 +94,67 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let fee = core::libtx::tx_fee(1, 1, 1); // 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( - 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(()) - }, - )?; + 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() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; + println!("Posted Slate: {:?}", slate); + let mut stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); + api1.post_tx(mask1, &slate, false)?; // 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( - 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(()) - }, - )?; + let (refreshed, txs) = api1.retrieve_txs(mask1, 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); // Refresh and check transaction log for wallet 2 - 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(()) - }, - )?; + let (refreshed, txs) = api2.retrieve_txs(mask2, 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); // ensure invoice TX works as well with no change - 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 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward - fee, + ..Default::default() + }; + slate = api2.issue_invoice_tx(mask2, args)?; - 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 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 = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; // wallet 2 finalizes and posts { @@ -222,54 +182,30 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { 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(()) - }, - )?; + println!("Invoice Posted TX: {}", slate); + stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); + api2.post_tx(mask2, &slate, false)?; // check wallet 2's version - 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(()) - }, - )?; + let (refreshed, txs) = api2.retrieve_txs(mask2, 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); + } // Refresh and check transaction log for wallet 1 - 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 (refreshed, txs) = api1.retrieve_txs(mask1, 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); + } // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/payment_proofs.rs b/controller/tests/payment_proofs.rs index 651e486..b72b98e 100644 --- a/controller/tests/payment_proofs.rs +++ b/controller/tests/payment_proofs.rs @@ -21,7 +21,6 @@ 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; @@ -29,6 +28,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// Various tests on accounts within the same wallet fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -45,10 +45,11 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -58,10 +59,11 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -77,99 +79,74 @@ fn payment_proofs_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 mut address = None; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - }, - )?; + let address = Some(api2.get_slatepack_address(mask2, SlatepackAddressIndex(0))?); println!("Public address is: {:?}", address); let amount = 60_000_000_000; let mut slate = Slate::blank(1, false); - 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)?; + // 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, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, 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)?; + api1.tx_lock_outputs(mask1, &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) = api1.retrieve_txs(mask1, 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, SlatepackAddressIndex(1)); + 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 = api1.retrieve_payment_proof(mask1, 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 = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, true)?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); - 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))?; + // Check payment proof here + let mut pp = api1.retrieve_payment_proof(mask1, 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 = api1.verify_payment_proof(mask1, &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 = api1.verify_payment_proof(mask1, &pp); + assert!(res.is_err()); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/repost.rs b/controller/tests/repost.rs index 0718364..6ad6b3d 100644 --- a/controller/tests/repost.rs +++ b/controller/tests/repost.rs @@ -21,7 +21,7 @@ extern crate grin_wallet_libwallet as libwallet; use grin_core as core; use std::path::PathBuf; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; use impls::{PathToSlate, SlateGetter as _, SlatePutter as _}; use std::sync::atomic::Ordering; @@ -49,9 +49,10 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -60,9 +61,10 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -75,33 +77,16 @@ 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; - // add some accounts - 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(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut bh = 10u64; let _ = @@ -110,34 +95,24 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let send_file = format!("{}/part_tx_1.tx", test_dir); let receive_file = format!("{}/part_tx_2.tx", test_dir); - let mut slate = Slate::blank(2, false); - // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - 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 (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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 = api1.init_send_tx(mask1, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, false)?; + api1.tx_lock_outputs(mask1, &slate)?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; @@ -145,7 +120,7 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> // wallet 1 receives file to different account, completes { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("listener")?; + w.set_account_by_name("listener")?; } wallet::controller::foreign_single_use( @@ -163,154 +138,89 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> // wallet 1 receives file to different account, completes { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } // wallet 1 finalize - 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(()) - }, - )?; + slate = PathToSlate((&receive_file).into()).get_tx()?.0; + slate = api1.finalize_tx(mask1, &slate)?; // Now repost from cached - 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 (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + println!("TXS[0]: {:?}", txs[0]); + let stored_tx = api1.get_stored_tx(mask1, None, Some(&txs[0].tx_slate_id.unwrap()))?; + println!("Stored tx: {:?}", stored_tx); + api1.post_tx(mask1, &slate, false)?; + bh += 1; 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( - 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(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("listener")?; + w.set_account_by_name("listener")?; } - 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(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); - // as above, but syncronously + // as above, but synchronously { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } - let mut slate = Slate::blank(2, false); let amount = 60_000_000_000; - 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(()) - }, - )?; + // 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 = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Now repost from cached - 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 (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let stored_tx_slate = api1.get_stored_tx(mask1, Some(txs[0].id), None)?.unwrap(); + api1.post_tx(mask1, &stored_tx_slate, false)?; + bh += 1; 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( - 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( - 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(()) - }, - )?; + // update/test contents of both accounts + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 4); + + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * amount); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/revert.rs b/controller/tests/revert.rs index ef5a887..abd27af 100644 --- a/controller/tests/revert.rs +++ b/controller/tests/revert.rs @@ -23,33 +23,25 @@ use grin_core::core::Transaction; use grin_core::global; use grin_keychain::ExtKeychain; use grin_util::secp::key::SecretKey; -use grin_util::Mutex; -use grin_wallet_controller::controller::owner_single_use as owner; +use grin_wallet_api::Owner; use grin_wallet_impls::test_framework::*; use grin_wallet_impls::{DefaultLCProvider, PathToSlate, SlatePutter}; 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; use std::time::Duration; -type Wallet = Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, +type Wallet = grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, >; +#[allow(clippy::type_complexity)] fn revert( test_dir: &'static str, ) -> Result< @@ -63,6 +55,8 @@ fn revert( Option, Wallet, Option, + Owner, LocalWalletClient, ExtKeychain>, + Owner, LocalWalletClient, ExtKeychain>, ), libwallet::Error, > { @@ -82,7 +76,8 @@ fn revert( "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = mask1_i.as_ref(); @@ -94,28 +89,23 @@ fn revert( "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running - std::thread::spawn(move || { + thread::spawn(move || { if let Err(e) = wallet_proxy.run() { error!("Wallet Proxy error: {}", e); } }); - owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { - api.create_account_path(m, "a")?; - api.set_active_account(m, "a")?; - Ok(()) - })?; + api1.create_account_path(mask1, "a")?; + api1.set_active_account(mask1, "a")?; - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - api.create_account_path(m, "b")?; - api.set_active_account(m, "b")?; - Ok(()) - })?; + api2.create_account_path(mask2, "b")?; + api2.set_active_account(mask2, "b")?; let reward = core::consensus::REWARD; let cm = global::coinbase_maturity() as u64; @@ -126,76 +116,60 @@ fn revert( award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false)?; // Sanity check contents - 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); - assert_eq!(info.total, bh * reward); - assert_eq!(info.amount_currently_spendable, (bh - cm) * reward); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); - assert_eq!(info.total, c); - assert_eq!(txs.len(), bh as usize); - Ok(()) - })?; + let (refreshed, info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, bh * reward); + assert_eq!(info.amount_currently_spendable, (bh - cm) * reward); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_eq!(info.total, c); + assert_eq!(txs.len(), bh as usize); - 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); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 0); // Send some funds - let mut tx = None; - owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: None, - amount: sent, - minimum_confirmations: cm, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..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)?; - let slate = client1.send_tx_slate_direct("wallet2", &slate)?; - let slate = api.finalize_tx(m, &slate)?; - tx = slate.tx; - - Ok(()) - })?; - let tx = tx.expect("tx from slate"); + // send to send + let args = InitTxArgs { + src_acct_name: None, + amount: sent, + minimum_confirmations: cm, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + let send_file = format!("{}/part_tx_1.tx", test_dir); + PathToSlate(send_file.into()).put_tx(&slate, false)?; + api1.tx_lock_outputs(mask1, &slate)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate)?; + let slate = api1.finalize_tx(mask1, &slate)?; + let tx = slate.tx.expect("tx from slate"); // Check funds have been received - 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); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); - assert!(!tx.confirmed); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + assert!(!&txs[0].confirmed); // Update parallel chain assert_eq!(chain2.head_header().unwrap().height, 0); @@ -208,8 +182,13 @@ fn revert( // Build 2 blocks at same height: 1 with the tx, 1 without let head = chain.head_header().unwrap(); - let block_with = - create_block_for_wallet(&chain, head.clone(), &[tx.clone()], wallet1.clone(), mask1)?; + let block_with = create_block_for_wallet( + &chain, + head.clone(), + std::slice::from_ref(&tx), + wallet1.clone(), + mask1, + )?; let block_without = create_block_for_wallet(&chain, head, &[], wallet1.clone(), mask1)?; // Add block with tx to the chain @@ -223,23 +202,19 @@ fn revert( let bh = bh + 1; // Check funds have been confirmed - 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); - assert_eq!(info.total, sent); - assert_eq!(info.amount_currently_spendable, sent); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); - assert!(tx.confirmed); - assert!(tx.kernel_excess.is_some()); - assert!(tx.reverted_after.is_none()); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, sent); + assert_eq!(info.amount_currently_spendable, sent); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + assert!(&txs[0].confirmed); + assert!(&txs[0].kernel_excess.is_some()); + assert!(&txs[0].reverted_after.is_none()); // Attach more blocks to the parallel chain, making it the longest one award_block_to_wallet(&chain2, &[], wallet1.clone(), mask1)?; @@ -258,32 +233,29 @@ fn revert( let bh = bh + 1; // Check funds have been reverted - 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); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, sent); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReverted); - assert!(!tx.confirmed); - assert!(tx.reverted_after.is_some()); - Ok(()) - })?; + api2.scan(mask2, None, false)?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, sent); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReverted); + assert!(!&txs[0].confirmed); + assert!(&txs[0].reverted_after.is_some()); stopper2.store(false, Ordering::Relaxed); Ok(( - chain, stopper, sent, bh, tx, wallet1, mask1_i, wallet2, mask2_i, + chain, stopper, sent, bh, tx, wallet1, mask1_i, wallet2, mask2_i, api1, api2, )) } fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { - let (chain, stopper, sent, bh, tx, wallet1, mask1_i, wallet2, mask2_i) = revert(test_dir)?; + let (chain, stopper, sent, bh, tx, wallet1, mask1_i, _wallet2, mask2_i, _api1, api2) = + revert(test_dir)?; let mask1 = mask1_i.as_ref(); let mask2 = mask2_i.as_ref(); @@ -293,22 +265,19 @@ fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let bh = bh + 1; // Check funds have been confirmed again - 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); - assert_eq!(info.total, sent); - assert_eq!(info.amount_currently_spendable, sent); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); - assert!(tx.confirmed); - assert!(tx.reverted_after.is_none()); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, sent); + assert_eq!(info.amount_currently_spendable, sent); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + let tx = &txs[0]; + assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); + assert!(tx.confirmed); + assert!(tx.reverted_after.is_none()); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -317,41 +286,37 @@ fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } fn revert_cancel_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { - let (_, stopper, sent, bh, _, _, _, wallet2, mask2_i) = revert(test_dir)?; + let (_, stopper, sent, bh, _, _, _, _wallet2, mask2_i, _api1, api2) = revert(test_dir)?; let mask2 = mask2_i.as_ref(); - // Cancelling tx - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - // Sanity check - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, sent); + // Sanity check + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, sent); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + let tx = &txs[0]; - // Cancel - api.cancel_tx(m, Some(tx.id), None)?; + // Cancel + api2.cancel_tx(mask2, Some(tx.id), None)?; - // Check updated summary info - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, 0); + // Check updated summary info + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, 0); - // Check updated tx log - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceivedCancelled); - Ok(()) - })?; + // Check updated tx log + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + let tx = &txs[0]; + assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceivedCancelled); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/self_send.rs b/controller/tests/self_send.rs index 6cf572e..0c18640 100644 --- a/controller/tests/self_send.rs +++ b/controller/tests/self_send.rs @@ -30,6 +30,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// self send impl fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -48,9 +49,10 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -63,99 +65,67 @@ 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut bh = 10u64; let _ = 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( + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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 = api1.init_send_tx(mask1, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + // Send directly to self + wallet::controller::foreign_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; + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, Some("listener"), None)?; Ok(()) }, )?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, false)?; // mines a block + bh += 1; 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( - 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(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'listener' account { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("listener")?; + w.set_account_by_name("listener")?; } - 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 (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -172,3 +142,63 @@ fn wallet_self_send() { } clean_output_dir(test_dir); } + +#[test] +fn late_lock_self_send_proof() -> Result<(), libwallet::Error> { + let test_dir = "test_output/late_lock_self_send_proof"; + setup(test_dir); + let mut wallet_proxy = create_wallet_proxy(test_dir); + let chain = wallet_proxy.chain.clone(); + let stopper = wallet_proxy.running.clone(); + create_wallet_and_add!( + client1, + wallet1, + mask1_i, + test_dir, + "wallet1", + None, + &mut wallet_proxy, + false, + api1 + ); + let mask1 = mask1_i.as_ref(); + let worker = thread::spawn(move || wallet_proxy.run()); + + let result = (|| { + test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false)?; + let mut slate = api1.init_send_tx( + mask1, + InitTxArgs { + amount: core::consensus::REWARD, + minimum_confirmations: 2, + late_lock: Some(true), + payment_proof_recipient_address: Some( + api1.get_slatepack_address(mask1, SlatepackAddressIndex(0))?, + ), + ..Default::default() + }, + )?; + wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, None, None)?; + Ok(()) + }, + )?; + let (_, txs) = api1.retrieve_txs(mask1, false, None, Some(slate.id), None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + + api1.finalize_tx(mask1, &slate).map(|_| ()) + })(); + + stopper.store(false, Ordering::Relaxed); + worker.join().unwrap()?; + drop(api1); + drop(wallet1); + drop(chain); + clean_output_dir(test_dir); + result +} diff --git a/controller/tests/self_send_cancel.rs b/controller/tests/self_send_cancel.rs index 492ecf5..16ad425 100644 --- a/controller/tests/self_send_cancel.rs +++ b/controller/tests/self_send_cancel.rs @@ -48,9 +48,10 @@ fn self_send_cancel_test_impl(test_dir: &'static str) -> Result<(), libwallet::E "wallet1", None, &mut wallet_proxy, - true + true, + _api ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -67,45 +68,40 @@ 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( - 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(()) - }, - )?; + common::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))?; + bh += 1; + Ok(()) + })?; - wallet::controller::owner_single_use( + common::owner_single_use( wallet1.clone(), mask1, PathBuf::from(test_dir), diff --git a/controller/tests/slatepack.rs b/controller/tests/slatepack.rs index 9322d95..9057d97 100644 --- a/controller/tests/slatepack.rs +++ b/controller/tests/slatepack.rs @@ -20,25 +20,30 @@ extern crate grin_wallet_impls as impls; use grin_core as core; use grin_wallet_config::GlobalWalletConfig; use grin_wallet_libwallet as libwallet; -use std::path::PathBuf; - use impls::test_framework::{self, LocalWalletClient}; -use impls::{PathToSlatepack, SlatePutter as _}; +use impls::DefaultLCProvider; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; use std::sync::atomic::Ordering; -use std::thread; use std::time::Duration; +use std::{fs, thread}; use grin_wallet_libwallet::{ - InitTxArgs, InitTxSendArgs, IssueInvoiceTxArgs, Slate, SlateState, Slatepack, SlatepackAddress, - Slatepacker, SlatepackerArgs, + slatepack, Error, InitTxArgs, InitTxSendArgs, IssueInvoiceTxArgs, Slate, Slatepack, + SlatepackAddress, SlatepackBin, WalletHandle, }; -use ed25519_dalek::SigningKey as edDalekSecretKey; use ed25519_dalek::VerifyingKey as edDalekPublicKey; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_keychain::ExtKeychain; +use grin_util::secp::SecretKey; +use grin_wallet_libwallet::api_impl::owner::{decrypt_slatepack, deserialize_slatepack}; +use grin_wallet_libwallet::slatepack::{get_slatepack_file_contents, SlatepackAddressIndex}; +use grin_wallet_util::byte_ser; fn output_slatepack( slate: &Slate, @@ -47,35 +52,55 @@ fn output_slatepack( use_bin: bool, sender: Option, recipients: Vec, -) -> Result<(), libwallet::Error> { - let packer = Slatepacker::new(SlatepackerArgs { - sender, - recipients, - dec_key: None, - }); +) -> Result<(), Error> { let mut file = file.into(); if armored { file = format!("{}.armored", file); } - PathToSlatepack::new(file.into(), &packer, armored).put_tx(&slate, use_bin) + let slatepack = slate.create_slatepack(sender, recipients)?; + let mut pub_tx = File::create(&file)?; + if use_bin { + if armored { + let armored = slatepack.armor()?; + pub_tx.write_all(armored.as_bytes())?; + } else { + pub_tx.write_all( + &byte_ser::to_bytes(&SlatepackBin(slatepack)).map_err(|_| Error::SlatepackSer)?, + )?; + } + } else { + pub_tx.write_all( + serde_json::to_string_pretty(&slatepack) + .map_err(|_| Error::SlateSer)? + .as_bytes(), + )?; + } + pub_tx.sync_all()?; + Ok(()) } fn slate_from_packed( + wallet_inst: WalletHandle< + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, + >, + keychain_mask: Option<&SecretKey>, file: &str, armored: bool, - dec_key: Option<&edDalekSecretKey>, -) -> Result<(Slatepack, Slate), libwallet::Error> { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key, - }); +) -> Result<(Slatepack, Slate), Error> { let mut file = file.into(); if armored { file = format!("{}.armored", file); } - let slatepack = PathToSlatepack::new(file.into(), &packer, armored).get_slatepack(true)?; - Ok((slatepack.clone(), packer.get_slate(&slatepack)?)) + let data = get_slatepack_file_contents(&file.into())?; + let slatepack = deserialize_slatepack( + &data, + wallet_inst, + keychain_mask, + vec![SlatepackAddressIndex(0)], + )?; + Ok((slatepack.clone(), slatepack.get_slate()?)) } /// self send impl @@ -85,8 +110,7 @@ fn slatepack_exchange_test_impl( use_armored: bool, use_encryption: bool, target_slate_version: Option, -) -> Result<(), libwallet::Error> { - let expected_slate_version = target_slate_version.unwrap_or(4); +) -> Result<(), Error> { // Create a new proxy to simulate server and wallet responses let mut wallet_proxy = create_wallet_proxy(test_dir); let chain = wallet_proxy.chain.clone(); @@ -102,9 +126,10 @@ fn slatepack_exchange_test_impl( "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -113,9 +138,10 @@ fn slatepack_exchange_test_impl( "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -128,84 +154,55 @@ fn slatepack_exchange_test_impl( let reward = core::consensus::REWARD; // add some accounts - 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(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; - // add some accounts - 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(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; - // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } + + { + wallet_inst!(wallet2, w); + w.set_account_by_name("account1")?; + } + + // Get some mining done let mut bh = 10u64; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let (recipients_1, dec_key_1, sender_1) = match use_encryption { + let (recipients_1, sender_1) = match use_encryption { true => { - let mut rec_address = SlatepackAddress::random(); - 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), - Some(rec_address.clone()), - ) + let sec_key = api1.get_slatepack_secret_key(mask1, SlatepackAddressIndex(0))?; + let pub_key = edDalekPublicKey::from(&sec_key); + let rec_address = SlatepackAddress::new(&pub_key); + + let sen_index = SlatepackAddressIndex(7); + let sec_key = api1.get_slatepack_secret_key(mask1, sen_index)?; + let pub_key = edDalekPublicKey::from(&sec_key); + let sen_address = SlatepackAddress::new(&pub_key); + (vec![rec_address.clone()], Some(sen_address.clone())) } - false => (vec![], None, None), + false => (vec![], None), }; - let (recipients_2, dec_key_2, sender_2) = match use_encryption { + let (recipients_2, sender_2) = match use_encryption { true => { - let mut rec_address = SlatepackAddress::random(); - 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), - Some(rec_address.clone()), - ) + let sec_key = api2.get_slatepack_secret_key(mask2, SlatepackAddressIndex(0))?; + let pub_key = edDalekPublicKey::from(&sec_key); + let rec_address = SlatepackAddress::new(&pub_key); + + let sen_index = SlatepackAddressIndex(11); + let sec_key = api2.get_slatepack_secret_key(mask2, sen_index)?; + let pub_key = edDalekPublicKey::from(&sec_key); + let sen_address = SlatepackAddress::new(&pub_key); + (vec![rec_address.clone()], Some(sen_address.clone())) } - false => (vec![], None, None), + false => (vec![], None), }; let (send_file, receive_file, final_file) = match use_bin { @@ -221,50 +218,39 @@ fn slatepack_exchange_test_impl( ), }; - 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, - target_slate_version, - ..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(()) - }, + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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 { + target_slate_version, + address_index: Some(SlatepackAddressIndex(7)), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_1.clone(), + recipients_2.clone(), )?; + api1.tx_lock_outputs(mask1, &slate)?; - // Get some mining done - { - wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("account1")?; - } - - let (mut slatepack, mut slate) = - slate_from_packed(&send_file, use_armored, (&dec_key_2).as_ref())?; - assert_eq!(slate.version_info.version, expected_slate_version); + let (slatepack, mut slate) = + slate_from_packed(wallet2.clone(), mask2, &send_file, use_armored)?; + assert_eq!( + slate.version_info.version, + target_slate_version.unwrap_or(4) + ); // wallet 2 receives file, completes, sends file back wallet::controller::foreign_single_use( @@ -278,8 +264,8 @@ fn slatepack_exchange_test_impl( &receive_file, use_armored, use_bin, - // re-encrypt for sender! sender_2.clone(), + // re-encrypt for sender! match slatepack.sender.clone() { Some(s) => vec![s.clone()], None => vec![], @@ -290,54 +276,42 @@ fn slatepack_exchange_test_impl( )?; // 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())?; - assert_eq!(slate.version_info.version, expected_slate_version); - slate = api.finalize_tx(m, &slate)?; - assert_eq!(slate.version_info.version, expected_slate_version); - // 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 (slatepack, mut slate) = + slate_from_packed(wallet1.clone(), mask1, &receive_file, use_armored)?; + assert_eq!( + slate.version_info.version, + target_slate_version.unwrap_or(4) + ); + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + output_slatepack( + &slate, + &final_file, + use_armored, + use_bin, + sender_1.clone(), + match slatepack.sender { + Some(s) => vec![s.clone()], + None => vec![], }, )?; + api1.post_tx(mask1, &slate, false)?; + bh += 1; 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( - 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 1 account + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); - // Check total in 'wallet 2' account - 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(()) - }, - )?; + // Check total in wallet 2 account + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * reward); // Now other types of exchange, for reference // Invoice transaction @@ -354,89 +328,60 @@ fn slatepack_exchange_test_impl( ), }; - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let args = IssueInvoiceTxArgs { - amount: 1000000000, - target_slate_version, - ..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(()) - }, + let args = IssueInvoiceTxArgs { + target_slate_version, + address_index: Some(SlatepackAddressIndex(11)), + amount: 1000000000, + ..Default::default() + }; + let slate = api2.issue_invoice_tx(mask2, args)?; + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_2.clone(), + recipients_1.clone(), )?; - 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; - assert_eq!(slate.version_info.version, expected_slate_version); - 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; - assert_eq!(slate.version_info.version, expected_slate_version); - slate = api.finalize_tx(&slate, false)?; - assert_eq!(slate.version_info.version, expected_slate_version); - 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(()) + let args = InitTxArgs { + target_slate_version, + 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 (slatepack, mut slate) = + slate_from_packed(wallet1.clone(), mask1, &send_file, use_armored)?; + assert_eq!( + slate.version_info.version, + target_slate_version.unwrap_or(4) + ); + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + output_slatepack( + &slate, + &receive_file, + use_armored, + use_bin, + sender_1.clone(), + match slatepack.sender { + Some(s) => vec![s.clone()], + None => vec![], }, )?; + // Wallet 2 receives the invoice transaction + let (_, mut slate) = slate_from_packed(wallet2.clone(), mask2, &receive_file, use_armored)?; + assert_eq!( + slate.version_info.version, + target_slate_version.unwrap_or(4) + ); + slate = api2.finalize_tx(mask2, &slate)?; + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + api2.post_tx(mask2, &slate, false)?; // Standard, with payment proof let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); @@ -453,63 +398,50 @@ fn slatepack_exchange_test_impl( ), }; - let mut slate = Slate::blank(2, true); - let mut address = None; - 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( - 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(()) - }, + // send from 1st wallet + let args = InitTxArgs { + target_slate_version, + address_index: Some(SlatepackAddressIndex(7)), + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: Some( + api2.get_slatepack_address(mask2, SlatepackAddressIndex(0))?, + ), + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_1, + recipients_2.clone(), )?; + api1.tx_lock_outputs(mask1, &slate)?; + // receive at 2nd wallet 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; + let (slatepack, mut slate) = + slate_from_packed(wallet2.clone(), mask2, &send_file, use_armored)?; + assert_eq!( + slate.version_info.version, + target_slate_version.unwrap_or(4) + ); slate = api.receive_tx(&slate, None, None)?; output_slatepack( &slate, &receive_file, use_armored, use_bin, - sender_2, + sender_2.clone(), match slatepack.sender { Some(s) => vec![s.clone()], None => vec![], @@ -519,22 +451,17 @@ fn slatepack_exchange_test_impl( }, )?; - // wallet 1 finalises and posts - 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(()) - }, - )?; + // wallet 1 finalizes and posts + let res = slate_from_packed(wallet1.clone(), mask1, &receive_file, use_armored)?; + assert_eq!( + res.1.version_info.version, + target_slate_version.unwrap_or(4) + ); + slate = res.1; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + api1.post_tx(mask1, &slate, false)?; // let logging finish stopper.store(false, Ordering::Relaxed); @@ -560,9 +487,10 @@ fn slatepack_api_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -579,50 +507,169 @@ 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( - wallet1.clone(), + let args = InitTxArgs { + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + for index in [SlatepackAddressIndex::MAX + 1, u32::MAX] { + assert!(matches!( + api1.init_send_tx( + mask1, + InitTxArgs { + address_index: Some(SlatepackAddressIndex(index)), + ..args.clone() + } + ), + Err(Error::SlatepackAddress(_)) + )); + assert!(matches!( + api1.issue_invoice_tx( + mask1, + IssueInvoiceTxArgs { + amount: reward, + address_index: Some(SlatepackAddressIndex(index)), + ..Default::default() + } + ), + Err(Error::SlatepackAddress(_)) + )); + } + api1.init_send_tx( 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)?; - let recipient_key = edDalekSecretKey::from_bytes(&[1u8; 32]); - let recipient = SlatepackAddress::new(&edDalekPublicKey::from(&recipient_key)); - let slatepack = api.create_slatepack_message(m, &slate, Some(0), vec![recipient])?; - println!("{}", slatepack); - let recipient_packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: Some(&recipient_key), - }); - let recipient_copy = recipient_packer.deser_slatepack(slatepack.as_bytes(), true)?; - recipient_packer.get_slate(&recipient_copy)?; - 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); - // wrong active account, the error names the right one - let own_address = api.get_slatepack_address(m, 0)?; - let own_slatepack = - api.create_slatepack_message(m, &slate, Some(0), vec![own_address])?; - api.create_account_path(m, "second")?; - api.set_active_account(m, "second")?; - let err = api - .slate_from_slatepack_message(m, own_slatepack, vec![0]) - .unwrap_err(); - assert!(err.to_string().contains("account 'default'"), "{}", err); - api.set_active_account(m, "default")?; - Ok(()) + InitTxArgs { + estimate_only: Some(true), + ..args.clone() }, )?; + let slate = api1.init_send_tx(mask1, args)?; + // Both the recipient and sender can decrypt the contract's reply. + let recipient_key = ed25519_dalek::SigningKey::from_bytes(&[1; 32]); + let recipient = SlatepackAddress::new(&edDalekPublicKey::from(&recipient_key)); + let message = api1.create_slatepack_message( + mask1, + &slate, + Some(SlatepackAddressIndex(0)), + vec![recipient], + )?; + let mut recipient_copy = libwallet::api_impl::owner::parse_slatepack(message.as_bytes())?; + recipient_copy.try_decrypt_payload(Some(&recipient_key))?; + recipient_copy.get_slate()?; + api1.slate_from_slatepack_message(mask1, message.clone(), vec![SlatepackAddressIndex(0)])?; + api1.create_account_path(mask1, "second")?; + api1.set_active_account(mask1, "second")?; + let err = api1 + .slate_from_slatepack_message(mask1, message, vec![SlatepackAddressIndex(0)]) + .unwrap_err(); + assert!(err.to_string().contains("account 'default'"), "{}", err); + api1.set_active_account(mask1, "default")?; + // create an encrypted slatepack (just encrypted for self) + let address_index = SlatepackAddressIndex(0); + let enc_addr = api1.get_slatepack_address(mask1, address_index)?; + let slatepack = + api1.create_slatepack_message(mask1, &slate, Some(address_index), vec![enc_addr])?; + let mut encrypted = api1.decode_slatepack_message(mask1, slatepack.clone(), vec![])?; + assert!(encrypted.is_encrypted()); + decrypt_slatepack(&mut encrypted, wallet1.clone(), mask1, vec![address_index])?; + assert_eq!(encrypted.get_slate()?.id, slate.id); + let slatepack_raw = + api1.decode_slatepack_message(mask1, slatepack.clone(), vec![address_index])?; + assert!(!slatepack_raw.is_encrypted()); + assert_eq!(slatepack_raw.get_slate()?.id, slate.id); + let decoded_slate = api1.slate_from_slatepack_message(mask1, slatepack, vec![address_index])?; + assert_eq!(decoded_slate.id, slate.id); + + let unknown_index = SlatepackAddressIndex(77); + let unknown_address = api1.get_slatepack_address(mask1, unknown_index)?; + let message = api1.create_slatepack_message(mask1, &slate, None, vec![unknown_address])?; + let encrypted = api1.decode_slatepack_message(mask1, message.clone(), vec![])?; + let decoded = api1.decode_slatepack_message(mask1, message.clone(), vec![address_index])?; + assert!(decoded.is_encrypted()); + assert_eq!(decoded.payload, encrypted.payload); + assert!(matches!( + api1.slate_from_slatepack_message(mask1, message.clone(), vec![address_index]), + Err(Error::SlatepackDecryption(_)) + )); + let mut api1 = api1; + assert!(matches!( + wallet::command::parse_slatepack(&mut api1, mask1, None, Some(message)), + Err(wallet::Error::LibWallet(Error::SlatepackDecryption(_))) + )); + + let index = { + wallet_inst!(wallet1, w); + w.get_private_context(mask1, slate.id.as_bytes())? + .payment_proof_derivation_index + .unwrap() + }; + assert_eq!(index, SlatepackAddressIndex(1)); + let address = api1.get_slatepack_address(mask1, index)?; + let message = api1.create_slatepack_message(mask1, &slate, None, vec![address])?; + let decoded = api1.decode_slatepack_message(mask1, message.clone(), vec![address_index])?; + assert!(!decoded.is_encrypted()); + assert_eq!(decoded.get_slate()?.id, slate.id); + + api1.create_account_path(mask1, "other")?; + api1.set_active_account(mask1, "other")?; + test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 6, false)?; + api1.set_active_account(mask1, "default")?; + let invoice = api1.issue_invoice_tx( + mask1, + IssueInvoiceTxArgs { + amount: reward, + dest_acct_name: Some("other".into()), + ..Default::default() + }, + )?; + let send = api1.init_send_tx( + mask1, + InitTxArgs { + amount: reward, + src_acct_name: Some("other".into()), + minimum_confirmations: 2, + ..Default::default() + }, + )?; + api1.set_active_account(mask1, "other")?; + let next = api1.issue_invoice_tx( + mask1, + IssueInvoiceTxArgs { + amount: reward, + ..Default::default() + }, + )?; + for (slate, expected) in [(&invoice, 1), (&send, 2), (&next, 3)] { + wallet_inst!(wallet1, w); + let context = w.get_private_context(mask1, slate.id.as_bytes())?; + assert_eq!(context.parent_key_id, w.parent_key_id()); + assert_eq!( + context.payment_proof_derivation_index, + Some(SlatepackAddressIndex(expected)) + ); + } + api1.set_active_account(mask1, "default")?; + let invoice = api1.issue_invoice_tx( + mask1, + IssueInvoiceTxArgs { + amount: reward, + ..Default::default() + }, + )?; + { + wallet_inst!(wallet1, w); + assert_eq!( + w.get_private_context(mask1, invoice.id.as_bytes())? + .payment_proof_derivation_index, + Some(SlatepackAddressIndex(2)) + ); + } + + api1.close_wallet(None)?; + let encrypted = api1.decode_slatepack_message(None, message, vec![])?; + assert!(encrypted.is_encrypted()); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -637,8 +684,7 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: let stopper = wallet_proxy.running.clone(); let config_path = PathBuf::from(test_dir).join("grin-wallet.toml"); GlobalWalletConfig::for_chain(&core::global::ChainTypes::AutomatedTesting, &config_path) - .write_to_file(config_path.to_str().unwrap(), false, None, None) - .unwrap(); + .write_to_file(config_path.to_str().unwrap(), false, None, None)?; create_wallet_and_add!( client1, @@ -648,9 +694,10 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -660,9 +707,10 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); let proxy_thread = thread::spawn(move || { if let Err(e) = wallet_proxy.run() { @@ -672,62 +720,65 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: let reward = core::consensus::REWARD; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 6, false); - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use(wallet2.clone(), mask2, config_path.clone(), |api, m| { - slate = api.issue_invoice_tx( - m, - IssueInvoiceTxArgs { - amount: reward, - ..Default::default() - }, - )?; - Ok(()) - })?; - - wallet::controller::owner_single_use(wallet1.clone(), mask1, config_path, |api, m| { - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), + let slate = api2.issue_invoice_tx( + mask2, + IssueInvoiceTxArgs { amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, ..Default::default() - }; + }, + )?; - let mut wrong_net_args = args.clone(); - wrong_net_args.send_args = Some(InitTxSendArgs { - dest: "grin1dvge9z4uqgqlpspmljrd7smh3grrw9xu2r9lkz3u67s3emj3ud2sd5gk9p".to_string(), - post_tx: false, - fluff: false, - skip_tor: Some(true), - }); - assert!(api.init_send_tx(m, wrong_net_args.clone()).is_err()); - assert!(api.process_invoice_tx(m, &slate, wrong_net_args).is_err()); + let args = InitTxArgs { + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; - let mut invalid_args = args.clone(); - invalid_args.send_args = Some(InitTxSendArgs { - dest: "tgrinaddr10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqnlumr7" - .to_string(), - post_tx: false, - fluff: false, - skip_tor: Some(true), - }); - assert!(api.init_send_tx(m, invalid_args.clone()).is_err()); - assert!(api.process_invoice_tx(m, &slate, invalid_args).is_err()); + let mut wrong_net_args = args.clone(); + wrong_net_args.send_args = Some(InitTxSendArgs { + dest: "grin1dvge9z4uqgqlpspmljrd7smh3grrw9xu2r9lkz3u67s3emj3ud2sd5gk9p".to_string(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }); + assert!(api1.init_send_tx(mask1, wrong_net_args.clone()).is_err()); + assert!(api1 + .process_invoice_tx(mask1, &slate, wrong_net_args) + .is_err()); - let mut valid_args = args; - valid_args.send_args = Some(InitTxSendArgs { - dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".to_string(), - post_tx: false, - fluff: false, - skip_tor: Some(true), - }); - api.process_invoice_tx(m, &slate, valid_args.clone())?; - api.init_send_tx(m, valid_args)?; - Ok(()) - })?; + let mut invalid_args = args.clone(); + invalid_args.send_args = Some(InitTxSendArgs { + dest: "tgrinaddr10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqnlumr7".to_string(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }); + assert!(api1.init_send_tx(mask1, invalid_args.clone()).is_err()); + assert!(api1 + .process_invoice_tx(mask1, &slate, invalid_args) + .is_err()); + + let mut valid_args = args; + valid_args.send_args = Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".to_string(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }); + let missing_config = PathBuf::from(test_dir).join("missing.toml"); + let api = grin_wallet_api::Owner::new(wallet1.clone(), None, missing_config); + assert!(api + .process_invoice_tx(mask1, &slate, valid_args.clone()) + .is_err()); + { + wallet_inst!(wallet1, w); + assert!(w.get_private_context(mask1, slate.id.as_bytes()).is_err()); + } + api1.process_invoice_tx(mask1, &slate, valid_args.clone())?; + api1.init_send_tx(mask1, valid_args)?; stopper.store(false, Ordering::Relaxed); proxy_thread.join().expect("wallet proxy thread panicked"); @@ -735,11 +786,11 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: } #[test] -fn slatepack_exchange_json_v5() { - let test_dir = "test_output/slatepack_exchange_json_v5"; +fn slatepack_exchange_json() { + let test_dir = "test_output/slatepack_exchange_json"; setup(test_dir); - // Json output - if let Err(e) = slatepack_exchange_test_impl(test_dir, false, false, false, Some(5)) { + // JSON output + if let Err(e) = slatepack_exchange_test_impl(test_dir, false, false, false, None) { panic!("Libwallet Error: {}", e); } clean_output_dir(test_dir); @@ -771,7 +822,7 @@ fn slatepack_exchange_armored() { fn slatepack_exchange_json_enc() { let test_dir = "test_output/slatepack_exchange_json_enc"; setup(test_dir); - // Json output + // JSON output if let Err(e) = slatepack_exchange_test_impl(test_dir, false, false, true, None) { panic!("Libwallet Error: {}", e); } @@ -804,7 +855,7 @@ fn slatepack_exchange_armored_enc() { fn slatepack_api() { let test_dir = "test_output/slatepack_api"; setup(test_dir); - // Json output + // JSON output if let Err(e) = slatepack_api_impl(test_dir) { panic!("Libwallet Error: {}", e); } @@ -821,23 +872,70 @@ fn slatepack_address() { clean_output_dir(test_dir); } +#[test] +fn slatepack_file_contents() { + let test_dir = "test_output/slatepack_file_contents"; + setup(test_dir); + + fs::create_dir_all(test_dir).unwrap(); + let sp_path = PathBuf::from(test_dir).join("pack_file"); + + // set Slatepack file to minimum allowable size + { + let f = File::create(sp_path.clone()).unwrap(); + f.set_len(slatepack::min_size()).unwrap(); + } + + let mut pack_path = get_slatepack_file_contents(&sp_path); + assert!(pack_path.is_ok()); + + // set Slatepack file to maximum allowable size + { + let f = File::create(sp_path.clone()).unwrap(); + f.set_len(slatepack::max_size()).unwrap(); + } + pack_path = get_slatepack_file_contents(&sp_path); + assert!(pack_path.is_ok()); + + // set Slatepack file below minimum allowable size + { + let f = File::create(sp_path.clone()).unwrap(); + f.set_len(slatepack::min_size() - 1).unwrap(); + } + pack_path = get_slatepack_file_contents(&sp_path); + assert!(pack_path.is_err()); + + // set Slatepack file above maximum allowable size + { + let f = File::create(sp_path.clone()).unwrap(); + f.set_len(slatepack::max_size() + 1).unwrap(); + } + pack_path = get_slatepack_file_contents(&sp_path); + assert!(pack_path.is_err()); + clean_output_dir(test_dir); +} + +#[test] +fn slatepack_exchange_json_v5() { + let test_dir = "test_output/slatepack_exchange_json_v5"; + setup(test_dir); + // Json output + if let Err(e) = slatepack_exchange_test_impl(test_dir, false, false, false, Some(5)) { + panic!("Libwallet Error: {}", e); + } + clean_output_dir(test_dir); +} + #[test] fn slatepack_v4() { const V4_SLATEPACK: &str = include_str!("slates/v4.slatepack"); common::setup_global_chain_type(); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - let packed = packer - .deser_slatepack(V4_SLATEPACK.as_bytes(), false) - .unwrap(); - let slate = packer.get_slate(&packed).unwrap(); + let packed = libwallet::api_impl::owner::parse_slatepack(V4_SLATEPACK.as_bytes()).unwrap(); + let slate = packed.get_slate().unwrap(); assert_eq!(slate.version_info.version, 4); - assert_eq!(slate.state, SlateState::Standard2); + assert_eq!(slate.state, libwallet::SlateState::Standard2); assert_eq!(slate.participant_data.len(), 1); assert_eq!( slate @@ -852,7 +950,7 @@ fn slatepack_v4() { assert_eq!(tx.outputs().len(), 1); assert_eq!(tx.kernels().len(), 1); assert_eq!( - packer.create_slatepack(&slate).unwrap().payload, + slate.create_slatepack(None, vec![]).unwrap().payload, packed.payload ); } diff --git a/controller/tests/transaction.rs b/controller/tests/transaction.rs index 5425ef8..7a0e514 100644 --- a/controller/tests/transaction.rs +++ b/controller/tests/transaction.rs @@ -33,6 +33,8 @@ use std::time::Duration; mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_api::Owner; +use libwallet::InitTxSendArgs; /// Exercises the Transaction API fully with a test NodeClient operating /// directly on a chain instance @@ -51,9 +53,10 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); println!("Mask1: {:?}", mask1); create_wallet_and_add!( client2, @@ -63,9 +66,10 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); println!("Mask2: {:?}", mask2); // Set the wallet proxy listener running @@ -81,413 +85,425 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> // mine a few blocks 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( - 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(()) - }, - )?; + // Check wallet1 contents are as expected + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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); + } // assert wallet contents // and a single use api for a send command let amount = 60_000_000_000; let header_version = core::consensus::header_version(chain.head().unwrap().height).0; let mut slate = Slate::blank(1, false); - 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)?; + { + // Do not allow to send 0 + let error = api1 + .init_send_tx( + mask1, + InitTxArgs { + amount: 0, + ..Default::default() + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); - assert_eq!(slate_i.state, SlateState::Standard1); - assert_eq!(slate_i.version_info.block_header_version, header_version); + // Result amount can not be 0 when amount includes fee + let mut init_args = InitTxArgs { + amount_includes_fee: Some(true), + amount: 23_000_000, + estimate_only: Some(true), + ..Default::default() + }; + let est = api1.init_send_tx(mask1, init_args.clone())?; + assert_eq!(init_args.amount, est.fee_fields.fee()); - // 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); + init_args.estimate_only = None; + let error = api1.init_send_tx(mask1, init_args).unwrap_err(); + assert_eq!( + error, + libwallet::Error::GenericError( + "Transaction amount is too small to include fee".to_string() + ) + ); - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - assert_eq!(slate.state, SlateState::Standard2); + // 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, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; - // wallet2 already has this slate, so accepted versions fail on the duplicate check - for bhv in 1..=GRIN_BLOCK_HEADER_VERSION + 1 { - let mut s = slate_i.clone(); - s.version_info.block_header_version = bhv; - let res = wallet::controller::foreign_single_use( - wallet2.clone(), - PathBuf::from(test_dir), - mask2_i.clone(), - |api| api.receive_tx(&s, None, None).map(|_| ()), + assert_eq!(slate_i.state, SlateState::Standard1); + assert_eq!(slate_i.version_info.block_header_version, header_version); + + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + let mut zero_amount_slate = slate_i.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api.receive_tx(&zero_amount_slate, None, None).unwrap_err(), + libwallet::Error::InvalidAmount ); - if bhv <= GRIN_BLOCK_HEADER_VERSION { - assert!(matches!( - res, - Err(libwallet::Error::TransactionAlreadyReceived(_)) - )); - } else { - assert!(matches!(res, Err(libwallet::Error::Compatibility(_)))); - } - } - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - assert_eq!(slate.state, SlateState::Standard3); + Ok(()) + }, + )?; - // 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 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); + + // wallet2 already has this slate, so accepted versions fail on the duplicate check + for bhv in 1..=GRIN_BLOCK_HEADER_VERSION + 1 { + let mut s = slate_i.clone(); + s.version_info.block_header_version = bhv; + let res = wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| api.receive_tx(&s, None, None).map(|_| ()), ); + if bhv <= GRIN_BLOCK_HEADER_VERSION { + assert!(matches!( + res, + Err(libwallet::Error::TransactionAlreadyReceived(_)) + )); + } else { + assert!(matches!(res, Err(libwallet::Error::Compatibility(_)))); + } + } + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; + assert_eq!(slate.state, SlateState::Standard3); - Ok(()) - }, - )?; + // 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 transaction log for wallet 1 - 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(()) - }, - )?; + { + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (refreshed, txs) = api1.retrieve_txs(mask1, 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); + } // Check transaction log for wallet 2 - 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(()) - }, - )?; + { + let (refreshed, txs) = api2.retrieve_txs(mask2, 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); + } // post transaction - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + api1.post_tx(mask1, &slate, false)?; - // Check wallet 1 contents are as expected - 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 wallet1 contents are as expected + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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()); - - Ok(()) - }, - )?; + // check tx log entry is confirmed + let (refreshed, txs) = api1.retrieve_txs(mask1, 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()); + } // 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( - 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(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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 + ); + } - 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); + { + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, 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) = api2.retrieve_txs(mask2, 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()); + } // Estimate fee and locked amount for a transaction - 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: true, + estimate_only: Some(true), + ..Default::default() + }; + let est = api1.init_send_tx(mask1, 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); - - Ok(()) - }, - )?; + 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 = api1.init_send_tx(mask1, 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); + } // Send another transaction, but don't post to chain immediately and use // the stored transaction instead - 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(()) - }, - )?; + { + // 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 = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; - 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(()) - }, - )?; + let (refreshed, _wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(refreshed); + let (_, txs) = api1.retrieve_txs(mask1, 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 = api1 + .get_stored_tx(mask1, None, Some(&tx.tx_slate_id.unwrap()))? + .unwrap(); + api1.post_tx(mask1, &stored_tx_slate, false)?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + // should be mined now + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount * 3 + ); + } // 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( - 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); + { + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, 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) = api2.retrieve_txs(mask2, 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()); + } // try to send a transaction with amount inclusive of fees, but amount too // small to cover fees. Should fail. - 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(()) - }, - )?; + { + 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 = api1.init_send_tx(mask1, args); + assert!(res.is_err()); + } + + // Multiple send attempts, make sure same outputs not locked. + // Fail sending without starting Tor + api2.set_tor_config(Some(grin_wallet_config::TorConfig { + use_integrated: Some(false), + socks_proxy_addr: "invalid".into(), + ..Default::default() + }))?; + let mut handles = vec![]; + + let api2_1 = Owner::new(api2.wallet_inst.clone(), None, api2.config_path()); + handles.push(thread::spawn(move || { + let args = InitTxArgs { + src_acct_name: None, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + amount: 1, + send_args: Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".into(), + post_tx: false, + fluff: false, + skip_tor: Some(false), + }), + ..Default::default() + }; + api2_1.init_send_tx(None, args) + })); + let api2_2 = Owner::new(api2.wallet_inst.clone(), None, api2.config_path()); + handles.push(thread::spawn(move || { + let args = InitTxArgs { + src_acct_name: None, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + amount: 1, + send_args: Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".into(), + post_tx: false, + fluff: false, + skip_tor: Some(false), + }), + ..Default::default() + }; + api2_2.init_send_tx(None, args) + })); + let results: Vec<_> = handles + .into_iter() + .map(|handle| handle.join().unwrap()) + .collect(); + assert_eq!(results.iter().filter(|r| { r.is_ok() }).count(), 1); + let err_res = results.iter().find(|r| r.is_err()).unwrap(); + assert!(matches!( + err_res.as_ref().err().unwrap(), + libwallet::Error::NotEnoughFunds { .. } + )); // 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( - 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(()) - }, - )?; + { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + 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 = api1.init_send_tx(mask1, 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); + } // let logging finish stopper.store(false, Ordering::Relaxed); @@ -511,9 +527,10 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -522,9 +539,10 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -540,159 +558,121 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); let amount = 30_000_000_000; - let mut slate = Slate::blank(1, false); - 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 args = InitTxArgs { + src_acct_name: None, + 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 = api1.init_send_tx(mask1, args)?; + let mut slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; // Check transaction log for wallet 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; - } + { + let (refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + println!( + "last confirmed height: {}", + wallet1_info.last_confirmed_height + ); + assert!(refreshed); + let (_, txs) = api1.retrieve_txs(mask1, 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) = + api1.retrieve_outputs(mask1, true, false, Some(tx.unwrap().id))?; + for m in output_mappings.clone() { + if m.output.status == OutputStatus::Locked { + locked_count += 1; } - assert_eq!(output_mappings.len(), 3); - assert_eq!(locked_count, 2); - assert_eq!(unconfirmed_count, 1); - - Ok(()) - }, - )?; + if m.output.status == OutputStatus::Unconfirmed { + unconfirmed_count += 1; + } + } + assert_eq!(output_mappings.len(), 3); + assert_eq!(locked_count, 2); + assert_eq!(unconfirmed_count, 1); + } // Check transaction log for wallet 2 - 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; - } + { + let (refreshed, txs) = api2.retrieve_txs(mask2, 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) = api2.retrieve_outputs(mask2, true, false, Some(tx.unwrap().id))?; + for m in outputs.clone() { + if m.output.status == OutputStatus::Unconfirmed { + 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) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + assert_eq!(wallet2_info.amount_awaiting_finalization, amount); + } // 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( - 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(()) - }, - )?; - + { + // can't roll back coinbase + let res = api1.cancel_tx(mask1, Some(1), None); + assert!(res.is_err()); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + api1.cancel_tx(mask1, Some(tx.id), None)?; + let (refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, 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 = api1.cancel_tx(mask1, Some(tx.id), None); + assert!(res.is_err()); + } // Wallet 2 rolls back - 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(()) - }, - )?; + { + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + api2.cancel_tx(mask2, Some(tx.id), None)?; + let (refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, 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 = api2.cancel_tx(mask2, Some(tx.id), None); + assert!(res.is_err()); + } // let logging finish stopper.store(false, Ordering::Relaxed); @@ -714,9 +694,10 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); println!("Mask1: {:?}", mask1); // Set the wallet proxy listener running @@ -737,50 +718,35 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { let min_confirmations = 1; // Check wallet 1 content are as expected - 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, min_confirmations)?; - println!( - "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(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = + api1.retrieve_summary_info(mask1, true, min_confirmations)?; + println!( + "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); + } // test selecting max amount - let result = wallet::controller::owner_single_use( - wallet1.clone(), + let result = api1.init_send_tx( mask1, - PathBuf::from(test_dir), - |api, m| { - api.init_send_tx( - m, - InitTxArgs { - amount: (reward * outputs_num as u64) - (cm * reward), - amount_includes_fee: Some(true), - minimum_confirmations: 0, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - refresh_outputs_from_node: true, - ..InitTxArgs::default() - }, - )?; - Ok(()) + InitTxArgs { + amount: (reward * outputs_num as u64) - (cm * reward), + amount_includes_fee: Some(true), + minimum_confirmations: 0, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + refresh_outputs_from_node: true, + ..InitTxArgs::default() }, ); - println!("{:?}", result); let max_tx_weight = global::max_tx_weight(); @@ -796,24 +762,15 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { match result { Ok(_) => {} - Err(e) => match e { - libwallet::Error::BigAmountError(a, fee, num_inputs) => { - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, e_a, e_fee, e_num_inputs) = - api.estimate_max_sendable(m, true, min_confirmations)?; - assert_eq!(e_a, a - fee); - assert_eq!(e_fee, fee); - assert_eq!(e_num_inputs, num_inputs); - Ok(()) - }, - )?; + Err(e) => { + if let libwallet::Error::BigAmountError(a, fee, num_inputs) = e { + let (_, e_a, e_fee, e_num_inputs) = + api1.estimate_max_sendable(mask1, true, min_confirmations)?; + assert_eq!(e_a, a - fee); + assert_eq!(e_fee, fee); + assert_eq!(e_num_inputs, num_inputs); } - _ => {} - }, + } } // let logging finish diff --git a/controller/tests/ttl_cutoff.rs b/controller/tests/ttl_cutoff.rs index faa3990..d8e70d7 100644 --- a/controller/tests/ttl_cutoff.rs +++ b/controller/tests/ttl_cutoff.rs @@ -20,8 +20,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 libwallet::{InitTxArgs, TxLogEntryType}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -45,10 +44,11 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -58,10 +58,11 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -78,126 +79,76 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); let amount = 60_000_000_000; - let mut slate = Slate::blank(1, false); - 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)?; + // 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 = api1.init_send_tx(mask1, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; + let mut slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + let (_, txs) = api1.retrieve_txs(mask1, 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)); // 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( - 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(); + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - assert_eq!(tx.tx_type, TxLogEntryType::TxSentCancelled); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); + assert_eq!(tx.tx_type, TxLogEntryType::TxSentCancelled); // Should also be gone in wallet 2, and output gone - 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); + let (_, txs) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); + let outputs = api2.retrieve_outputs(mask2, false, true, None)?.1; + assert_eq!(outputs.len(), 0); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - assert_eq!(tx.tx_type, TxLogEntryType::TxReceivedCancelled); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); + assert_eq!(tx.tx_type, TxLogEntryType::TxReceivedCancelled); // 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( - 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; + // 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 = api1.init_send_tx(mask1, args)?; + api1.tx_lock_outputs(mask1, &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) = api1.retrieve_txs(mask1, 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)); // 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( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |sender_api, m| { - let (_, _) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - Ok(()) - }, - )?; + let (_, _) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; // And when wallet 1 sends, should be rejected - 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 res = client1.send_tx_slate_direct("wallet2", &slate); + println!("Send after TTL result is: {:?}", res); + assert!(res.is_err()); // 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 424db24..1536bcc 100644 --- a/controller/tests/tx_list_filter.rs +++ b/controller/tests/tx_list_filter.rs @@ -23,191 +23,214 @@ 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 self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; -use std::sync::{atomic::Ordering, Arc}; +use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; use util::secp::key::SecretKey; -use util::Mutex; use self::keychain::ExtKeychain; -use self::libwallet::WalletInst; use impls::DefaultLCProvider; mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_api::Owner; fn test_wallet_tx_filtering( - wallet: Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, - >, mask: Option<&SecretKey>, - test_dir: &'static str, + api: Owner, LocalWalletClient, ExtKeychain>, ) -> Result<(), libwallet::Error> { - 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); + let query = |args| { + api.retrieve_txs(mask, true, None, None, Some(args)) + .map(|(_, txs)| txs) + }; + let txs = query(RetrieveTxQueryArgs::default())?; + assert!(!txs.is_empty()); + let before_first_tx = + txs.iter().map(|tx| tx.creation_ts).min().unwrap() - Duration::from_secs(1); + // Max creation time before all test transactions + let mut tx_query_args = RetrieveTxQueryArgs { + max_creation_timestamp: Some(before_first_tx), + ..Default::default() + }; + assert!(query(tx_query_args.clone())?.is_empty()); - // 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 confirmation time should not affect creation time + tx_query_args.max_creation_timestamp = None; + tx_query_args.min_confirmed_timestamp = Some(before_first_tx); + assert_eq!(query(tx_query_args)?.len(), txs.len()); - // 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); + let tx_query_args = RetrieveTxQueryArgs { + min_id: Some(5), + ..Default::default() + }; - // 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); + // 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); - // 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); + // Max ID + let tx_query_args = RetrieveTxQueryArgs { + min_id: Some(5), + max_id: Some(20), + ..Default::default() + }; + 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); - // 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); + // Exclude 1 canceled + let tx_query_args = RetrieveTxQueryArgs { + exclude_cancelled: Some(true), + min_id: Some(5), + max_id: Some(50), + ..Default::default() + }; + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 28); - // 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); + // Exclude 1 canceled, show confirmed only + let tx_query_args = RetrieveTxQueryArgs { + exclude_cancelled: Some(true), + include_confirmed_only: Some(true), + min_id: Some(5), + max_id: Some(50), + ..Default::default() + }; + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 14); - // 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); + // show outstanding only (including canceled) + let tx_query_args = RetrieveTxQueryArgs { + exclude_cancelled: Some(false), + include_outstanding_only: Some(true), + min_id: Some(5), + max_id: Some(50), + ..Default::default() + }; + 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); + // outstanding only and confirmed only should give empty set + let tx_query_args = RetrieveTxQueryArgs { + exclude_cancelled: Some(false), + include_outstanding_only: Some(true), + include_confirmed_only: Some(true), + min_id: Some(5), + max_id: Some(50), + ..Default::default() + }; + 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 sent only + let tx_query_args = RetrieveTxQueryArgs { + include_sent_only: Some(true), + ..Default::default() + }; + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 15); - // 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 received only (none in this set) + let tx_query_args = RetrieveTxQueryArgs { + include_received_only: Some(true), + ..Default::default() + }; + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // 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); + // include reverted only (none in this set) + let tx_query_args = RetrieveTxQueryArgs { + include_reverted_only: Some(true), + ..Default::default() + }; + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // 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); + // include coinbase only + let tx_query_args = RetrieveTxQueryArgs { + include_coinbase_only: Some(true), + ..Default::default() + }; + 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); + // Amounts + let tx_query_args = RetrieveTxQueryArgs { + min_amount: Some(60_000_000_000 - 59_963_300_000), + ..Default::default() + }; + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 27); - // 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; + // amount, should see as above with coinbases excluded + let tx_query_args = RetrieveTxQueryArgs { + min_amount: Some(60_000_000_000 - 59_963_300_000), + max_amount: Some(60_000_000_000 - 1), + ..Default::default() + }; + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 8); - assert_eq!(tx_results[0].id, 33); - assert_eq!(tx_results[tx_results.len() - 1].id, 0); + // Amount - should only see coinbase (incoming) + let tx_query_args = RetrieveTxQueryArgs { + min_amount: Some(60_000_000_000), + ..Default::default() + }; + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 19); - // 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); + // sort order + let tx_query_args = RetrieveTxQueryArgs { + sort_order: Some(libwallet::RetrieveTxQuerySortOrder::Desc), + ..Default::default() + }; + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; - /*for entry in tx_results.iter() { - println!("{:?}", entry); - }*/ + assert_eq!(tx_results[0].id, 33); + assert_eq!(tx_results[tx_results.len() - 1].id, 0); - Ok(()) - }, - )?; + // change sort field to amount desc, should have coinbases first + let tx_query_args = RetrieveTxQueryArgs { + sort_order: Some(libwallet::RetrieveTxQuerySortOrder::Desc), + sort_field: Some(RetrieveTxQuerySortField::TotalAmount), + ..Default::default() + }; + 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); Ok(()) } @@ -229,9 +252,10 @@ fn build_chain_for_tx_filtering( "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); debug!("Mask1: {:?}", mask1); create_wallet_and_add!( client2, @@ -241,9 +265,10 @@ fn build_chain_for_tx_filtering( "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); debug!("Mask2: {:?}", mask2); // Set the wallet proxy listener running @@ -255,25 +280,8 @@ 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; + api1.stop_updater()?; + api2.stop_updater()?; // few values to keep things shorter let reward = core::consensus::REWARD; @@ -285,22 +293,14 @@ fn build_chain_for_tx_filtering( let mut wallet_1_has_funds = false; // Check wallet 1 contents - 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 (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 spendable - {}", + wallet1_info.amount_currently_spendable + ); + if wallet1_info.amount_currently_spendable > reward { + wallet_1_has_funds = true; + } if !wallet_1_has_funds { let _ = @@ -312,62 +312,44 @@ fn build_chain_for_tx_filtering( let num_txs = 1; for _ in 0..num_txs { let amount: u64 = i as u64 * 1_000_000; - let mut slate = Slate::blank(1, false); debug!("Creating TX for {}", amount); - 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)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; - } - } - - // Cancel a tx for filtering testing - let amount: u64 = 1_000_000; - let mut slate = Slate::blank(1, false); - debug!("Creating TX for {}", amount); - 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, 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(()) - }, - )?; + let slate_i = api1.init_send_tx(mask1, args)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + api1.finalize_tx(mask1, &slate)?; + } + } + + // Cancel a tx for filtering testing + let amount: u64 = 1_000_000; + debug!("Creating TX for {}", amount); + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + api1.cancel_tx(mask1, Some(33), None)?; // Perform actual testing - test_wallet_tx_filtering(wallet1, mask1, test_dir)?; + test_wallet_tx_filtering(mask1, api1)?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/updater_thread.rs b/controller/tests/updater_thread.rs index 2beebab..52c94db 100644 --- a/controller/tests/updater_thread.rs +++ b/controller/tests/updater_thread.rs @@ -46,9 +46,10 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -57,9 +58,10 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -69,33 +71,16 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err }); // add some accounts - 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(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; - // add some accounts - 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(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let bh = 10u64; let _ = diff --git a/doc/samples/v3_api_node/package-lock.json b/doc/samples/v3_api_node/package-lock.json index 0649ef6..6cc6f67 100644 --- a/doc/samples/v3_api_node/package-lock.json +++ b/doc/samples/v3_api_node/package-lock.json @@ -9,7 +9,7 @@ "version": "0.0.1", "license": "ISC", "dependencies": { - "jayson": "^4.3.0" + "jayson": "^5.0.0" } }, "node_modules/@types/connect": { @@ -65,14 +65,6 @@ "es6-promise": "^4.0.3" } }, - "node_modules/eyes": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", - "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", - "engines": { - "node": "> 0.1.90" - } - }, "node_modules/isomorphic-ws": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/isomorphic-ws/-/isomorphic-ws-4.0.1.tgz", @@ -83,9 +75,9 @@ } }, "node_modules/jayson": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/jayson/-/jayson-4.3.0.tgz", - "integrity": "sha512-AauzHcUcqs8OBnCHOkJY280VaTiCm57AbuO7lqzcw7JapGj50BisE3xhksye4zlTSR1+1tAz67wLTl8tEH1obQ==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/jayson/-/jayson-5.0.0.tgz", + "integrity": "sha512-FghxOWlJB5ZPsRsuMF1U4GFHjkJfOEYSlIHpI6Wt6MXIzvqWVo0Kpl7/SMfY36vWggA+b+L09zRGP6m4ROVnKg==", "license": "MIT", "dependencies": { "@types/connect": "^3.4.33", @@ -94,18 +86,15 @@ "commander": "^2.20.3", "delay": "^5.0.0", "es6-promisify": "^5.0.0", - "eyes": "^0.1.8", "isomorphic-ws": "^4.0.1", "json-stringify-safe": "^5.0.1", - "stream-json": "^1.9.1", - "uuid": "^8.3.2", "ws": "^7.5.10" }, "bin": { "jayson": "bin/jayson.js" }, "engines": { - "node": ">=8" + "node": ">=20" } }, "node_modules/json-stringify-safe": { @@ -113,34 +102,6 @@ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" }, - "node_modules/stream-chain": { - "version": "2.2.5", - "resolved": "https://registry.npmjs.org/stream-chain/-/stream-chain-2.2.5.tgz", - "integrity": "sha512-1TJmBx6aSWqZ4tx7aTpBDXK0/e2hhcNSTV8+CbFJtDjbb+I1mZ8lHit0Grw9GRT+6JbIrrDd8esncgBi8aBXGA==", - "license": "BSD-3-Clause" - }, - "node_modules/stream-json": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/stream-json/-/stream-json-1.9.1.tgz", - "integrity": "sha512-uWkjJ+2Nt/LO9Z/JyKZbMusL8Dkh97uUBTv3AJQ74y07lVahLY4eEFsPsE97pxYBwr8nnjMAIch5eqI0gPShyw==", - "license": "BSD-3-Clause", - "dependencies": { - "stream-chain": "^2.2.5" - } - }, - "node_modules/uuid": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", - "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "license": "MIT", - "bin": { - "uuid": "dist/esm/bin/uuid" - } - }, "node_modules/ws": { "version": "7.5.13", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", diff --git a/doc/samples/v3_api_node/package.json b/doc/samples/v3_api_node/package.json index fb89fc9..71bdfff 100644 --- a/doc/samples/v3_api_node/package.json +++ b/doc/samples/v3_api_node/package.json @@ -9,9 +9,6 @@ "author": "", "license": "ISC", "dependencies": { - "jayson": "^4.3.0" - }, - "overrides": { - "uuid": "^11.1.1" + "jayson": "^5.0.0" } } diff --git a/doc/samples/v3_api_node/readme.md b/doc/samples/v3_api_node/readme.md index ed8e907..1a490ca 100644 --- a/doc/samples/v3_api_node/readme.md +++ b/doc/samples/v3_api_node/readme.md @@ -20,7 +20,7 @@ The sample sends it as the password for the `grin` user. If `api_secret_path` is 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): +Then (assuming Node.js >=20 and npm are installed on the system): ```.sh npm install diff --git a/grin b/grin index e42e0c4..da95576 160000 --- a/grin +++ b/grin @@ -1 +1 @@ -Subproject commit e42e0c4a9ead332545fc91fca21df2c99ada4e9e +Subproject commit da955767a35a59cf1d8790a4a4dd70a49372710b diff --git a/impls/Cargo.toml b/impls/Cargo.toml index bb4add2..745b1a0 100644 --- a/impls/Cargo.toml +++ b/impls/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_impls" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Concrete types derived from libwallet traits" license = "Apache-2.0" @@ -32,31 +32,31 @@ sysinfo = "0.29" base64 = "0.12.0" url = "2.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" +arti-client = { version = "0.43.0", features = ["static", "pt-client", "onion-service-service", "onion-service-client"] } +tor-rtcompat = { version = "0.43.0", features = ["static"] } +fs-mistrust = "0.14.2" 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" +tor-hsservice = "0.43.0" +tor-hsrproxy = "0.43.0" +tor-keymgr = "0.43.0" +tor-llcrypto = "0.43.0" +tor-hscrypto = "0.43.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.5.0" } -grin_wallet_config = { path = "../config", version = "5.5.0" } -grin_wallet_libwallet = { path = "../libwallet", version = "5.5.0" } +grin_wallet_util = { path = "../util", version = "5.5.1" } +grin_wallet_config = { path = "../config", version = "5.5.1" } +grin_wallet_libwallet = { path = "../libwallet", version = "5.5.1" } ##### Grin Imports -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_core = { workspace = true } +grin_keychain = { workspace = true } +grin_chain = { workspace = true } +grin_util = { workspace = true } +grin_api = { workspace = true } -##### \ No newline at end of file +##### diff --git a/impls/src/adapters/mod.rs b/impls/src/adapters/mod.rs index 361009e..c59e122 100644 --- a/impls/src/adapters/mod.rs +++ b/impls/src/adapters/mod.rs @@ -13,11 +13,9 @@ // limitations under the License. mod file; -mod slatepack; pub mod tor; pub use self::file::PathToSlate; -pub use self::slatepack::PathToSlatepack; pub use self::tor::TorSlateSender; use crate::config::WalletConfig; diff --git a/impls/src/adapters/slatepack.rs b/impls/src/adapters/slatepack.rs deleted file mode 100644 index 2b04c23..0000000 --- a/impls/src/adapters/slatepack.rs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2021 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. - -/// Slatepack Output 'plugin' implementation -use std::fs::{metadata, File}; -use std::io::{Read, Write}; -use std::path::PathBuf; - -use crate::libwallet::{slatepack, Error, Slate, Slatepack, SlatepackBin, Slatepacker}; -use crate::{SlateGetter, SlatePutter}; -use grin_wallet_util::byte_ser; - -// And Slate putter impls to output to files -pub struct PathToSlatepack<'a> { - pub pathbuf: PathBuf, - pub packer: &'a Slatepacker<'a>, - pub armor_output: bool, -} - -impl<'a> PathToSlatepack<'a> { - /// Create with pathbuf and recipients - pub fn new(pathbuf: PathBuf, packer: &'a Slatepacker<'a>, armor_output: bool) -> Self { - Self { - pathbuf, - packer, - armor_output, - } - } - - pub fn get_slatepack_file_contents(&self) -> Result, Error> { - let metadata = metadata(&self.pathbuf)?; - let len = metadata.len(); - let min_len = slatepack::min_size(); - let max_len = slatepack::max_size(); - if len < min_len || len > max_len { - let msg = format!( - "Data is invalid length: {} | min: {}, max: {} |", - len, min_len, max_len - ); - return Err(Error::SlatepackDeser(msg)); - } - let mut pub_tx_f = File::open(&self.pathbuf)?; - let mut data = Vec::new(); - pub_tx_f.read_to_end(&mut data)?; - Ok(data) - } - - pub fn get_slatepack(&self, decrypt: bool) -> Result { - let data = self.get_slatepack_file_contents()?; - self.packer.deser_slatepack(&data, decrypt) - } -} - -impl<'a> SlatePutter for PathToSlatepack<'a> { - fn put_tx(&self, slate: &Slate, as_bin: bool) -> Result<(), Error> { - let slatepack = self.packer.create_slatepack(slate)?; - let mut pub_tx = File::create(&self.pathbuf)?; - if as_bin { - if self.armor_output { - let armored = self.packer.armor_slatepack(&slatepack)?; - pub_tx.write_all(armored.as_bytes())?; - } else { - pub_tx.write_all( - &byte_ser::to_bytes(&SlatepackBin(slatepack)) - .map_err(|_| Error::SlatepackSer)?, - )?; - } - } else { - pub_tx.write_all( - serde_json::to_string_pretty(&slatepack) - .map_err(|_| Error::SlateSer)? - .as_bytes(), - )?; - } - pub_tx.sync_all()?; - Ok(()) - } -} - -impl<'a> SlateGetter for PathToSlatepack<'a> { - fn get_tx(&self) -> Result<(Slate, bool), Error> { - let data = self.get_slatepack_file_contents()?; - let slatepack = self.packer.deser_slatepack(&data, true)?; - Ok((self.packer.get_slate(&slatepack)?, true)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::fs; - - use grin_core::global; - - fn clean_output_dir(test_dir: &str) { - let _ = fs::remove_dir_all(test_dir); - } - - fn setup(test_dir: &str) { - clean_output_dir(test_dir); - } - - const SLATEPACK_DIR: &'static str = "target/test_output/slatepack"; - - #[test] - fn pathbuf_get_file_contents() { - global::set_local_chain_type(global::ChainTypes::AutomatedTesting); - setup(SLATEPACK_DIR); - - fs::create_dir_all(SLATEPACK_DIR).unwrap(); - let sp_path = PathBuf::from(SLATEPACK_DIR).join("pack_file"); - - // set Slatepack file to minimum allowable size - { - let f = File::create(sp_path.clone()).unwrap(); - f.set_len(slatepack::min_size()).unwrap(); - } - - let args = slatepack::SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }; - let packer = Slatepacker::new(args); - - let mut pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true); - assert!(pack_path.get_slatepack_file_contents().is_ok()); - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false); - assert!(pack_path.get_slatepack_file_contents().is_ok()); - - // set Slatepack file to maximum allowable size - { - let f = File::create(sp_path.clone()).unwrap(); - f.set_len(slatepack::max_size()).unwrap(); - } - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true); - assert!(pack_path.get_slatepack_file_contents().is_ok()); - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false); - assert!(pack_path.get_slatepack_file_contents().is_ok()); - - // set Slatepack file below minimum allowable size - { - let f = File::create(sp_path.clone()).unwrap(); - f.set_len(slatepack::min_size() - 1).unwrap(); - } - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true); - assert!(pack_path.get_slatepack_file_contents().is_err()); - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false); - assert!(pack_path.get_slatepack_file_contents().is_err()); - - // set Slatepack file above maximum allowable size - { - let f = File::create(sp_path.clone()).unwrap(); - f.set_len(slatepack::max_size() + 1).unwrap(); - } - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true); - assert!(pack_path.get_slatepack_file_contents().is_err()); - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false); - assert!(pack_path.get_slatepack_file_contents().is_err()); - } -} diff --git a/impls/src/adapters/tor.rs b/impls/src/adapters/tor.rs index 50e21b8..35320c3 100644 --- a/impls/src/adapters/tor.rs +++ b/impls/src/adapters/tor.rs @@ -27,7 +27,7 @@ use serde_json::{json, Value}; use std::collections::HashMap; use std::convert::TryFrom; use std::net::SocketAddr; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; #[derive(Clone)] @@ -65,7 +65,7 @@ impl TorSlateSender { } /// Launch external Tor process. - fn launch_tor_process(config: &TorConfig, tor_dir: &PathBuf) -> Result { + fn launch_tor_process(config: &TorConfig, tor_dir: &Path) -> Result { let mut tor = TorProcess::new(); let socks_proxy_addr = SocketAddr::V4( config @@ -101,7 +101,7 @@ impl TorSlateSender { ) .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; // Start TOR process - let mut path = tor_dir.clone(); + let mut path = tor_dir.to_path_buf(); path.push("torrc"); tor.torrc_path(path.to_str().unwrap()) .working_dir(tor_dir.to_str().unwrap()) @@ -124,7 +124,7 @@ impl TorSlateSender { 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") { + if !self.config.use_integrated.unwrap_or(false) && err_string.contains("404") { // Report that the other version of the wallet is out of date report = "Other wallet is incompatible and requires an upgrade. \ Please urge the other wallet owner to upgrade and try the transaction again." @@ -178,11 +178,10 @@ impl TorSlateSender { 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 + client.send_request(req)? } else { tor_post(&self.config, &input, url) - .map_err(|e| ClientError::RequestError(format!("{:?}", e)))? + .map_err(|e| ClientError::RequestError(e.to_string()))? }; Ok(res) } diff --git a/impls/src/client_utils/client.rs b/impls/src/client_utils/client.rs index 94b7b37..728c3ba 100644 --- a/impls/src/client_utils/client.rs +++ b/impls/src/client_utils/client.rs @@ -19,7 +19,6 @@ use lazy_static::lazy_static; use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE, USER_AGENT}; use reqwest::{ClientBuilder, Method, Proxy, RequestBuilder}; use serde::{Deserialize, Serialize}; -use serde_json; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; @@ -32,6 +31,7 @@ lazy_static! { } #[derive(Clone, Eq, thiserror::Error, PartialEq, Debug)] +#[allow(clippy::enum_variant_names)] pub enum Error { #[error("Internal error: {0}")] Internal(String), @@ -76,7 +76,7 @@ impl Client { if let Some(p) = proxy { let (addr, scheme) = p; - let proxy = Proxy::all(&format!("{}{}:{}", scheme, addr.ip(), addr.port())) + let proxy = Proxy::all(format!("{}{}:{}", scheme, addr.ip(), addr.port())) .map_err(|e| Error::Internal(format!("Unable to create proxy: {}", e)))?; builder = builder.proxy(proxy); } @@ -91,7 +91,7 @@ impl Client { /// Helper function to easily issue a HTTP GET request against a given URL that /// returns a JSON object. Handles request building, JSON deserialization and /// response code checking. - pub fn _get<'a, T>(&self, url: &'a str, api_secret: Option) -> Result + pub fn _get(&self, url: &str, api_secret: Option) -> Result where for<'de> T: Deserialize<'de>, { @@ -101,11 +101,7 @@ impl Client { /// Helper function to easily issue an async HTTP GET request against a given /// URL that returns a future. Handles request building, JSON deserialization /// and response code checking. - pub async fn _get_async<'a, T>( - &self, - url: &'a str, - api_secret: Option, - ) -> Result + pub async fn _get_async(&self, url: &str, api_secret: Option) -> Result where for<'de> T: Deserialize<'de> + Send + 'static, { @@ -225,7 +221,7 @@ impl Client { IN: Serialize, { let json = serde_json::to_string(input) - .map_err(|_| Error::Internal("Could not serialize data to JSON".to_owned()))?; + .map_err(|e| Error::Internal(format!("Could not serialize data to JSON: {}", e)))?; self.build_request(url, Method::POST, api_secret, Some(json)) } @@ -235,7 +231,7 @@ impl Client { { let data = self.send_request(req)?; serde_json::from_str(&data) - .map_err(|_| Error::ResponseError("Cannot parse response".to_owned())) + .map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e))) } async fn handle_request_async(&self, req: RequestBuilder) -> Result @@ -244,7 +240,7 @@ impl Client { { let data = self.send_request_async(req).await?; let ser = serde_json::from_str(&data) - .map_err(|_| Error::ResponseError("Cannot parse response".to_owned()))?; + .map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e)))?; Ok(ser) } @@ -253,6 +249,10 @@ impl Client { .send() .await .map_err(|e| Error::RequestError(format!("Cannot make request: {}", e)))?; + let status = resp.status(); + if status.is_client_error() || status.is_server_error() { + return Err(Error::ResponseError(format!("HTTP {}", status))); + } let text = resp .text() .await @@ -261,7 +261,7 @@ impl Client { } pub fn send_request(&self, req: RequestBuilder) -> Result { - // This client is currently used both outside and inside of a tokio runtime + // This client is currently used both outside and inside the tokio runtime // context. In the latter case we are not allowed to do a blocking call to // our global runtime, which unfortunately means we have to spawn a new thread if Handle::try_current().is_ok() { @@ -275,3 +275,53 @@ impl Client { } } } + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + use tokio::net::TcpListener; + + #[tokio::test] + async fn http_status() { + let client = Client { + client: ClientBuilder::new() + .no_proxy() + .timeout(Duration::from_secs(5)) + .build() + .unwrap(), + }; + for (status, body, expected) in [ + ("200 OK", "{}", Ok(serde_json::json!({}))), + ( + "401 Unauthorized", + "Unauthorized", + Err(Error::ResponseError("HTTP 401 Unauthorized".into())), + ), + ] { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut headers = BufReader::new(&mut stream).lines(); + while let Some(line) = headers.next_line().await.unwrap() { + if line.is_empty() { + break; + } + } + let response = format!( + "HTTP/1.1 {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + status, + body.len(), + body + ); + stream.write_all(response.as_bytes()).await.unwrap(); + }); + assert_eq!( + client._get_async::(&url, None).await, + expected + ); + server.await.unwrap(); + } + } +} diff --git a/impls/src/client_utils/json_rpc.rs b/impls/src/client_utils/json_rpc.rs index 06e4465..a125336 100644 --- a/impls/src/client_utils/json_rpc.rs +++ b/impls/src/client_utils/json_rpc.rs @@ -22,7 +22,7 @@ use serde_json; pub fn build_request<'a, 'b>(name: &'a str, params: &'b serde_json::Value) -> Request<'a, 'b> { Request { method: name, - params: params, + params, id: From::from(1), jsonrpc: Some("2.0"), } @@ -133,7 +133,7 @@ impl fmt::Display for Error { write!(f, "duplicate RPC batch response ID: {}", v) } Error::_WrongBatchResponseId(ref v) => write!(f, "wrong RPC batch response ID: {}", v), - ref e => f.write_str(&format!("{}", e)), + ref e => write!(f, "{:?}", e), } } } @@ -217,27 +217,27 @@ pub fn _standard_error(code: StandardError, data: Option) -> StandardError::ParseError => RpcError { code: -32700, message: "Parse error".to_string(), - data: data, + data, }, StandardError::InvalidRequest => RpcError { code: -32600, message: "Invalid Request".to_string(), - data: data, + data, }, StandardError::MethodNotFound => RpcError { code: -32601, message: "Method not found".to_string(), - data: data, + data, }, StandardError::InvalidParams => RpcError { code: -32602, message: "Invalid params".to_string(), - data: data, + data, }, StandardError::InternalError => RpcError { code: -32603, message: "Internal error".to_string(), - data: data, + data, }, } } @@ -251,13 +251,13 @@ pub fn _result_to_response( Ok(data) => Response { result: Some(data), error: None, - id: id, + id, jsonrpc: Some(String::from("2.0")), }, Err(err) => Response { result: None, error: Some(err), - id: id, + id, jsonrpc: Some(String::from("2.0")), }, } diff --git a/impls/src/error.rs b/impls/src/error.rs index 4169e68..a22cb2a 100644 --- a/impls/src/error.rs +++ b/impls/src/error.rs @@ -75,8 +75,8 @@ pub enum Error { Encryption, /// BIP 39 word list - #[error("BIP39 Mnemonic (word list) Error")] - Mnemonic, + #[error("BIP39 Mnemonic (word list) Error: {}", _0)] + Mnemonic(String), /// Command line argument error #[error("{}", _0)] diff --git a/impls/src/lib.rs b/impls/src/lib.rs index 9bbedfa..f5c9b5b 100644 --- a/impls/src/lib.rs +++ b/impls/src/lib.rs @@ -42,9 +42,9 @@ pub mod test_framework; pub mod tor; pub use crate::adapters::{ - PathToSlate, PathToSlatepack, SlateGetter, SlatePutter, SlateReceiver, SlateSender, - TorSlateSender, + PathToSlate, SlateGetter, SlatePutter, SlateReceiver, SlateSender, TorSlateSender, }; +pub use crate::client_utils::json_rpc; pub use crate::error::Error; pub use crate::lifecycle::DefaultLCProvider; pub use crate::node_clients::HTTPNodeClient; diff --git a/impls/src/lifecycle/default.rs b/impls/src/lifecycle/default.rs index 7514a30..594f462 100644 --- a/impls/src/lifecycle/default.rs +++ b/impls/src/lifecycle/default.rs @@ -32,9 +32,7 @@ use std::path::MAIN_SEPARATOR; /// 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); - let path = path.replace("\\", &sep); - path + path.replace("/", sep).replace("\\", sep) } pub struct DefaultLCProvider @@ -77,8 +75,8 @@ where let data_dir = self .data_dir .to_owned() - .replace("/", &sep) - .replace("\\", &sep); + .replace("/", sep) + .replace("\\", sep); Ok(data_dir) } @@ -108,7 +106,7 @@ where return Ok(()); } - let mut default_config = GlobalWalletConfig::for_chain(&chain_type, &config_file_name); + 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), @@ -140,7 +138,7 @@ where absolute_path_wallet.push(self.data_dir.clone()); // if no config provided, update defaults - if update == true { + if update { // create top level dir if it doesn't exist let dd = PathBuf::from(self.data_dir.clone()); if !dd.exists() { @@ -182,7 +180,7 @@ where &mut self, _name: Option<&str>, mnemonic: Option, - mnemonic_length: usize, + entropy_size: usize, password: ZeroingString, test_mode: bool, ) -> Result<(), Error> { @@ -196,23 +194,22 @@ where return Err(Error::WalletSeedExists(msg)); } } + let entropy_size = if entropy_size == 0 { 32 } else { entropy_size }; WalletSeed::init_file( &data_dir_name, - mnemonic_length, + entropy_size, mnemonic.clone(), password, test_mode, ) - .map_err(|_| { - Error::Lifecycle("Error creating wallet seed (is mnemonic valid?)".to_owned()) - })?; + .map_err(|e| Error::Lifecycle(format!("Error creating wallet seed: {}", e)))?; info!("Wallet seed file created"); let mut wallet: WalletBackend = match WalletBackend::new(&data_dir_name, self.node_client.clone()) { Err(e) => { - let msg = format!("Error creating wallet: {}, Data Dir: {}", e, &data_dir_name); + let msg = format!("Error creating wallet: {}, Data Dir: {}", e, data_dir_name); error!("{}", msg); - return Err(Error::Lifecycle(msg).into()); + return Err(Error::Lifecycle(msg)); } Ok(d) => d, }; @@ -240,7 +237,7 @@ where let mut wallet: WalletBackend = match WalletBackend::new(&data_dir_name, self.node_client.clone()) { Err(e) => { - let msg = format!("Error opening wallet: {}, Data Dir: {}", e, &data_dir_name); + let msg = format!("Error opening wallet: {}, Data Dir: {}", e, data_dir_name); return Err(Error::Lifecycle(msg)); } Ok(d) => d, @@ -248,6 +245,9 @@ where let wallet_seed = WalletSeed::from_file(&data_dir_name, password).map_err(|_| { Error::Lifecycle("Error opening wallet (is password correct?)".to_owned()) })?; + if wallet_seed.is_empty() { + warn!("This wallet has an empty seed and its funds are unsafe. Move them to a new wallet."); + } let keychain = wallet_seed .derive_keychain(global::is_testnet()) .map_err(|_| Error::Lifecycle("Error deriving keychain".to_owned()))?; @@ -269,7 +269,7 @@ where let mut data_dir_name = PathBuf::from(self.data_dir.clone()); data_dir_name.push(GRIN_WALLET_DIR); let data_dir_name = data_dir_name.to_str().unwrap(); - let res = WalletSeed::seed_file_exists(&data_dir_name) + let res = WalletSeed::seed_file_exists(data_dir_name) .map_err(|_| Error::CallbackImpl("Error checking for wallet existence"))?; Ok(res) } @@ -286,7 +286,7 @@ where .map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?; let res = wallet_seed .to_mnemonic() - .map_err(|_| Error::Lifecycle("Error recovering wallet seed".into()))?; + .map_err(|e| Error::Lifecycle(format!("Error recovering wallet seed: {}. This wallet has no valid recovery phrase and its funds may be unsafe. Move them to a new wallet.", e)))?; Ok(ZeroingString::from(res)) } @@ -320,7 +320,7 @@ where data_dir_name.push(GRIN_WALLET_DIR); let data_dir_name = data_dir_name.to_str().unwrap(); // Get seed for later check - let orig_wallet_seed = WalletSeed::from_file(&data_dir_name, old) + let orig_wallet_seed = WalletSeed::from_file(data_dir_name, old) .map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?; let orig_mnemonic = orig_wallet_seed .to_mnemonic() @@ -346,7 +346,7 @@ where ); info!("Wallet seed file created"); - let new_wallet_seed = WalletSeed::from_file(&data_dir_name, new) + let new_wallet_seed = WalletSeed::from_file(data_dir_name, new) .map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?; if orig_wallet_seed != new_wallet_seed { @@ -382,3 +382,97 @@ where } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::keychain::ExtKeychain; + use crate::lifecycle::seed::{EncryptedWalletSeed, SEED_FILE}; + use crate::node_clients::HTTPNodeClient; + use std::fs::File; + use std::io::Write; + use std::time::Duration; + + fn provider(test_dir: &str) -> DefaultLCProvider { + let client = + HTTPNodeClient::new("http://127.0.0.1:1", None, Duration::from_secs(1)).unwrap(); + let mut provider = DefaultLCProvider::new(client); + provider.set_top_level_directory(test_dir).unwrap(); + provider + } + + #[test] + fn default_recovery_phrase() { + let test_dir = "test_output/default_recovery_phrase"; + let _ = fs::remove_dir_all(test_dir); + global::set_local_chain_type(global::ChainTypes::AutomatedTesting); + let mut provider = provider(test_dir); + let password = ZeroingString::from("test"); + + provider + .create_wallet(None, None, 0, password.clone(), false) + .unwrap(); + let mnemonic = provider.get_mnemonic(None, password).unwrap(); + + assert_eq!(mnemonic.split_whitespace().count(), 24); + fs::remove_dir_all(test_dir).unwrap(); + } + + #[test] + fn mnemonic_error_redacted() { + let test_dir = "test_output/mnemonic_error_redacted"; + let _ = fs::remove_dir_all(test_dir); + let mut provider = provider(test_dir); + let input = ZeroingString::from("INVALID_INPUT_MARKER ".repeat(12)); + let error = provider + .create_wallet(None, Some(input), 32, ZeroingString::from("test"), false) + .unwrap_err() + .to_string(); + + assert!(error.contains("invalid bip39 word")); + assert!(!error.contains("INVALID_INPUT_MARKER")); + assert!(!provider.wallet_exists(None).unwrap()); + fs::remove_dir_all(test_dir).unwrap(); + } + + #[test] + fn missing_recovery_phrase() { + let test_dir = "test_output/missing_recovery_phrase"; + let _ = fs::remove_dir_all(test_dir); + global::set_local_chain_type(global::ChainTypes::AutomatedTesting); + let mut provider = provider(test_dir); + let password = ZeroingString::from("test"); + let data_dir = PathBuf::from(test_dir).join(GRIN_WALLET_DIR); + fs::create_dir_all(data_dir.clone()).unwrap(); + + let seed_file_path = &format!( + "{}{}{}", + fmt_path(data_dir.to_str().unwrap().to_string()), + MAIN_SEPARATOR, + SEED_FILE, + ); + + let enc_seed = EncryptedWalletSeed::from_seed( + &WalletSeed::from_bytes(vec![].as_slice()), + password.clone(), + ) + .unwrap(); + let enc_seed_json = serde_json::to_string_pretty(&enc_seed).unwrap(); + let mut file = File::create(seed_file_path).unwrap(); + file.write_all(enc_seed_json.as_bytes()).unwrap(); + + let error = match provider.get_mnemonic(None, password.clone()) { + Ok(_) => panic!("expected missing recovery phrase error"), + Err(error) => error, + }; + + assert_eq!( + error, + Error::Lifecycle("Error recovering wallet seed: BIP39 Mnemonic (word list) Error: invalid mnemonic/entropy length 0. This wallet has no valid recovery phrase and its funds may be unsafe. Move them to a new wallet.".into()) + ); + provider.open_wallet(None, password, false, false).unwrap(); + provider.close_wallet(None).unwrap(); + assert_eq!(fs::read_to_string(seed_file_path).unwrap(), enc_seed_json); + fs::remove_dir_all(test_dir).unwrap(); + } +} diff --git a/impls/src/lifecycle/seed.rs b/impls/src/lifecycle/seed.rs index 5dbbd6c..09969b3 100644 --- a/impls/src/lifecycle/seed.rs +++ b/impls/src/lifecycle/seed.rs @@ -15,7 +15,6 @@ use crate::blake2; use core::num::NonZeroU32; use rand::{thread_rng, Rng}; -use serde_json; use std::fs::{self, File}; use std::io::{Read, Write}; use std::path::Path; @@ -39,17 +38,24 @@ impl WalletSeed { WalletSeed(bytes.to_vec()) } + pub(super) fn is_empty(&self) -> bool { + self.0.is_empty() + } + pub fn from_mnemonic(word_list: util::ZeroingString) -> Result { let res = mnemonic::to_entropy(&word_list); match res { Ok(s) => Ok(WalletSeed::from_bytes(&s)), - Err(_) => Err(Error::Mnemonic.into()), + Err(mnemonic::Error::BadWord(_)) => { + Err(Error::Mnemonic("invalid bip39 word".to_owned())) + } + Err(e) => Err(Error::Mnemonic(format!("{}", e))), } } pub fn _from_hex(hex: &str) -> Result { - let bytes = util::from_hex(&hex.to_string()) - .map_err(|_| Error::GenericError("Invalid hex".to_owned()))?; + let bytes = + util::from_hex(hex).map_err(|_| Error::GenericError("Invalid hex".to_owned()))?; Ok(WalletSeed::from_bytes(&bytes)) } @@ -61,7 +67,7 @@ impl WalletSeed { let result = mnemonic::from_entropy(&self.0); match result { Ok(r) => Ok(r), - Err(_) => Err(Error::Mnemonic.into()), + Err(e) => Err(Error::Mnemonic(format!("{}", e))), } } @@ -76,14 +82,14 @@ impl WalletSeed { } pub fn init_new( - seed_length: usize, + entropy_size: usize, test_mode: bool, password: Option, - ) -> WalletSeed { + ) -> Result { let mut seed: Vec = vec![]; let mut rng = thread_rng(); if !test_mode { - for _ in 0..seed_length { + for _ in 0..entropy_size { seed.push(rng.gen()); } } else { @@ -93,7 +99,10 @@ impl WalletSeed { .as_bytes() .to_vec(); } - WalletSeed(seed) + let _ = mnemonic::from_entropy(seed.as_slice()) + .map(util::ZeroingString::from) + .map_err(|e| Error::Mnemonic(format!("{}", e)))?; + Ok(WalletSeed(seed)) } pub fn seed_file_exists(data_file_dir: &str) -> Result { @@ -126,7 +135,9 @@ impl WalletSeed { } path.push(backup_seed_file_name.clone()); if fs::rename(seed_file_name, backup_seed_file_name.as_str()).is_err() { - return Err(Error::GenericError("Can't rename wallet seed file".to_owned()).into()); + return Err(Error::GenericError( + "Can't rename wallet seed file".to_owned(), + )); } warn!("{} backed up as {}", seed_file_name, backup_seed_file_name); Ok(backup_seed_file_name) @@ -153,14 +164,13 @@ impl WalletSeed { data_file_dir.to_owned(), "To create a new wallet from a recovery phrase, use 'grin-wallet init -r'" .to_owned(), - ) - .into()); + )); } let seed = WalletSeed::from_mnemonic(word_list)?; let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?; let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?; let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?; - file.write_all(&enc_seed_json.as_bytes()) + file.write_all(enc_seed_json.as_bytes()) .map_err(|_| Error::IO)?; warn!("Seed created from word list"); Ok(()) @@ -168,7 +178,7 @@ impl WalletSeed { pub fn init_file( data_file_dir: &str, - seed_length: usize, + entropy_size: usize, recovery_phrase: Option, password: util::ZeroingString, test_mode: bool, @@ -193,13 +203,13 @@ impl WalletSeed { let seed = match recovery_phrase { Some(p) => WalletSeed::from_mnemonic(p)?, - None => WalletSeed::init_new(seed_length, test_mode, Some(password.clone())), + None => WalletSeed::init_new(entropy_size, test_mode, Some(password.clone()))?, }; let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?; let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?; let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?; - file.write_all(&enc_seed_json.as_bytes()) + file.write_all(enc_seed_json.as_bytes()) .map_err(|_| Error::IO)?; Ok(seed) } @@ -277,7 +287,7 @@ impl EncryptedWalletSeed { let password = password.as_bytes(); let mut key = [0; 32]; pbkdf2::derive( - ring::pbkdf2::PBKDF2_HMAC_SHA512, + pbkdf2::PBKDF2_HMAC_SHA512, NonZeroU32::new(100).unwrap(), &salt, password, @@ -297,7 +307,7 @@ impl EncryptedWalletSeed { aad, &mut enc_bytes, ); - if let Err(_) = res { + if res.is_err() { return Err(Error::Encryption); } @@ -325,7 +335,7 @@ impl EncryptedWalletSeed { let password = password.as_bytes(); let mut key = [0; 32]; pbkdf2::derive( - ring::pbkdf2::PBKDF2_HMAC_SHA512, + pbkdf2::PBKDF2_HMAC_SHA512, NonZeroU32::new(100).unwrap(), &salt, password, @@ -342,7 +352,7 @@ impl EncryptedWalletSeed { aad, &mut encrypted_seed, ); - if let Err(_) = res { + if res.is_err() { return Err(Error::Encryption); } for _ in 0..aead::AES_256_GCM.tag_len() { @@ -359,8 +369,12 @@ mod tests { use crate::util::ZeroingString; #[test] fn wallet_seed_encrypt() { + // Wrong entropy size. + let wrong_entropy_size = WalletSeed::init_new(31, false, None).err(); + assert!(wrong_entropy_size.is_some()); + let password = ZeroingString::from("passwoid"); - let wallet_seed = WalletSeed::init_new(32, false, None); + let wallet_seed = WalletSeed::init_new(32, false, None).unwrap(); let mut enc_wallet_seed = EncryptedWalletSeed::from_seed(&wallet_seed, password.clone()).unwrap(); println!("EWS: {:?}", enc_wallet_seed); diff --git a/impls/src/node_clients/http.rs b/impls/src/node_clients/http.rs index 8b7ed0e..4feba20 100644 --- a/impls/src/node_clients/http.rs +++ b/impls/src/node_clients/http.rs @@ -142,19 +142,12 @@ impl NodeClient for HTTPNodeClient { }, Err(e) => { // If node isn't available, allow offline functions - // unfortunately have to parse string due to error structure - let err_string = format!("{}", e); - 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"); - None - }; + 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; } }; self.node_version_info = Some(retval.clone()); @@ -220,7 +213,7 @@ impl NodeClient for HTTPNodeClient { // build vec of commits for inclusion in query let query_params: Vec = wallet_outputs .iter() - .map(|commit| format!("{}", commit.as_ref().to_hex())) + .map(|commit| commit.as_ref().to_hex()) .collect(); // going to leave this here even though we're moving @@ -283,10 +276,9 @@ impl NodeClient for HTTPNodeClient { }; let rt = RUNTIME.clone(); - let res: Result, _> = - std::thread::spawn(move || rt.block_on(async move { task.await })) - .join() - .unwrap(); + let res: Result, _> = std::thread::spawn(move || rt.block_on(task)) + .join() + .unwrap(); let results: Vec = match res { Ok(resps) => { @@ -345,7 +337,7 @@ impl NodeClient for HTTPNodeClient { let params = json!([start_index, end_index, max_outputs, Some(true)]); let res = self.send_json_request::("get_unspent_outputs", ¶ms)?; // We asked for unspent outputs via the api but defensively filter out spent outputs just in case. - for out in res.outputs.into_iter().filter(|out| out.spent == false) { + for out in res.outputs.into_iter().filter(|out| !out.spent) { let is_coinbase = match out.output_type { api::OutputType::Coinbase => true, api::OutputType::Transaction => false, diff --git a/impls/src/test_framework/mod.rs b/impls/src/test_framework/mod.rs index c90eac5..1191229 100644 --- a/impls/src/test_framework/mod.rs +++ b/impls/src/test_framework/mod.rs @@ -20,12 +20,9 @@ use crate::core::core::{Output, Transaction, TxKernel}; use crate::core::{consensus, global, pow}; use crate::libwallet; use crate::libwallet::api_impl::{foreign, owner}; -use crate::libwallet::{ - BlockFees, InitTxArgs, NodeClient, WalletInfo, WalletInst, WalletLCProvider, -}; +use crate::libwallet::{BlockFees, InitTxArgs, NodeClient, WalletInfo, WalletLCProvider}; use crate::util::secp::key::SecretKey; use crate::util::secp::pedersen; -use crate::util::Mutex; use chrono::Duration; use grin_keychain::Keychain; use std::sync::Arc; @@ -54,7 +51,7 @@ fn get_kernel_local( max_height: Option, ) -> Option { chain - .get_kernel_height(&excess, min_height, max_height) + .get_kernel_height(excess, min_height, max_height) .unwrap() .map(|(tx_kernel, height, mmr_index)| api::LocatedTxKernel { tx_kernel, @@ -147,7 +144,7 @@ pub fn create_block_for_wallet<'a, L, C, K>( chain: &Chain, prev: core::core::BlockHeader, txs: &[Transaction], - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result where @@ -178,7 +175,7 @@ where pub fn award_block_to_wallet<'a, L, C, K>( chain: &Chain, txs: &[Transaction], - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result<(), libwallet::Error> where @@ -200,7 +197,7 @@ pub fn process_block(chain: &Chain, block: core::core::Block) { /// Award a blocks to a wallet directly pub fn award_blocks_to_wallet<'a, L, C, K>( chain: &Chain, - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, number: usize, pause_between: bool, @@ -221,7 +218,7 @@ where /// send an amount to a destination pub fn send_to_dest<'a, L, C, K>( - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, client: LocalWalletClient, dest: &str, @@ -261,7 +258,7 @@ where /// get wallet info totals pub fn wallet_info<'a, L, C, K>( - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result where diff --git a/impls/src/test_framework/testclient.rs b/impls/src/test_framework/testclient.rs index f25e913..a639a03 100644 --- a/impls/src/test_framework/testclient.rs +++ b/impls/src/test_framework/testclient.rs @@ -26,7 +26,7 @@ use crate::keychain::Keychain; use crate::libwallet; use crate::libwallet::api_impl::foreign; use crate::libwallet::slate_versions::v4::SlateV4; -use crate::libwallet::{NodeClient, NodeVersionInfo, Slate, WalletInst, WalletLCProvider}; +use crate::libwallet::{NodeClient, NodeVersionInfo, Slate, WalletLCProvider}; use crate::util; use crate::util::secp::key::SecretKey; use crate::util::secp::pedersen; @@ -66,11 +66,12 @@ where /// handle to chain itself pub chain: Arc, /// list of interested wallets + #[allow(clippy::type_complexity)] pub wallets: HashMap< String, ( Sender, - Arc>>>, + grin_wallet_libwallet::WalletHandle<'a, L, C, K>, Option, ), >, @@ -119,7 +120,7 @@ where &mut self, addr: &str, tx: Sender, - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option, ) { self.wallets @@ -185,12 +186,7 @@ where libwallet::Error::ClientCallback("Error parsing Transaction".to_owned()) })?; - super::award_block_to_wallet( - &self.chain, - &[tx], - dest_wallet, - (&dest_wallet_mask).as_ref(), - )?; + super::award_block_to_wallet(&self.chain, &[tx], dest_wallet, dest_wallet_mask.as_ref())?; Ok(WalletProxyMessage { sender_id: "node".to_owned(), @@ -219,7 +215,7 @@ where let w = w_lock.lc_provider()?.wallet_inst()?; let mask = wallet.2.clone(); // receive tx - match foreign::receive_tx(w, (&mask).as_ref(), &Slate::from(slate), None, false) { + match foreign::receive_tx(w, mask.as_ref(), &Slate::from(slate), None, false) { Err(e) => { return Ok(WalletProxyMessage { sender_id: m.dest, diff --git a/impls/src/tor/arti.rs b/impls/src/tor/arti.rs index 769e2bc..d0a0c89 100644 --- a/impls/src/tor/arti.rs +++ b/impls/src/tor/arti.rs @@ -34,6 +34,7 @@ use sha2::Sha512; use std::collections::HashMap; use std::net::SocketAddr; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, LazyLock, Mutex}; use std::thread::{self, JoinHandle}; use std::time::Duration; @@ -59,12 +60,26 @@ struct TorService { state_lock: PathBuf, } +/// Failure from an HTTP request over Tor, classified by whether delivery may +/// have started. +#[derive(Debug, thiserror::Error)] +pub enum TorPostError { + /// The failure happened before handing the request to Hyper. + #[error("{0}")] + NotSent(Error), + /// Hyper started sending the request, so delivery cannot be ruled out. + #[error("{0}")] + PossiblySent(Error), +} + +type ArtiClientConfig = (Arc>, TorClientConfig); + 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)>>> = + static ref ARTI_CLIENT_CONFIG: LazyLock>> = LazyLock::new(|| Mutex::new(None)); /// Running services, where key is onion address. static ref ARTI_PROXY_SERVICES: LazyLock>> = @@ -138,7 +153,7 @@ pub fn start_tor_service(key: SecretKey, addr: &str, config: &TorConfig) -> Resu info!("Proxy configuration will be ignored."); } - let (state_path, cache_path) = state_cache_paths(&config); + let (state_path, cache_path) = state_cache_paths(config); let (client, config) = init_client(&state_path, &cache_path, config)?; // Add service key to keystore. @@ -151,7 +166,7 @@ pub fn start_tor_service(key: SecretKey, addr: &str, config: &TorConfig) -> Resu let state_lock = state_path .join("hss") .join(format!("{}.lock", onion_address)); - let _ = add_service_key(config.fs_mistrust(), &key, &hs, keystore_path)?; + add_service_key(config.fs_mistrust(), &key, &hs, keystore_path)?; // Launch Onion service. let service_config = OnionServiceConfigBuilder::default() @@ -216,39 +231,73 @@ pub fn start_tor_client(config: TorConfig) -> Result<(), Error> { Ok(()) } +/// Build an origin-form JSON POST request +fn build_post_request(json: String, url: &Uri) -> Result>, Error> { + let authority = url + .authority() + .ok_or_else(|| Error::GenericError(format!("URL {} has bad authority", url)))?; + let request_target = url + .path_and_query() + .map(|path| path.as_str()) + .unwrap_or("/"); + + Request::builder() + .uri(request_target) + .method("POST") + .header("host", authority.as_str()) + .header("accept", "application/json") + .header("content-type", "application/json") + .body(Full::from(json)) + .map_err(|e| Error::TorProcess(format!("{:?}", e))) +} + /// Make POST request. -pub fn tor_post(tor_config: &TorConfig, input: &IN, url: &str) -> Result +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 json = serde_json::to_string(input).map_err(|_| { + TorPostError::NotSent(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)))?; + .map_err(|_| TorPostError::NotSent(Error::GenericError(format!("Bad URL: {}", url))))?; let host = match url.host() { - None => return Err(Error::GenericError(format!("URL {} has bad host", url))), + None => { + return Err(TorPostError::NotSent(Error::GenericError(format!( + "URL {} has bad host", + url + )))) + } Some(h) => h, } .to_string(); + let port = url.port_u16().unwrap_or(80); + let request = build_post_request(json, &url).map_err(TorPostError::NotSent)?; 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 (state_path, cache_path) = state_cache_paths(tor_config); + let (client, _) = + init_client(&state_path, &cache_path, tor_config).map_err(TorPostError::NotSent)?; + 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 send_started = Arc::new(AtomicBool::new(false)); + let send_started_in_request = send_started.clone(); + let runtime = c.runtime().clone(); + let res = runtime + .timeout(timeout, async move { + let stream = c.connect((host, port)).await.map_err(|e| { + TorPostError::NotSent(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)))?; + .map_err(|e| { + TorPostError::NotSent(Error::TorProcess(format!("{:?}", e))) + })?; // Spawn a task to poll the connection and drive the HTTP state. tokio::spawn(async move { @@ -257,36 +306,44 @@ where } }); - 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)))?; + send_started_in_request.store(true, Ordering::Release); + let resp = request_sender.send_request(request).await.map_err(|e| { + TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e))) + })?; - let body_resp = resp - .into_body() - .collect() - .await - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let status = resp.status(); + let body_resp = resp.into_body().collect().await.map_err(|e| { + TorPostError::PossiblySent(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)))?; + let body_text = String::from_utf8(body).map_err(|e| { + TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e))) + })?; + if !status.is_success() { + return Err(TorPostError::PossiblySent(Error::TorProcess(format!( + "HTTP request failed with status {}: {}", + status, body_text + )))); + } Ok(body_text) }) .await; match res { - Err(e) => Err(Error::TorProcess(format!("{:?}", e))), + Err(e) if send_started.load(Ordering::Acquire) => Err(TorPostError::PossiblySent( + Error::TorProcess(format!("{:?}", e)), + )), + Err(e) => Err(TorPostError::NotSent(Error::TorProcess(format!("{:?}", e)))), Ok(body) => Ok(body), } }) }) .join() - .unwrap_or_else(|e| return Err(Error::TorProcess(format!("{:?}", e))))?; + .unwrap_or_else(|e| { + Err(TorPostError::PossiblySent(Error::TorProcess(format!( + "{:?}", + e + )))) + })?; res } @@ -296,8 +353,12 @@ fn init_client( cache_path: &PathBuf, tor_config: &TorConfig, ) -> Result<(Arc>, TorClientConfig), Error> { - let mut builder = TorClientConfigBuilder::from_directories(&state_path, cache_path); + let mut builder = TorClientConfigBuilder::from_directories(state_path, cache_path); builder.address_filter().allow_onion_addrs(true); + // Circuit timeout minimum applies to listeners and sends too + builder + .override_net_params() + .insert("cbtmintimeout".into(), 60_000); // Configure bridge. if let Some(bridge_line) = tor_config.bridge.bridge_line.as_ref() { @@ -345,7 +406,7 @@ fn init_client( *cached_client_config = None; } } - let res = launch_client(config.clone(), &tor_config); + let res = launch_client(config.clone(), tor_config); match res { Ok(client) => { cached_client_config.replace((client.clone(), config.clone())); @@ -458,7 +519,7 @@ fn add_service_key( Some(expanded_kp) => { key_manager .insert( - HsIdKey::from(expanded_kp.public().clone()), + HsIdKey::from(*expanded_kp.public()), &HsIdPublicKeySpecifier::new(hs_nickname.clone()), KeystoreSelector::Primary, true, @@ -476,3 +537,21 @@ fn add_service_key( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::build_post_request; + use hyper::{Method, Uri}; + + #[test] + fn builds_origin_form_json_request() { + let url: Uri = "http://example.onion:8080/v1?test=1".parse().unwrap(); + let request = build_post_request("{}".to_string(), &url).unwrap(); + + assert_eq!(request.method(), Method::POST); + assert_eq!(request.uri(), "/v1?test=1"); + assert_eq!(request.headers()["host"], "example.onion:8080"); + assert_eq!(request.headers()["accept"], "application/json"); + assert_eq!(request.headers()["content-type"], "application/json"); + } +} diff --git a/impls/src/tor/bridge.rs b/impls/src/tor/bridge.rs index 834e0b9..764658c 100644 --- a/impls/src/tor/bridge.rs +++ b/impls/src/tor/bridge.rs @@ -87,8 +87,8 @@ impl<'a> FlagParser<'a> { fn end(&mut self, is_bool_flag: bool, right: &str) -> usize { if is_bool_flag { 0 - } else if right.starts_with('"') { - right[1..].find('"').unwrap_or(0) + 2 + } else if let Some(stripped) = right.strip_prefix('"') { + stripped.find('"').unwrap_or(0) + 2 } else { right.find(' ').unwrap_or(right.len()) } @@ -113,7 +113,7 @@ impl<'a> Iterator for FlagParser<'a> { let end = self.end(self.is_bool_flag, right); let key = left.split_whitespace().last()?; let val = &right[..end]; - self.line = &right[end..].trim(); + self.line = right[end..].trim(); Some((key, val)) } } @@ -121,7 +121,7 @@ impl<'a> Iterator for FlagParser<'a> { /// Every args field that could be in the bridge line /// obfs4 args : https://github.com/Yawning/obfs4/blob/40245c4a1cf221395c59d1f4bf274127045352f9/transports/obfs4/obfs4.go#L86-L91 /// meek_lite args : https://github.com/Yawning/obfs4/blob/40245c4a1cf221395c59d1f4bf274127045352f9/transports/meeklite/meek.go#L93-L127 -#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default)] pub struct Transport { /// transport type: obfs4, meek_lite, meek, snowflake pub transport: Option, @@ -143,22 +143,6 @@ pub struct Transport { pub disablehpkp: Option, } -impl Default for Transport { - fn default() -> Transport { - Transport { - transport: None, - server: None, - fingerprint: None, - cert: None, - iatmode: None, - url: None, - front: None, - utls: None, - disablehpkp: None, - } - } -} - impl Transport { /// Parse the server address of the bridge line fn parse_socketaddr_arg(arg: Option<&&str>) -> Result { @@ -170,7 +154,7 @@ impl Transport { Ok(address.to_string()) } None => { - let msg = format!("Missing bridge server address"); + let msg = "Missing bridge server address".to_string(); Err(Error::TorBridge(msg)) } } @@ -202,7 +186,7 @@ impl Transport { })?; if cert_vec.len() != 52 { let msg = format!("Invalid certificate: {}", arg); - return Err(Error::TorBridge(msg).into()); + return Err(Error::TorBridge(msg)); } Ok(arg.to_string()) } @@ -219,16 +203,17 @@ impl Transport { /// Parse the max value for the arg -max in the client line option (snowflake) fn parse_hpkp_arg(arg: &str) -> Result { let max = arg.parse::().map_err(|_e| { - Error::TorBridge( - format!("Invalid -max value: {}, must be \"true\" or \"false\"", arg).into(), - ) + Error::TorBridge(format!( + "Invalid -max value: {}, must be \"true\" or \"false\"", + arg + )) })?; Ok(max.to_string()) } } // Client Plugin such as snowflake or obfs4proxy -#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default)] pub struct PluginClient { // Path plugin client pub path: Option, @@ -236,15 +221,6 @@ pub struct PluginClient { pub option: Option, } -impl Default for PluginClient { - fn default() -> PluginClient { - PluginClient { - path: None, - option: None, - } - } -} - impl PluginClient { /// Get the hashmap key(argument) and attached value of the client option line. pub fn get_flags(s: &str) -> HashMap<&str, &str> { @@ -333,7 +309,7 @@ impl PluginClient { "Invalid ICE address: {}. Must be a stun or turn address", addr ); - return Err(Error::TorBridge(msg).into()); + return Err(Error::TorBridge(msg)); } } Ok(ice_addr.to_string()) @@ -372,9 +348,9 @@ impl PluginClient { let (ck_url, ck_ice) = (hm_flags.contains_key("-url"), hm_flags.contains_key("-ice")); if !(ck_url || ck_ice) { let msg = if !ck_url { - format!("Missing URL argurment for snowflake transport, specify \"-url\"") + "Missing URL argurment for snowflake transport, specify \"-url\"".to_string() } else { - format!("Missing ICE argurment for snowflake transport, specify \"-ice\"") + "Missing ICE argurment for snowflake transport, specify \"-ice\"".to_string() }; return Err(Error::TorBridge(msg)); } @@ -410,7 +386,7 @@ impl PluginClient { } /// Tor Bridge Field -#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default)] pub struct TorBridge { /// tor bridge (transport field) pub bridge: Transport, @@ -418,15 +394,6 @@ pub struct TorBridge { pub client: PluginClient, } -impl Default for TorBridge { - fn default() -> TorBridge { - TorBridge { - bridge: Transport::default(), - client: PluginClient::default(), - } - } -} - impl TorBridge { /// Get the hashmap key(argument) and attached value of the bridge line. r pub fn get_flags(s: &str) -> HashMap<&str, &str> { @@ -541,8 +508,8 @@ impl TryFrom for TorBridge { let cert = match flags.get_key_value("cert=") { Some(hm) => Transport::parse_cert_arg(hm.1)?, None => { - let msg = - format!("Missing cert argurment in obfs4 transport, specify \"cert=\""); + let msg = "Missing cert argurment in obfs4 transport, specify \"cert=\"" + .to_string(); return Err(Error::TorBridge(msg)); } }; @@ -559,14 +526,14 @@ impl TryFrom for TorBridge { bridge: Transport { transport: Some("obfs4".into()), server: Some(socketaddr.to_string()), - fingerprint: fingerprint, - cert: Some(cert.into()), + fingerprint, + cert: Some(cert), iatmode: Some(iatmode), ..Transport::default() }, client: PluginClient { path: Some(path), - option: option, + option, }, }; Ok(tbpc) @@ -578,9 +545,8 @@ impl TryFrom for TorBridge { let url = match flags.get_key_value("url=") { Some(hm) => PluginClient::parse_url_arg(hm.1)?, None => { - let msg = format!( - "Missing url argurment in meek_lite transport, specify \"url=\"" - ); + let msg = "Missing url argurment in meek_lite transport, specify \"url=\"" + .to_string(); return Err(Error::TorBridge(msg)); } }; @@ -588,10 +554,7 @@ impl TryFrom for TorBridge { Some(hm) => Some(PluginClient::parse_front_arg(hm.1)?), None => None, }; - let utls = match flags.get_key_value("utls=") { - Some(hm) => Some(hm.1.to_string()), - None => None, - }; + let utls = flags.get_key_value("utls=").map(|hm| hm.1.to_string()); let disablehpkp = match flags.get_key_value("disablehpkp=") { Some(hm) => Some(Transport::parse_hpkp_arg(hm.1)?), None => None, @@ -605,16 +568,16 @@ impl TryFrom for TorBridge { bridge: Transport { transport: Some("meek_lite".into()), server: Some(socketaddr.to_string()), - fingerprint: fingerprint, + fingerprint, url: Some(url), - front: front, - utls: utls, - disablehpkp: disablehpkp, + front, + utls, + disablehpkp, ..Transport::default() }, client: PluginClient { path: Some(path), - option: option, + option, }, }; Ok(tbpc) @@ -638,7 +601,7 @@ impl TryFrom for TorBridge { bridge: Transport { transport: Some("snowflake".into()), server: Some(socketaddr.to_string()), - fingerprint: fingerprint, + fingerprint, ..Transport::default() }, client: PluginClient { diff --git a/impls/src/tor/config.rs b/impls/src/tor/config.rs index 422fae1..3375dd4 100644 --- a/impls/src/tor/config.rs +++ b/impls/src/tor/config.rs @@ -131,7 +131,7 @@ pub fn create_onion_service_pub_key_file( pub fn create_onion_service_hostname_file(os_directory: &str, hostname: &str) -> Result<(), Error> { let file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, HOSTNAME_FILE); let mut file = File::create(file_path).map_err(|_| Error::IO)?; - file.write_all(&format!("{}.onion\n", hostname).as_bytes()) + file.write_all(format!("{}.onion\n", hostname).as_bytes()) .map_err(|_| Error::IO)?; Ok(()) } @@ -228,7 +228,7 @@ pub fn output_tor_listener_config( let mut service_dirs = vec![]; for k in listener_keys { - let service_dir = output_onion_service_config(tor_config_directory, &k)?; + let service_dir = output_onion_service_config(tor_config_directory, k)?; service_dirs.push(service_dir.to_string()); } @@ -253,7 +253,7 @@ pub fn output_tor_sender_config( hm_tor_proxy: HashMap, ) -> Result<(), Error> { // create data directory if it doesn't exist - fs::create_dir_all(&tor_config_dir).map_err(|_| Error::IO)?; + fs::create_dir_all(tor_config_dir).map_err(|_| Error::IO)?; output_torrc( tor_config_dir, @@ -272,7 +272,7 @@ pub fn is_tor_address(input: &str) -> Result<(), Error> { Ok(_) => Ok(()), Err(e) => { let msg = format!("{:?}", e); - Err(Error::NotOnion(msg).into()) + Err(Error::NotOnion(msg)) } } } diff --git a/impls/src/tor/process.rs b/impls/src/tor/process.rs index 4e53f8e..9bf8b7f 100644 --- a/impls/src/tor/process.rs +++ b/impls/src/tor/process.rs @@ -90,6 +90,12 @@ pub struct TorProcess { sys: System, } +impl Default for TorProcess { + fn default() -> Self { + Self::new() + } +} + impl TorProcess { pub fn new() -> Self { TorProcess { @@ -153,7 +159,7 @@ impl TorProcess { let mut tor = Command::new(&self.tor_cmd); if let Some(ref d) = self.working_dir { - tor.current_dir(&d); + tor.current_dir(d); let pid_file_name = format!("{}{}pid", d, MAIN_SEPARATOR); // kill off PID if its already running if Path::new(&pid_file_name).exists() { @@ -167,7 +173,7 @@ impl TorProcess { } } if let Some(ref torrc_path) = self.torrc_path { - tor.args(&vec!["-f", torrc_path]); + tor.args(vec!["-f", torrc_path]); } let mut tor_process = tor .args(&self.args) diff --git a/impls/src/tor/proxy.rs b/impls/src/tor/proxy.rs index 9e0deb2..a54e9ca 100644 --- a/impls/src/tor/proxy.rs +++ b/impls/src/tor/proxy.rs @@ -20,7 +20,7 @@ use std::str; use url::Host; /// Tor Proxy -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct TorProxy { /// proxy type used for the proxy, eg "socks4", "socks5", "http", "https" pub transport: Option, @@ -34,18 +34,6 @@ pub struct TorProxy { pub allowed_port: Option>, } -impl Default for TorProxy { - fn default() -> TorProxy { - TorProxy { - transport: None, - address: None, - username: None, - password: None, - allowed_port: None, - } - } -} - impl TorProxy { fn parse_host_port(addr: &str) -> Result<(String, Option), Error> { let host: String; @@ -70,7 +58,7 @@ impl TorProxy { } pub fn parse_address(addr: &str) -> Result<(String, Option), Error> { - let (host, str_port) = TorProxy::parse_host_port(&addr)?; + let (host, str_port) = TorProxy::parse_host_port(addr)?; let host = Host::parse(&host) .map_err(|_e| Error::TorProxy(format!("Invalid host address: {}", host)))?; let port = if let Some(p) = str_port { @@ -92,13 +80,10 @@ impl TorProxy { for port in ports.clone() { allowed_ports.push_str(format!("*:{}", port).as_str()); if port != last_port { - allowed_ports.push_str(","); + allowed_ports.push(','); } } - hm.insert( - "ReachableAddresses".to_string(), - format!("{}", allowed_ports.clone()), - ); + hm.insert("ReachableAddresses".to_string(), allowed_ports); } let transport = match self.transport { @@ -156,7 +141,7 @@ impl TryFrom for TorProxy { address_addr = host } Ok(TorProxy { - transport: Some(transport.into()), + transport: Some(transport), address: Some(address_addr), username: tb.username, password: tb.password, @@ -167,7 +152,7 @@ impl TryFrom for TorProxy { "Missing proxy address: {} - must be or ", transport ); - return Err(Error::TorProxy(msg).into()); + Err(Error::TorProxy(msg)) } } // Missing transport type @@ -176,7 +161,7 @@ impl TryFrom for TorProxy { "Invalid proxy transport: {} - must be socks4/socks5/http(s)", transport ); - Err(Error::TorProxy(msg).into()) + Err(Error::TorProxy(msg)) } } } else { diff --git a/libwallet/Cargo.toml b/libwallet/Cargo.toml index 09e2b19..397b267 100644 --- a/libwallet/Cargo.toml +++ b/libwallet/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_libwallet" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format." license = "Apache-2.0" @@ -43,14 +43,14 @@ num-bigint = "0.2" chacha20 = "0.8.1" hmac = { version = "0.12.0", features = ["std"]} -grin_wallet_util = { path = "../util", version = "5.5.0" } -grin_wallet_config = { path = "../config", version = "5.5.0" } +grin_wallet_util = { path = "../util", version = "5.5.1" } +grin_wallet_config = { path = "../config", version = "5.5.1" } ##### Grin Imports -grin_core = { path = "../grin/core"} -grin_keychain = { path = "../grin/keychain"} -grin_util = { path = "../grin/util"} -grin_store = { path = "../grin/store"} +grin_core = { workspace = true } +grin_keychain = { workspace = true } +grin_util = { workspace = true } +grin_store = { workspace = true } ##### diff --git a/libwallet/src/address.rs b/libwallet/src/address.rs index 8d55b39..01bed27 100644 --- a/libwallet/src/address.rs +++ b/libwallet/src/address.rs @@ -15,35 +15,60 @@ //! Functions defining wallet 'addresses', i.e. ed2559 keys based on //! a derivation path -use crate::grin_util::secp::key::SecretKey; -use crate::Error; -use grin_keychain::{ChildNumber, Identifier, Keychain, SwitchCommitmentType}; - use crate::blake2::blake2b::blake2b; +use crate::slatepack::SlatepackAddressIndex; +use crate::Error; + +use grin_keychain::{ChildNumber, Identifier, Keychain, SwitchCommitmentType}; +use grin_util::secp::key::SecretKey; + +/// Derive a Slatepack address path from an output parent path and index. +/// +/// Output paths: +/// - account m/0: m/0/0/0, m/0/0/1 +/// - account m/1: m/1/0/0, m/1/0/1 +/// +/// Slatepack address paths: +/// - account m/0: m/0/1/0, m/0/1/1 +/// - account m/1: m/1/1/0, m/1/1/1 +pub fn address_derivation_path( + parent_key_id: &Identifier, + index: SlatepackAddressIndex, +) -> Identifier { + let mut key_path = parent_key_id.to_path(); + key_path.path[1] = ChildNumber::from(1); + key_path.depth += 1; + key_path.path[key_path.depth as usize - 1] = ChildNumber::from(index.value()); + Identifier::from_path(&key_path) +} /// Derive a secret key given a derivation path and index pub fn address_from_derivation_path( keychain: &K, parent_key_id: &Identifier, - index: u32, + index: SlatepackAddressIndex, ) -> Result where K: Keychain, { - let mut key_path = parent_key_id.to_path(); - // An output derivation for acct m/0 - // is m/0/0/0, m/0/0/1 (for instance), m/1 is m/1/0/0, m/1/0/1 - // Address generation path should be - // for m/0: m/0/1/0, m/0/1/1 - // for m/1: m/1/1/0, m/1/1/1 - key_path.path[1] = ChildNumber::from(1); - key_path.depth += 1; - key_path.path[key_path.depth as usize - 1] = ChildNumber::from(index); - let key_id = Identifier::from_path(&key_path); + let key_id = address_derivation_path(parent_key_id, index); let sec_key = keychain.derive_key(0, &key_id, SwitchCommitmentType::None)?; let hashed = blake2b(32, &[], &sec_key.0[..]); - Ok(SecretKey::from_slice( - &keychain.secp(), - &hashed.as_bytes()[..], - )?) + Ok(SecretKey::from_slice(keychain.secp(), hashed.as_bytes())?) +} + +#[cfg(test)] +mod tests { + use super::*; + use grin_keychain::ExtKeychain; + + #[test] + fn slatepack_address_path() { + let parent = ExtKeychain::derive_key_id(2, 2, 0, 0, 0); + let expected = ExtKeychain::derive_key_id(3, 2, 1, 3, 0); + assert_eq!( + address_derivation_path(&parent, SlatepackAddressIndex(3)), + expected + ); + } } diff --git a/libwallet/src/api_impl/foreign.rs b/libwallet/src/api_impl/foreign.rs index ca30339..ed63451 100644 --- a/libwallet/src/api_impl/foreign.rs +++ b/libwallet/src/api_impl/foreign.rs @@ -23,17 +23,18 @@ use crate::api_impl::owner::{check_ttl, payment_proof_kernel, post_tx}; use crate::api_impl::types::update_tx_slate_state; use crate::backend::WalletBackend; use crate::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI}; -use crate::grin_core::core::FeeFields; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; use crate::internal::{selection, tx, updater}; use crate::payment_proof::EarlyPaymentProof; use crate::slate::PaymentProofType; use crate::slate_versions::SlateVersion; +use crate::slatepack::SlatepackAddressIndex; use crate::{ address, BlockFees, CbData, Error, NodeClient, Slate, SlateState, TxLogEntryType, VersionInfo, }; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::FeeFields; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; const FOREIGN_API_VERSION: u16 = 2; @@ -71,6 +72,10 @@ where C: NodeClient, K: Keychain, { + if slate.amount == 0 { + return Err(Error::InvalidAmount); + } + let mut ret_slate = slate.clone(); if ret_slate.state != SlateState::Standard1 { return Err(Error::SlateState); @@ -128,7 +133,11 @@ where ret_slate.amount, &excess, saddr, - address::address_from_derivation_path(&keychain, &parent_key_id, 0)?, + address::address_from_derivation_path( + &keychain, + &parent_key_id, + SlatepackAddressIndex(0), + )?, )?; p.promise_signature = Some(sig); @@ -169,7 +178,7 @@ where selection::repopulate_tx(w, keychain_mask, &mut sl, &temp_ctx, false)?; tx::complete_tx(w, keychain_mask, &mut sl, &context)?; - tx::update_stored_tx(w, keychain_mask, &context, &mut sl, true)?; + tx::update_stored_tx(w, keychain_mask, &context, &sl, true)?; { let mut batch = w.batch(keychain_mask)?; batch.delete_private_context(sl.id.as_bytes())?; diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 5d42527..c7a5e69 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -14,57 +14,76 @@ //! Generic implementation of owner API functions -use std::cmp; -use uuid::Uuid; - use crate::api_impl::foreign::finalize_tx as foreign_finalize; -use crate::grin_core::core::amount_to_hr_string; -use crate::grin_core::core::hash::Hashed; -use crate::grin_core::core::{FeeFields, Output, OutputFeatures, Transaction, TxKernel}; -use crate::grin_core::libtx::proof; -use crate::grin_keychain::ViewKey; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::pedersen::Commitment; -use crate::grin_util::{Mutex, ToHex}; -use crate::payment_proof::{EarlyPaymentProof, ProofWitness}; -use crate::util::OnionV3Address; - use crate::api_impl::owner_updater::StatusMessage; +use crate::internal::{keys, scan, selection, tx, updater}; +use crate::slate::{PaymentInfo, Slate, SlateState}; +use crate::slatepack::SlatepackAddressIndex; +use crate::types::{AcctPathMapping, NodeClient, OutputData, OutputStatus, TxLogEntry, WalletInfo}; +use crate::util::OnionV3Address; +use crate::{ + address, + mwixnet::{ + create_onion, ComSignature, Hop, MixnetReqCreationParams, MwixnetReqCreationResult, + SwapReq, MAX_MWIXNET_HOPS, + }, + slatepack, wallet_lock, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult, + OutputCommitMapping, PaymentProof, RetrieveTxQueryArgs, ScannedBlockInfo, Slatepack, + SlatepackAddress, SlatepackArmor, SlatepackBin, TxLogEntryType, ViewWallet, WalletBackend, + WalletInitStatus, WalletLCProvider, +}; +use grin_core::core::amount_to_hr_string; +use grin_core::core::hash::Hashed; +use grin_core::core::{FeeFields, Output, OutputFeatures, Transaction, TransactionBody}; +use grin_core::global::DEFAULT_ACCEPT_FEE_BASE; +use grin_core::libtx::proof; +use grin_keychain::ViewKey; +use grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType}; +use grin_util::secp::{key::SecretKey, pedersen::Commitment}; +use grin_util::ToHex; +use grin_wallet_util::byte_ser; + +use crate::contract; use crate::contract::types::{ ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI, ContractView, }; -use crate::grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType}; - -use crate::internal::{keys, scan, selection, tx, updater}; -use crate::slate::{PaymentInfo, PaymentProofType, Slate, SlateState}; -use crate::types::{AcctPathMapping, NodeClient, TxLogEntry, WalletInfo}; -use crate::{ - address, contract, - mwixnet::{create_onion, ComSignature, Hop, MixnetReqCreationParams, SwapReq}, - wallet_lock, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult, - OutputCommitMapping, PaymentProof, RetrieveTxQueryArgs, ScannedBlockInfo, SlateVersion, - Slatepack, SlatepackAddress, Slatepacker, SlatepackerArgs, TxLogEntryType, ViewWallet, - WalletBackend, WalletInitStatus, WalletInst, WalletLCProvider, -}; +use crate::payment_proof::{EarlyPaymentProof, ProofWitness}; +use crate::slate::PaymentProofType; +use crate::SlateVersion; use ed25519_dalek::SigningKey as DalekSecretKey; use ed25519_dalek::Verifier; use ed25519_dalek::VerifyingKey as DalekPublicKey; -use x25519_dalek::{PublicKey as xPublicKey, StaticSecret}; - +use grin_core::core::TxKernel; +use std::cmp; use std::convert::{TryFrom, TryInto}; use std::sync::mpsc::Sender; -use std::sync::Arc; +use uuid::Uuid; /// List of accounts -pub fn accounts(w: &mut WalletBackend) -> Result, Error> +pub fn accounts( + w: &mut WalletBackend, + minimum_confirmations: Option, +) -> Result, Error> where C: NodeClient, K: Keychain, { - keys::accounts(w) + let mut accounts: Vec = if let Some(mc) = minimum_confirmations { + updater::retrieve_accounts_info(w, mc)? + } else { + keys::accounts(w)? + }; + let active = w.parent_key_id(); + for account in accounts.iter_mut() { + account.current = Some(account.path == active); + } + accounts.sort_by(|a, b| a.path.cmp(&b.path)); + // Put active account on top. + accounts.sort_by_key(|k| k.path != active); + Ok(accounts) } -/// new account path +/// New account path pub fn create_account_path( w: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -77,18 +96,22 @@ where keys::new_acct_path(w, keychain_mask, label) } -/// set active account -pub fn set_active_account(w: &mut WalletBackend, label: &str) -> Result<(), Error> +/// Set active account +pub fn set_active_account( + w: &mut WalletBackend, + keychain_mask: Option<&SecretKey>, + label: &str, +) -> Result<(), Error> where C: NodeClient, K: Keychain, { - w.set_parent_key_id_by_name(label) + w.set_active_account(keychain_mask, label) } /// Hash of the wallet root public key pub fn get_rewind_hash<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result where @@ -106,15 +129,16 @@ where /// Retrieve the slatepack address for the current parent key at /// the given index pub fn get_slatepack_address<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, - index: u32, + index: SlatepackAddressIndex, ) -> Result where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { + index.check()?; wallet_lock!(wallet_inst, w); let parent_key_id = w.parent_key_id(); let k = w.keychain(keychain_mask)?; @@ -125,15 +149,16 @@ where /// Retrieve the decryption key for the current parent key /// the given index pub fn get_slatepack_secret_key<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, - index: u32, + index: SlatepackAddressIndex, ) -> Result where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { + index.check()?; wallet_lock!(wallet_inst, w); let parent_key_id = w.parent_key_id(); let k = w.keychain(keychain_mask)?; @@ -144,7 +169,7 @@ where /// Label of another account that can decrypt the slatepack, if any pub fn slatepack_account<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slatepack: &Slatepack, ) -> Result, Error> @@ -157,7 +182,8 @@ where let active = w.parent_key_id(); let k = w.keychain(keychain_mask)?; for acct in w.acct_path_iter()?.filter(|acct| acct.path != active) { - let sec_addr_key = address::address_from_derivation_path(&k, &acct.path, 0)?; + let sec_addr_key = + address::address_from_derivation_path(&k, &acct.path, SlatepackAddressIndex(0))?; let dec_key = DalekSecretKey::from_bytes(&sec_addr_key.0); let mut candidate = slatepack.clone(); if candidate.try_decrypt_payload(Some(&dec_key)).is_ok() { @@ -169,10 +195,10 @@ where /// Create a slatepack message from the given slate pub fn create_slatepack_message<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slate: &Slate, - sender_index: Option, + sender_index: Option, mut recipients: Vec, ) -> Result where @@ -180,8 +206,12 @@ where C: NodeClient + 'a, K: Keychain + 'a, { - let sender = match sender_index { - Some(i) => Some(get_slatepack_address(wallet_inst, keychain_mask, i)?), + let sender = match sender_index.as_ref() { + Some(i) => Some(get_slatepack_address( + wallet_inst.clone(), + keychain_mask, + *i, + )?), None => None, }; if !recipients.is_empty() { @@ -191,127 +221,246 @@ where } } } - let packer = Slatepacker::new(SlatepackerArgs { - sender, - recipients, - dec_key: None, - }); - let slatepack = packer.create_slatepack(slate)?; - packer.armor_slatepack(&slatepack) + let slatepack = slate.create_slatepack(sender, recipients)?; + slatepack.armor() } /// Unpack a slate from the given slatepack message, /// optionally decrypting pub fn slate_from_slatepack_message<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slatepack: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { - if secret_indices.is_empty() { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - let slatepack = packer.deser_slatepack(slatepack.as_bytes(), true)?; - packer.get_slate(&slatepack) - } else { - for index in secret_indices { - let dec_key = Some(get_slatepack_secret_key( - wallet_inst.clone(), - keychain_mask, - index, - )?); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: (&dec_key).as_ref(), - }); - let res = packer.deser_slatepack(slatepack.as_bytes(), true); - let slatepack = match res { - Ok(sp) => sp, - Err(_) => { - continue; - } - }; - return packer.get_slate(&slatepack); - } - // maybe it's for another account - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - let encrypted = packer.deser_slatepack(slatepack.as_bytes(), false)?; - let msg = match slatepack_account(wallet_inst, keychain_mask, &encrypted)? { - Some(label) => format!( + let sp = decode_slatepack_message( + wallet_inst.clone(), + keychain_mask, + slatepack, + secret_indices, + ) + .map_err(|e| Error::SlatepackDecryption(format!("Could not decrypt slatepack: {}", e)))?; + if sp.is_encrypted() { + if let Some(label) = slatepack_account(wallet_inst, keychain_mask, &sp)? { + return Err(Error::SlatepackDecryption(format!( "it is encrypted for account '{}' of this wallet, make it the active account", label - ), - None => { - "Could not decrypt slatepack with any provided index on the address derivation path" - .to_owned() - } - }; - Err(Error::SlatepackDecryption(msg)) + ))); + } } + sp.get_slate() } /// Decode a slatepack message, to allow viewing /// Will decrypt if possible, otherwise will return /// undecrypted slatepack pub fn decode_slatepack_message<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slatepack: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - if secret_indices.is_empty() { - packer.deser_slatepack(slatepack.as_bytes(), false) - } else { - for index in secret_indices { - let dec_key = Some(get_slatepack_secret_key( - wallet_inst.clone(), - keychain_mask, - index, - )?); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: (&dec_key).as_ref(), - }); - let res = packer.deser_slatepack(slatepack.as_bytes(), true); - let slatepack = match res { - Ok(sp) => sp, - Err(_) => { - continue; - } - }; - return Ok(slatepack); - } - packer.deser_slatepack(slatepack.as_bytes(), false) + for i in &secret_indices { + i.check()?; } + let slatepack = parse_slatepack(slatepack.as_bytes())?; + if slatepack.is_encrypted() && !secret_indices.is_empty() { + let mut decrypted = slatepack.clone(); + if decrypt_slatepack(&mut decrypted, wallet_inst, keychain_mask, secret_indices).is_ok() { + return Ok(decrypted); + } + } + Ok(slatepack) +} + +/// Deserialize provided data to slatepack +pub fn deserialize_slatepack<'a, L, C, K>( + data: &[u8], + wallet_inst: crate::WalletHandle<'a, L, C, K>, + keychain_mask: Option<&SecretKey>, + secret_indices: Vec, +) -> Result +where + L: WalletLCProvider<'a, C, K>, + C: NodeClient + 'a, + K: Keychain + 'a, +{ + let mut slatepack = parse_slatepack(data)?; + decrypt_slatepack(&mut slatepack, wallet_inst, keychain_mask, secret_indices)?; + Ok(slatepack) +} + +/// Parse a slatepack without accessing wallet keys +pub fn parse_slatepack(data: &[u8]) -> Result { + // check if data is armored, if so, remove and continue + let data_len = data.len() as u64; + if data_len < slatepack::min_size() || data_len > slatepack::max_size() { + return Err(Error::SlatepackDeser("Data invalid length".to_string())); + } + + let test_header = &data[..slatepack::HEADER.len()]; + + let data = match str::from_utf8(test_header) { + Ok(s) => { + if s == slatepack::HEADER { + SlatepackArmor::decode(data)? + } else { + data.to_vec() + } + } + Err(_) => data.to_vec(), + }; + + // try as bin first, then as json + let slatepack = match byte_ser::from_bytes::(&data) { + Ok(s) => s.0, + Err(e) => { + debug!("Not a valid binary slatepack: {} - Will try JSON", e); + let content = String::from_utf8(data).map_err(|e| { + let msg = format!("{}", e); + Error::SlatepackDeser(msg) + })?; + serde_json::from_str(&content).map_err(|e| { + let msg = format!("Error reading JSON slatepack: {}", e); + Error::SlatepackDeser(msg) + })? + } + }; + + slatepack.ver_check_warn(); + Ok(slatepack) +} + +/// Decrypt a parsed slatepack using wallet indices +pub fn decrypt_slatepack<'a, L, C, K>( + slatepack: &mut Slatepack, + wallet_inst: crate::WalletHandle<'a, L, C, K>, + keychain_mask: Option<&SecretKey>, + mut secret_indices: Vec, +) -> Result<(), Error> +where + L: WalletLCProvider<'a, C, K>, + C: NodeClient + 'a, + K: Keychain + 'a, +{ + secret_indices.sort_unstable(); + secret_indices.dedup(); + if slatepack.is_encrypted() { + // Try decrypt with selected indices. + let mut try_decrypt_with = |indices: &Vec| -> Result<(), Error> { + for i in indices { + let dec_key = get_slatepack_secret_key(wallet_inst.clone(), keychain_mask, *i)?; + match slatepack.try_decrypt_payload(Some(&dec_key)) { + Ok(_) => return Ok(()), + Err(e) => { + if matches!(e, Error::Age(_)) { + continue; + } else { + return Err(e); + } + } + } + } + Err(Error::SlatepackDecryption( + "Can not decrypt slatepack with provided indexes".to_string(), + )) + }; + + // Try decrypt with initial indices. + return match try_decrypt_with(&secret_indices) { + Ok(_) => Ok(()), + Err(_) => { + // Collect indexes for transactions. + let collect_indexes = |outstanding: bool, + secret_indices: &Vec| + -> Result, Error> { + wallet_lock!(wallet_inst, w); + let mut indices: Vec = w + .tx_log_iter()? + .flatten() + .filter(|tx| { + let tx_type = if outstanding { + !tx.confirmed + && (tx.tx_type == TxLogEntryType::TxReceived + || tx.tx_type == TxLogEntryType::TxSent + || tx.tx_type == TxLogEntryType::TxReverted) + } else { + tx.confirmed + && tx.tx_type != TxLogEntryType::TxReceivedCancelled + && tx.tx_type != TxLogEntryType::TxSentCancelled + }; + tx_type && tx.parent_key_id == w.parent_key_id() + }) + .filter_map(|t| t.address_index) + .filter(|i| !secret_indices.contains(i)) + .collect(); + indices.sort_unstable(); + indices.dedup(); + Ok(indices) + }; + let mut indexes = collect_indexes(true, &secret_indices)?; + match try_decrypt_with(&mut indexes) { + Ok(_) => Ok(()), + Err(_) => { + for i in indexes { + if !secret_indices.contains(&i) { + secret_indices.push(i); + } + } + let indexes = collect_indexes(false, &secret_indices)?; + match try_decrypt_with(&indexes) { + Ok(()) => Ok(()), + Err(_) => { + for i in indexes { + if !secret_indices.contains(&i) { + secret_indices.push(i); + } + } + let mut indexes: Vec = { + wallet_lock!(wallet_inst, w); + w.private_context_iter()? + .flatten() + .filter(|c| { + let index = + if let Some(i) = c.payment_proof_derivation_index { + !secret_indices.contains(&i) + } else { + false + }; + c.parent_key_id == w.parent_key_id() && index + }) + .map(|c| c.payment_proof_derivation_index.unwrap()) + .collect() + }; + indexes.sort_unstable(); + indexes.dedup(); + match try_decrypt_with(&indexes) { + Ok(_) => Ok(()), + Err(e) => Err(e), + } + } + } + } + } + } + }; + } + Ok(()) } /// retrieve outputs pub fn retrieve_outputs<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, include_spent: bool, @@ -345,7 +494,7 @@ where /// Calculate max amount to send. pub fn estimate_max_sendable<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -404,7 +553,7 @@ where /// Retrieve txs pub fn retrieve_txs<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -444,7 +593,7 @@ where /// Retrieve summary info pub fn retrieve_summary_info<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -473,7 +622,7 @@ where } fn retrieve_payment_proof_tx<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -509,7 +658,7 @@ where /// Retrieve payment proof pub fn retrieve_payment_proof<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -569,6 +718,7 @@ where recipient_sig: r_sig, sender_address: SlatepackAddress::new(&proof.sender_address), sender_sig: s_sig, + sender_address_path: Some(proof.sender_address_path), }) } @@ -592,7 +742,7 @@ pub(super) fn payment_proof_kernel( /// Retrieve an early payment proof pub fn retrieve_payment_proof_early<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -686,6 +836,13 @@ where if let Some(v) = args.target_slate_version { SlateVersion::try_from(v)?; } + if let Some(index) = args.address_index { + index.check()?; + } + + if args.amount == 0 { + return Err(Error::InvalidAmount); + } let payment_proof_address = if let Some(a) = &args.payment_proof_recipient_address { if a.valid_network() { @@ -766,15 +923,12 @@ where )? }; - // Payment Proof, add addresses to slate and save address - // TODO: Note we only use single derivation path for now, - // probably want to allow sender to specify which one - let deriv_path = 0u32; - + let address_index = args.address_index.unwrap_or(SlatepackAddressIndex(0)); if let Some(a) = payment_proof_address { let k = w.keychain(keychain_mask)?; - let sec_addr_key = address::address_from_derivation_path(&k, &parent_key_id, deriv_path)?; + let sec_addr_key = + address::address_from_derivation_path(&k, &parent_key_id, address_index)?; let sender_address = OnionV3Address::from_private(&sec_addr_key.0)?; slate.payment_proof = Some(PaymentInfo { @@ -785,14 +939,13 @@ where timestamp: None, memo: None, }); - - context.payment_proof_derivation_index = Some(deriv_path); } // Save the aggsig context in our DB for when we - // recieve the transaction back + // receive the transaction back { let mut batch = w.batch(keychain_mask)?; + context.payment_proof_derivation_index = Some(address_index); batch.save_private_context(slate.id.as_bytes(), &context)?; batch.commit()?; } @@ -806,7 +959,7 @@ where pub fn issue_invoice_tx( w: &mut WalletBackend, keychain_mask: Option<&SecretKey>, - args: IssueInvoiceTxArgs, + mut args: IssueInvoiceTxArgs, use_test_rng: bool, ) -> Result where @@ -816,6 +969,13 @@ where if let Some(v) = args.target_slate_version { SlateVersion::try_from(v)?; } + if let Some(index) = args.address_index { + index.check()?; + } + + if args.amount == 0 { + return Err(Error::InvalidAmount); + } let parent_key_id = match args.dest_acct_name { Some(d) => { @@ -828,9 +988,13 @@ where None => w.parent_key_id(), }; + if args.address_index.is_none() { + args.address_index = Some(w.next_tx_slatepack_address_index(&parent_key_id)?); + } + let mut slate = tx::new_tx_slate(w, args.amount, true, 2, use_test_rng, None)?; let height = w.w2n_client().get_chain_tip()?.0; - let context = tx::add_output_to_slate( + let mut context = tx::add_output_to_slate( w, keychain_mask, &mut slate, @@ -844,10 +1008,20 @@ where slate.version_info.version = v; }; + // Update transaction log address index + let mut tx = w.get_tx_log_entry(&slate.id, &parent_key_id)?; + if let Some(tx) = tx.as_mut() { + tx.address_index = args.address_index; + let mut batch = w.batch(keychain_mask)?; + batch.save_tx_log_entry(tx.clone(), &parent_key_id)?; + batch.commit()?; + } + // Save the aggsig context in our DB for when we - // recieve the transaction back + // receive the transaction back { let mut batch = w.batch(keychain_mask)?; + context.payment_proof_derivation_index = args.address_index; batch.save_private_context(slate.id.as_bytes(), &context)?; batch.commit()?; } @@ -870,6 +1044,10 @@ where C: NodeClient, K: Keychain, { + if slate.amount == 0 { + return Err(Error::InvalidAmount); + } + let mut ret_slate = slate.clone(); check_ttl(w, &ret_slate)?; let parent_key_id = match args.src_acct_name { @@ -949,6 +1127,7 @@ where // if self-sending, merge contexts if let Ok(c) = context_res { + context.payment_proof_derivation_index = c.payment_proof_derivation_index; context.initial_sec_key = c.initial_sec_key; context.initial_sec_nonce = c.initial_sec_nonce; context.fee = c.fee; @@ -964,7 +1143,7 @@ where selection::repopulate_tx(w, keychain_mask, &mut ret_slate, &context, false)?; // Save the aggsig context in our DB for when we - // recieve the transaction back + // receive the transaction back { let mut batch = w.batch(keychain_mask)?; batch.save_private_context(slate.id.as_bytes(), &context)?; @@ -990,11 +1169,14 @@ where K: Keychain, { let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?; + if slate.state == SlateState::Invoice2 && context.input_ids.is_empty() { + return Err(Error::SlateState); + } let mut excess_override = None; let mut sl = slate.clone(); - if sl.tx == None { + if sl.tx.is_none() { sl.tx = Some(Slate::empty_transaction()); selection::repopulate_tx(w, keychain_mask, &mut sl, &context, true)?; } @@ -1023,23 +1205,25 @@ where /// cancel tx pub fn cancel_tx<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, tx_id: Option, tx_slate_id: Option, + refresh_from_node: bool, ) -> Result<(), Error> where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { - if !update_wallet_state( - wallet_inst.clone(), - keychain_mask, - status_send_channel, - false, - )? { + if refresh_from_node + && !update_wallet_state( + wallet_inst.clone(), + keychain_mask, + status_send_channel, + false, + )? { return Err(Error::TransactionCancellationError( "Can't contact running Grin node. Not Cancelling.", )); @@ -1062,11 +1246,7 @@ where { let mut uuid = None; if let Some(i) = tx_id { - let tx = w - .tx_log_iter()? - .filter(|tx| tx.is_ok()) - .map(|tx| tx.unwrap()) - .find(|t| t.id == i); + let tx = w.tx_log_iter()?.flatten().find(|t| t.id == i); if let Some(t) = tx { uuid = t.tx_slate_id; } @@ -1122,7 +1302,7 @@ where /// Scan outputs with the rewind hash of a third-party wallet. /// Help to retrieve outputs information that belongs it pub fn scan_rewind_hash<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, rewind_hash: String, start_height: Option, status_send_channel: &Option>, @@ -1143,7 +1323,7 @@ where w.w2n_client().get_chain_tip()? }; - let start_height = start_height.unwrap_or_else(|| 1); + let start_height = start_height.unwrap_or(1); let info = scan::scan_rewind_hash( wallet_inst, @@ -1159,7 +1339,7 @@ where /// Accepts a wallet inst instead of a raw wallet so it can /// lock as little as possible pub fn scan<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, start_height: Option, delete_unconfirmed: bool, @@ -1176,7 +1356,7 @@ where w.w2n_client().get_chain_tip()? }; - let start_height = start_height.unwrap_or_else(|| 1); + let start_height = start_height.unwrap_or(1); // Scan every 10k heights to save data between batches in case of interruption. let mut total_pmmr_range = None; @@ -1211,7 +1391,7 @@ where /// node height pub fn node_height<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result where @@ -1231,12 +1411,7 @@ where }), Err(_) => { let outputs = retrieve_outputs(wallet_inst, keychain_mask, &None, true, false, None)?; - let height = outputs - .1 - .iter() - .map(|m| m.output.height) - .max() - .unwrap_or_else(|| 0); + let height = outputs.1.iter().map(|m| m.output.height).max().unwrap_or(0); Ok(NodeHeightResult { height, header_hash: "".to_owned(), @@ -1251,7 +1426,7 @@ pub const REORG_RESCAN_WINDOW: u64 = 24 * 60 * 2; /// Experimental, wrap the entire definition of how a wallet's state is updated pub fn update_wallet_state<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, update_all: bool, @@ -1417,7 +1592,7 @@ pub(crate) fn check_ttl_at_height(slate: &Slate, height: u64) -> Result<(), Erro /// Verify/validate arbitrary payment proof /// Returns (whether this wallet is the sender, whether this wallet is the recipient) pub fn verify_payment_proof<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, proof: &PaymentProof, ) -> Result<(bool, bool), Error> @@ -1455,19 +1630,30 @@ 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 sec_key = + address::address_from_derivation_path(&keychain, &parent_key_id, SlatepackAddressIndex(0))?; let d_skey = DalekSecretKey::from_bytes(&sec_key.0); - let my_address_pubkey: DalekPublicKey = (&d_skey).into(); + let possible_receiver_key: DalekPublicKey = (&d_skey).into(); - let sender_mine = my_address_pubkey == sender_pubkey; - let recipient_mine = my_address_pubkey == recipient_pubkey; + let sec_key = address::address_from_derivation_path( + &keychain, + &parent_key_id, + proof + .sender_address_path + .unwrap_or(SlatepackAddressIndex(0)), + )?; + let d_skey = DalekSecretKey::from_bytes(&sec_key.0); + let possible_sender_key: DalekPublicKey = (&d_skey).into(); + + let sender_mine = possible_sender_key == sender_pubkey; + let recipient_mine = possible_receiver_key == recipient_pubkey; Ok((sender_mine, recipient_mine)) } /// Attempt to update outputs in wallet, return whether it was successful fn update_outputs<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, update_all: bool, ) -> Result @@ -1491,9 +1677,9 @@ where /// Update transactions that need to be validated via kernel lookup fn update_txs_via_kernel<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, - txs: &mut Vec, + txs: &mut [TxLogEntry], ) -> Result where L: WalletLCProvider<'a, C, K>, @@ -1651,96 +1837,135 @@ pub fn create_mwixnet_req( commitment: &Commitment, lock_output: bool, use_test_rng: bool, -) -> Result +) -> Result where C: NodeClient, K: Keychain, { - let parent_key_id = w.parent_key_id(); - let keychain = w.keychain(keychain_mask)?; - let outputs = updater::retrieve_outputs(w, keychain_mask, false, None, Some(&parent_key_id))?; - - let mut output = None; - for o in &outputs { - if o.commit == *commitment { - output = Some(o.output.clone()); - break; - } + if params.server_keys.is_empty() { + return Err(Error::GenericError( + "mwixnet requires at least one server key".to_string(), + )); } - - if output.is_none() { - return Err(Error::GenericError(String::from("output not found"))); - } - - let amount = output.clone().unwrap().value; - let input_blind = keychain.derive_key( - amount, - &output.clone().unwrap().key_id, - SwitchCommitmentType::Regular, - )?; - - let mut server_pubkeys = vec![]; - for i in 0..params.server_keys.len() { - server_pubkeys.push(xPublicKey::from(&StaticSecret::from( - params.server_keys[i].0, + if params.server_keys.len() > MAX_MWIXNET_HOPS { + return Err(Error::GenericError(format!( + "mwixnet supports at most {} server keys", + MAX_MWIXNET_HOPS ))); } - let fee = grin_core::libtx::tx_fee(1, 1, 1); - let new_amount = amount - (fee * server_pubkeys.len() as u64); + let parent_key_id = w.parent_key_id(); + let keychain = w.keychain(keychain_mask)?; + let outputs = updater::retrieve_outputs(w, keychain_mask, true, None, Some(&parent_key_id))?; + let output = outputs + .into_iter() + .find(|o| o.commit == *commitment) + .map(|o| o.output) + .ok_or_else(|| Error::GenericError("output not found".to_string()))?; + let current_height = w.w2n_client().get_chain_tip()?.0; + if !output.eligible_to_spend(current_height, 1) { + return Err(Error::GenericError("output is not spendable".to_string())); + } + + let amount = output.value; + let input_blind = keychain.derive_key(amount, &output.key_id, SwitchCommitmentType::Regular)?; + + let server_pubkeys = ¶ms.server_keys; + let minimum_fee = TransactionBody::weight_by_iok(1, 1, 1) * DEFAULT_ACCEPT_FEE_BASE; + let fee_per_hop = params.fee_per_hop.unwrap_or(minimum_fee); + if fee_per_hop < minimum_fee { + return Err(Error::Fee(format!( + "mwixnet fee is below the swap minimum {}", + amount_to_hr_string(minimum_fee, true) + ))); + } + let fee = FeeFields::try_from(fee_per_hop).map_err(|e| Error::Fee(e.to_string()))?; + let total_fee = fee_per_hop + .checked_mul(server_pubkeys.len() as u64) + .ok_or_else(|| Error::Fee("mwixnet fee overflow".to_string()))?; + let total_fee_fields = FeeFields::try_from(total_fee) + .map_err(|_| Error::Fee("mwixnet total fee exceeds FeeFields limit".to_string()))?; + let new_amount = amount + .checked_sub(total_fee) + .ok_or_else(|| Error::Fee("mwixnet fees exceed output value".to_string()))?; let new_output = build_output(w, keychain_mask, OutputFeatures::Plain, new_amount)?; let secp = keychain.secp(); let mut blind_sum = new_output .blind - .split(&BlindingFactor::from_secret_key(input_blind.clone()), &secp)?; + .split(&BlindingFactor::from_secret_key(input_blind.clone()), secp)?; - let hops = server_pubkeys + let hops: Vec = server_pubkeys .iter() .enumerate() - .map(|(i, &p)| { + .map(|(i, &p)| -> Result { if (i + 1) == server_pubkeys.len() { - Hop { - server_pubkey: p.clone(), - excess: blind_sum.secret_key(&secp).unwrap(), - fee: FeeFields::from(fee as u32), - rangeproof: Some(new_output.output.proof.clone()), - } + Ok(Hop { + server_pubkey: p, + excess: blind_sum.secret_key(secp)?, + fee, + rangeproof: Some(new_output.output.proof), + }) } else { - let hop_excess; - if use_test_rng { - hop_excess = BlindingFactor::zero(); + let hop_excess = if use_test_rng { + BlindingFactor::zero() } else { - hop_excess = BlindingFactor::rand(&secp); - } - blind_sum = blind_sum.split(&hop_excess, &secp).unwrap(); - Hop { - server_pubkey: p.clone(), - excess: hop_excess.secret_key(&secp).unwrap(), - fee: FeeFields::from(fee as u32), + BlindingFactor::rand(secp) + }; + blind_sum = blind_sum.split(&hop_excess, secp)?; + Ok(Hop { + server_pubkey: p, + excess: hop_excess.secret_key(secp)?, + fee, rangeproof: None, - } + }) } }) - .collect(); + .collect::, _>>()?; - let onion = create_onion(&commitment, &hops, use_test_rng).unwrap(); - let comsig = ComSignature::sign( - amount, - &input_blind, - &onion.serialize().unwrap(), - use_test_rng, - ) - .unwrap(); + let onion = create_onion(commitment, &hops, use_test_rng) + .map_err(|e| Error::GenericError(e.to_string()))?; + let onion_bytes = onion.serialize().map_err(Error::Deser)?; + let comsig = ComSignature::sign(amount, &input_blind, &onion_bytes, use_test_rng) + .map_err(|e| Error::Signature(e.to_string()))?; // Lock output if requested - if lock_output { + let tx_id = if lock_output { let mut batch = w.batch(keychain_mask)?; - let mut update_output = batch.get(&output.as_ref().unwrap().key_id, &None)?; - update_output.lock(); - batch.lock_output(&mut update_output)?; - batch.commit()?; - } + let log_id = batch.next_tx_log_id(&parent_key_id)?; + let mut tx = TxLogEntry::new(parent_key_id.clone(), TxLogEntryType::TxSent, log_id); + tx.amount_debited = amount; + tx.amount_credited = new_amount; + tx.num_inputs = 1; + tx.num_outputs = 1; + tx.fee = Some(total_fee_fields); + tx.kernel_lookup_min_height = Some(current_height); - Ok(SwapReq { comsig, onion }) + let mut update_output = batch.get(&output.key_id, &output.mmr_index)?; + update_output.tx_log_entry = Some(log_id); + batch.lock_output(&mut update_output)?; + batch.save(OutputData { + root_key_id: parent_key_id.clone(), + key_id: new_output.key_id.clone(), + n_child: new_output.key_id.to_path().last_path_index(), + commit: Some(new_output.output.commitment().to_hex()), + mmr_index: None, + value: new_amount, + status: OutputStatus::Unconfirmed, + height: current_height, + lock_height: 0, + is_coinbase: false, + tx_log_entry: Some(log_id), + })?; + batch.save_tx_log_entry(tx, &parent_key_id)?; + batch.commit()?; + Some(log_id) + } else { + None + }; + + Ok(MwixnetReqCreationResult { + request: SwapReq { comsig, onion }, + tx_id, + }) } diff --git a/libwallet/src/api_impl/owner_updater.rs b/libwallet/src/api_impl/owner_updater.rs index 9201c6e..f513a82 100644 --- a/libwallet/src/api_impl/owner_updater.rs +++ b/libwallet/src/api_impl/owner_updater.rs @@ -19,14 +19,14 @@ use std::sync::Arc; use std::thread; use std::time::Duration; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::Mutex; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; +use grin_util::Mutex; use crate::api_impl::owner; use crate::types::NodeClient; use crate::Error; -use crate::{WalletInst, WalletLCProvider}; +use crate::WalletLCProvider; const MESSAGE_QUEUE_MAX_LEN: usize = 10_000; @@ -101,7 +101,7 @@ where C: NodeClient + 'a, K: Keychain + 'a, { - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, is_running: Arc, } @@ -112,10 +112,7 @@ where K: Keychain + 'a, { /// create a new updater - pub fn new( - wallet_inst: Arc>>>, - is_running: Arc, - ) -> Self { + pub fn new(wallet_inst: crate::WalletHandle<'a, L, C, K>, is_running: Arc) -> Self { is_running.store(false, Ordering::Relaxed); Updater { wallet_inst, @@ -141,7 +138,7 @@ where if wallet_opened { owner::update_wallet_state( self.wallet_inst.clone(), - (&keychain_mask).as_ref(), + keychain_mask.as_ref(), status_send_channel, false, )?; diff --git a/libwallet/src/api_impl/types.rs b/libwallet/src/api_impl/types.rs index 9ab2f47..22a9f1a 100644 --- a/libwallet/src/api_impl/types.rs +++ b/libwallet/src/api_impl/types.rs @@ -14,14 +14,14 @@ //! Types specific to the wallet api, mostly argument serialization -use crate::grin_core::core::Output; -use crate::grin_core::libtx::secp_ser; -use crate::grin_keychain::{BlindingFactor, Identifier}; -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::{Error, NodeClient, Slate, SlatepackAddress, WalletBackend}; +use grin_core::core::Output; +use grin_core::libtx::secp_ser; +use grin_keychain::{BlindingFactor, Identifier}; +use grin_util::secp::pedersen; use chrono::prelude::*; use ed25519_dalek::Signature as DalekSignature; @@ -29,6 +29,7 @@ use grin_keychain::Keychain; use grin_util::secp::SecretKey; pub use crate::mwixnet::{Hop, MixnetReqCreationParams, SwapReq}; +use crate::slatepack::SlatepackAddressIndex; /// Type for storing amounts (in nanogrins). /// Serializes as a string but can deserialize from a string or u64. @@ -38,7 +39,7 @@ pub struct Amount(#[serde(with = "secp_ser::string_or_u64")] pub u64); /// V2 Init / Send TX API Args #[derive(Clone, Debug, Serialize, Deserialize)] pub struct InitTxArgs { - /// The human readable account name from which to draw outputs + /// The human-readable account name from which to draw outputs /// for the transaction, overriding whatever the active account is as set via the /// [`set_active_account`](../grin_wallet_api/owner/struct.Owner.html#method.set_active_account) method. pub src_acct_name: Option, @@ -90,6 +91,9 @@ pub struct InitTxArgs { /// inputs until just before finalization #[serde(default)] pub late_lock: Option, + /// Slatepack address index + #[serde(default)] + pub address_index: Option, /// Sender arguments. If present, the underlying function will also attempt to send the /// transaction to a destination and optionally finalize the result pub send_args: Option, @@ -125,15 +129,16 @@ impl Default for InitTxArgs { estimate_only: Some(false), payment_proof_recipient_address: None, late_lock: Some(false), + address_index: None, send_args: None, } } } /// V2 Issue Invoice Tx Args -#[derive(Clone, Serialize, Deserialize)] +#[derive(Clone, Serialize, Deserialize, Default)] pub struct IssueInvoiceTxArgs { - /// The human readable account name to which the received funds should be added + /// The human-readable account name to which the received funds should be added /// overriding whatever the active account is as set via the /// [`set_active_account`](../grin_wallet_api/owner/struct.Owner.html#method.set_active_account) method. pub dest_acct_name: Option, @@ -143,16 +148,8 @@ pub struct IssueInvoiceTxArgs { /// Optionally set the output target slate version (acceptable /// down to the minimum slate version compatible with the current. If `None`, V4 is used. pub target_slate_version: Option, -} - -impl Default for IssueInvoiceTxArgs { - fn default() -> IssueInvoiceTxArgs { - IssueInvoiceTxArgs { - dest_acct_name: None, - amount: 0, - target_slate_version: None, - } - } + /// Issuer slatepack address derivation path index. + pub address_index: Option, } /// Sort tx retrieval order @@ -187,7 +184,7 @@ pub struct RetrieveTxQueryArgs { /// Retrieve transactions with an id higher than or equal to the given /// If None, consider items from the first transaction and later pub min_id: Option, - /// Retrieve tranactions with an id less than or equal to the given + /// Retrieve transactions with an id less than or equal to the given /// If None, consider items from the last transaction and earlier pub max_id: Option, /// The maximum number of transactions to return @@ -226,7 +223,7 @@ pub struct RetrieveTxQueryArgs { pub min_confirmed_timestamp: Option>, /// higher bound on the confirmation timestamp, inclusive pub max_confirmed_timestamp: Option>, - /// Field within the tranasction list on which to sort + /// Field within the transaction list on which to sort /// defaults to ID if not present pub sort_field: Option, /// Sort order, defaults to ASC if not present (earliest is first) @@ -279,7 +276,7 @@ impl BlockFees { } } -/// Map Outputdata to commits +/// Map [OutputData] to commits #[derive(Serialize, Deserialize, Debug, Clone)] pub struct OutputCommitMapping { /// Output Data @@ -335,6 +332,9 @@ pub struct PaymentProof { /// Sender Signature #[serde(with = "dalek_ser::dalek_sig_serde")] pub sender_sig: DalekSignature, + /// Sender Slatepack address derivation path index + #[serde(default)] + pub sender_address_path: Option, } /// Build output result diff --git a/libwallet/src/backend.rs b/libwallet/src/backend.rs index be27342..876719d 100644 --- a/libwallet/src/backend.rs +++ b/libwallet/src/backend.rs @@ -21,6 +21,7 @@ use uuid::Uuid; use crate::blake2::blake2b::{Blake2b, Blake2bResult}; +use crate::slatepack::SlatepackAddressIndex; use crate::{ AcctPathMapping, Context, Error, NodeClient, OutputData, ScannedBlockInfo, TxLogEntry, WalletInitStatus, @@ -44,19 +45,21 @@ const CONFIRMED_HEIGHT_PREFIX: u8 = b'c'; const PRIVATE_TX_CONTEXT_PREFIX: u8 = b'p'; const TX_LOG_ENTRY_PREFIX: u8 = b't'; const TX_LOG_ID_PREFIX: u8 = b'i'; +const TX_ADDRESS_INDEX_PREFIX: u8 = b's'; const ACCOUNT_PATH_MAPPING_PREFIX: u8 = b'a'; const LAST_SCANNED_BLOCK: u8 = b'l'; const LAST_SCANNED_KEY: &str = "LAST_SCANNED_KEY"; const WALLET_INIT_STATUS: u8 = b'w'; const WALLET_INIT_STATUS_KEY: &str = "WALLET_INIT_STATUS"; -const DB_PREFIXES: [u8; 9] = [ +const DB_PREFIXES: [u8; 10] = [ OUTPUT_PREFIX, DERIV_PREFIX, CONFIRMED_HEIGHT_PREFIX, PRIVATE_TX_CONTEXT_PREFIX, TX_LOG_ENTRY_PREFIX, TX_LOG_ID_PREFIX, + TX_ADDRESS_INDEX_PREFIX, ACCOUNT_PATH_MAPPING_PREFIX, LAST_SCANNED_BLOCK, WALLET_INIT_STATUS, @@ -77,7 +80,7 @@ where // h(root_key|slate_id|"blind") let mut hasher = Blake2b::new(SECRET_KEY_SIZE); hasher.update(&root_key.0[..]); - hasher.update(&slate_id[..]); + hasher.update(slate_id); hasher.update(&b"blind"[..]); let blind_xor_key = hasher.finalize(); let mut ret_blind = [0; SECRET_KEY_SIZE]; @@ -86,7 +89,7 @@ where // h(root_key|slate_id|"nonce") let mut hasher = Blake2b::new(SECRET_KEY_SIZE); hasher.update(&root_key.0[..]); - hasher.update(&slate_id[..]); + hasher.update(slate_id); hasher.update(&b"nonce"[..]); let nonce_xor_key = hasher.finalize(); let mut ret_nonce = [0; SECRET_KEY_SIZE]; @@ -108,8 +111,8 @@ where pub keychain: Option, /// Check value for XORed keychain seed pub master_checksum: Box>, - /// Parent path to use by default for output operations - parent_key_id: Identifier, + /// BIP32 account path to use by default for output operations + active_account: AcctPathMapping, /// wallet to node client w2n_client: C, } @@ -138,30 +141,45 @@ where // Make sure default wallet derivation path always exists // as well as path (so it can be retrieved by batches to know where to store - // completed transactions, for reference + // completed transactions, for reference) let default_account = AcctPathMapping { - label: "default".to_owned(), + label: "default".to_string(), path: WalletBackend::::default_path(), + info: None, + current: Some(true), }; - { let mut batch = store.batch()?; - batch.put_ser( + let saved_default = batch.get_ser::( Some(ACCOUNT_PATH_MAPPING_PREFIX), default_account.label.as_bytes(), - &default_account, + None, )?; - batch.commit()?; + if saved_default.is_none() { + batch.put_ser( + Some(ACCOUNT_PATH_MAPPING_PREFIX), + default_account.label.as_bytes(), + &default_account, + )?; + batch.commit()?; + } } - let res = WalletBackend { + let mut res = WalletBackend { db: store, data_file_dir: data_file_dir.to_owned(), keychain: None, master_checksum: Box::new(None), - parent_key_id: WalletBackend::::default_path(), + active_account: default_account, w2n_client: n_client, }; + + // Set current active account + let active = res.acct_path_iter()?.find(|a| a.current.unwrap_or(false)); + if let Some(a) = active { + res.active_account = a; + } + Ok(res) } @@ -192,7 +210,7 @@ where let root_key = k.derive_key(0, &K::root_key_id(), SwitchCommitmentType::Regular)?; let mut hasher = Blake2b::new(SECRET_KEY_SIZE); hasher.update(&root_key.0[..]); - self.master_checksum = Box::new(Some(hasher.finalize())); + *self.master_checksum = Some(hasher.finalize()); let mask_value = { match mask { @@ -202,9 +220,9 @@ where let mask_value = match use_test_rng { true => { let mut test_rng = StepRng::new(1_234_567_890_u64, 1); - SecretKey::new(&k.secp(), &mut test_rng) + SecretKey::new(k.secp(), &mut test_rng) } - false => SecretKey::new(&k.secp(), &mut thread_rng()), + false => SecretKey::new(k.secp(), &mut thread_rng()), }; k.mask_master_key(&mask_value)?; Some(mask_value) @@ -267,7 +285,7 @@ where } else {*/ Ok(Some( self.keychain(keychain_mask)? - .commit(amount, &id, SwitchCommitmentType::Regular)? + .commit(amount, id, SwitchCommitmentType::Regular)? .0 .to_vec() .to_hex(), // TODO: proper support for different switch commitment schemes @@ -275,27 +293,55 @@ where /*}*/ } - /// Set parent key id by stored account name. - pub fn set_parent_key_id_by_name(&mut self, label: &str) -> Result<(), Error> { + /// Set current active account by stored account name. + pub fn set_active_account( + &mut self, + keychain_mask: Option<&SecretKey>, + label: &str, + ) -> Result<(), Error> { + let res = self.acct_path_iter()?.find(|l| l.label == label); + match res { + None => Err(Error::UnknownAccountLabel(label.to_string())), + Some(mut a) => { + let mut batch = self.batch(keychain_mask)?; + let current = batch + .acct_path_iter()? + .filter(|a| a.current.unwrap_or(false)) + .collect::>(); + for mut a in current { + a.current = None; + batch.save_acct_path(a.clone())?; + } + a.current = Some(true); + batch.save_acct_path(a.clone())?; + batch.commit()?; + + self.active_account = a; + Ok(()) + } + } + } + + /// Set account by stored account name. + pub fn set_account_by_name(&mut self, label: &str) -> Result<(), Error> { let label = label.to_owned(); let res = self.acct_path_iter()?.find(|l| l.label == label); if let Some(a) = res { - self.set_parent_key_id(a.path); + self.active_account = a; Ok(()) } else { Err(Error::UnknownAccountLabel(label)) } } - /// The BIP32 path of the parent path to use for all output-related - /// functions, essentially 'accounts' within a wallet. - pub fn set_parent_key_id(&mut self, id: Identifier) { - self.parent_key_id = id; + /// Get active account. + pub fn active_account(&self) -> AcctPathMapping { + self.active_account.clone() } /// Get the parent path. pub fn parent_key_id(&mut self) -> Identifier { - self.parent_key_id.clone() + self.active_account.path.clone() } /// Get output data by id. @@ -338,10 +384,16 @@ where } /// Get an (Optional) tx log entry by uuid. - pub fn get_tx_log_entry(&self, u: &Uuid) -> Result, Error> { - self.db - .get_ser(Some(TX_LOG_ENTRY_PREFIX), u.as_bytes(), None) - .map_err(|e| e.into()) + pub fn get_tx_log_entry( + &self, + id: &Uuid, + parent_id: &Identifier, + ) -> Result, Error> { + let tx = self + .tx_log_iter()? + .flatten() + .find(|tx| tx.parent_key_id == *parent_id && tx.tx_slate_id == Some(*id)); + Ok(tx) } /// Iterate over all tx log data stored by the backend. @@ -361,6 +413,54 @@ where .map_err(From::from) } + /// Next transaction slatepack address derivation path index. + pub fn next_tx_slatepack_address_index( + &mut self, + parent_key_id: &Identifier, + ) -> Result { + let mut index = { + let batch = self.db.batch()?; + batch + .get_ser( + Some(TX_ADDRESS_INDEX_PREFIX), + &parent_key_id.to_bytes(), + None, + )? + .unwrap_or(0) + }; + if index >= SlatepackAddressIndex::MAX { + return Err(Error::SlatepackAddress( + "Slatepack address indices exhausted".into(), + )); + } + index += 1; + let mut batch = self.db.batch()?; + batch.put_ser( + Some(TX_ADDRESS_INDEX_PREFIX), + &parent_key_id.to_bytes(), + &index, + )?; + batch.commit()?; + Ok(SlatepackAddressIndex(index)) + } + + /// Iterator over private tx contexts. + pub fn private_context_iter( + &self, + ) -> Result>, Error> { + let protocol_version = self.db.protocol_version(); + self.db + .iter(Some(PRIVATE_TX_CONTEXT_PREFIX), move |_, mut v| { + ser::deserialize( + &mut v, + protocol_version, + ser::DeserializationMode::default(), + ) + .map_err(From::from) + }) + .map_err(From::from) + } + /// Retrieve the private context associated with a given slate id. pub fn get_private_context( &mut self, @@ -418,7 +518,7 @@ where let path_buf = Path::new(&path).to_path_buf(); let mut stored_tx = File::create(path_buf)?; let tx_hex = ser::ser_vec(tx, ser::ProtocolVersion(1)).unwrap().to_hex(); - stored_tx.write_all(&tx_hex.as_bytes())?; + stored_tx.write_all(tx_hex.as_bytes())?; stored_tx.sync_all()?; Ok(()) } @@ -490,14 +590,14 @@ where /// Next child ID when we want to create a new output, based on current parent. pub fn next_child(&mut self, keychain_mask: Option<&SecretKey>) -> Result { - let parent_key_id = self.parent_key_id.clone(); + let parent_key_id = self.active_account.path.clone(); self.next_child_for(&parent_key_id, keychain_mask) } /// Last verified height of outputs directly descending from the current parent key. pub fn last_confirmed_height(&mut self) -> Result { - let parent_key_id = self.parent_key_id.clone(); - self.last_confirmed_height_for_parent(&parent_key_id) + let parent_key_id = self.active_account.clone(); + self.last_confirmed_height_for_parent(&parent_key_id.path) } /// Last verified height of outputs directly descending from the given parent key. @@ -512,7 +612,7 @@ where &parent_key_id.to_bytes(), None, )? - .unwrap_or_else(|| 0); + .unwrap_or(0); Ok(last_confirmed_height) } @@ -539,7 +639,7 @@ where WALLET_INIT_STATUS_KEY.as_bytes(), None, )? - .unwrap_or_else(|| WalletInitStatus::InitComplete); + .unwrap_or(WalletInitStatus::InitComplete); Ok(status) } } @@ -667,7 +767,7 @@ where let last_tx_log_id = self .db .get_ser(Some(TX_LOG_ID_PREFIX), &parent_key_id.to_bytes(), None)? - .unwrap_or_else(|| 0); + .unwrap_or(0); self.db.put_ser( Some(TX_LOG_ID_PREFIX), &parent_key_id.to_bytes(), @@ -713,7 +813,8 @@ where } /// Save an account label -> path mapping. - pub fn save_acct_path(&mut self, mapping: AcctPathMapping) -> Result<(), Error> { + pub fn save_acct_path(&mut self, mut mapping: AcctPathMapping) -> Result<(), Error> { + mapping.info = None; self.db.put_ser( Some(ACCOUNT_PATH_MAPPING_PREFIX), mapping.label.as_bytes(), diff --git a/libwallet/src/contract/actions/new.rs b/libwallet/src/contract/actions/new.rs index 0df0fc8..2a1ed77 100644 --- a/libwallet/src/contract/actions/new.rs +++ b/libwallet/src/contract/actions/new.rs @@ -19,11 +19,11 @@ use crate::contract; use crate::contract::actions::setup; use crate::contract::types::ContractSetupArgsAPI; use crate::error::Error; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; use crate::internal::tx; use crate::slate::Slate; use crate::types::{Context, NodeClient}; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; use uuid::Uuid; /// Create a new contract with initial setup done by the initiator. `slate_id`, when diff --git a/libwallet/src/contract/actions/revoke.rs b/libwallet/src/contract/actions/revoke.rs index dba1854..cddc941 100644 --- a/libwallet/src/contract/actions/revoke.rs +++ b/libwallet/src/contract/actions/revoke.rs @@ -18,11 +18,11 @@ use crate::blake2::blake2b::blake2b; use crate::contract::types::{ContractRevokeArgsAPI, ContractSetupArgsAPI, OutputSelectionArgs}; use crate::contract::{new, sign, utils}; use crate::error::Error; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; use crate::internal::tx; use crate::slate::Slate; use crate::types::{NodeClient, OutputData, OutputStatus, TxLogEntryType}; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; use uuid::Uuid; /// Deterministic slate id for the self-spend that revokes a given contract slate. diff --git a/libwallet/src/contract/actions/setup.rs b/libwallet/src/contract/actions/setup.rs index cc86e8f..1c9d6d0 100644 --- a/libwallet/src/contract/actions/setup.rs +++ b/libwallet/src/contract/actions/setup.rs @@ -19,11 +19,11 @@ use crate::backend::WalletBackend; use crate::contract; use crate::contract::types::ContractSetupArgsAPI; use crate::error::Error; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; use crate::slate::Slate; use crate::types::{Context, NodeClient}; use grin_core::core::FeeFields; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; // Contract deadlines use the node tip because the active account may not own the context fn check_contract_ttl(w: &mut WalletBackend, slate: &Slate) -> Result<(), Error> diff --git a/libwallet/src/contract/actions/sign.rs b/libwallet/src/contract/actions/sign.rs index 8d981e3..3accbfb 100644 --- a/libwallet/src/contract/actions/sign.rs +++ b/libwallet/src/contract/actions/sign.rs @@ -20,10 +20,10 @@ use crate::contract; use crate::contract::actions::setup; use crate::contract::types::ContractSetupArgsAPI; use crate::error::Error; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; use crate::slate::{Slate, SlateState}; use crate::types::{Context, NodeClient}; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; fn verify_first_sign_net_change( state: &SlateState, diff --git a/libwallet/src/contract/actions/view.rs b/libwallet/src/contract/actions/view.rs index fd28c64..5fa11ff 100644 --- a/libwallet/src/contract/actions/view.rs +++ b/libwallet/src/contract/actions/view.rs @@ -19,11 +19,11 @@ use crate::backend::WalletBackend; use crate::contract; use crate::contract::types::{ContractView, OwnCommitmentStatus}; use crate::error::Error; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; use crate::internal::updater; use crate::slate::{Slate, SlateState}; use crate::types::{NodeClient, TxLogEntry}; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; fn balance_change(net_change: Option, fee: Option) -> Result, Error> { match (net_change, fee) { @@ -177,7 +177,7 @@ mod tests { #[test] fn reads_change_from_tx_log() { let mut tx = TxLogEntry::new( - crate::grin_keychain::Identifier::zero(), + grin_keychain::Identifier::zero(), crate::types::TxLogEntryType::TxReceived, 0, ); diff --git a/libwallet/src/contract/context.rs b/libwallet/src/contract/context.rs index 89d3df3..85dcf31 100644 --- a/libwallet/src/contract/context.rs +++ b/libwallet/src/contract/context.rs @@ -18,13 +18,13 @@ use crate::backend::WalletBackend; use crate::contract::selection::prepare_outputs; use crate::contract::types::ContractSetupArgsAPI; use crate::contract::utils as contract_utils; -use crate::grin_keychain::{Identifier, Keychain}; -use crate::grin_util::secp::key::SecretKey; use crate::internal::updater; use crate::slate::Slate; use crate::types::{Context, NodeClient}; use crate::{Error, OutputData}; use grin_core::core::FeeFields; +use grin_keychain::{Identifier, Keychain}; +use grin_util::secp::key::SecretKey; /// Get or create transaction Context for the given slate pub fn get_or_create( @@ -189,7 +189,7 @@ fn add_inputs_to_ctx(context: &mut Context, inputs: &[OutputData]) { context.add_input(&input.key_id, &input.mmr_index, input.value); debug!( "contract::utils::add_inputs_to_ctx => input id: {}, value:{}", - &input.key_id, input.value + input.key_id, input.value ); } } diff --git a/libwallet/src/contract/proofs.rs b/libwallet/src/contract/proofs.rs index c5f8f6f..d7e9365 100644 --- a/libwallet/src/contract/proofs.rs +++ b/libwallet/src/contract/proofs.rs @@ -16,13 +16,14 @@ use crate::backend::WalletBackend; use crate::contract::types::ProofArgs; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::Secp256k1; use crate::payment_proof::EarlyPaymentProof; use crate::slate::{PaymentProofType, Slate}; +use crate::slatepack::SlatepackAddressIndex; use crate::types::{Context, NodeClient}; use crate::{address, Error}; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; +use grin_util::secp::Secp256k1; /// Commit the payer nonce to the sender-nonce proof fields. pub(super) fn commit_sender_nonce( @@ -67,7 +68,9 @@ where { let keychain = wallet.keychain(keychain_mask)?; let participant_index = slate.find_index_matching_context(&keychain, context)?; - let derivation_index = context.payment_proof_derivation_index.unwrap_or(0); + let derivation_index = context + .payment_proof_derivation_index + .unwrap_or(SlatepackAddressIndex(0)); let receiver_key = address::address_from_derivation_path(&keychain, &context.parent_key_id, derivation_index)?; slate.add_payment_proof_data( diff --git a/libwallet/src/contract/selection.rs b/libwallet/src/contract/selection.rs index a44ff9d..fb62056 100644 --- a/libwallet/src/contract/selection.rs +++ b/libwallet/src/contract/selection.rs @@ -17,11 +17,11 @@ use crate::backend::WalletBackend; use crate::contract::types::{ContractSetupArgsAPI, OutputSelectionArgs}; use crate::contract::utils::fee_contribution; -use crate::grin_core::core::amount_to_hr_string; -use crate::grin_keychain::{Identifier, Keychain}; use crate::types::NodeClient; use crate::{Error, OutputData}; +use grin_core::core::amount_to_hr_string; use grin_core::core::FeeFields; +use grin_keychain::{Identifier, Keychain}; /// Prepares inputs & outputs that satisfy `Σmy_inputs >= Σmy_outputs + my_fee_cost` taking into account selection args pub fn prepare_outputs( @@ -382,8 +382,8 @@ mod tests { use super::*; use crate::contract::utils::my_fee_contribution; - use crate::grin_keychain::{Identifier, IDENTIFIER_SIZE}; use crate::OutputStatus; + use grin_keychain::{Identifier, IDENTIFIER_SIZE}; fn _create_output_data_for(amounts: Vec) -> Vec { let mut rv: Vec = vec![]; @@ -396,7 +396,7 @@ mod tests { key_id: key_id.clone(), n_child: key_id.clone().to_path().last_path_index(), mmr_index: None, - commit: Some(format!("{}{}", "abc", idx.to_string())), + commit: Some(format!("{}{}", "abc", idx)), value: *amount, status: OutputStatus::Unspent, height: 1, @@ -451,7 +451,7 @@ mod tests { }, ..Default::default() }; - assert!(compute(&setup_args, None, &mut vec![]).is_err()); + assert!(compute(&setup_args, None, &mut []).is_err()); let setup_args = ContractSetupArgsAPI { net_change: Some(-1), @@ -472,7 +472,7 @@ mod tests { }, ..Default::default() }; - assert!(compute(&setup_args, None, &mut vec![]).is_err()); + assert!(compute(&setup_args, None, &mut []).is_err()); } #[test] @@ -491,7 +491,7 @@ mod tests { false, ), }; - let result = compute(&setup_args, None, &mut vec![]); + let result = compute(&setup_args, None, &mut []); assert_eq!(result.err().unwrap(), expected); } @@ -534,7 +534,7 @@ mod tests { let expected_fee = my_fee_contribution(3, 1, 1, 2).unwrap(); let expected_output_amounts = vec![ // we expect a single output with change holding 5 - 3 - fees - (5_000_000_000 as i64 + (setup_args.net_change.unwrap())) as u64 - expected_fee.fee(), + (5_000_000_000_i64 + (setup_args.net_change.unwrap())) as u64 - expected_fee.fee(), ]; let result = compute(&setup_args, None, &mut inputs.clone()).unwrap(); @@ -648,7 +648,7 @@ mod tests { ..Default::default() }; let expected_fee = my_fee_contribution(0, 1, 1, 2).unwrap(); - let result = compute(&setup_args, None, &mut vec![]).unwrap(); + let result = compute(&setup_args, None, &mut []).unwrap(); assert_eq!( result, @@ -664,7 +664,7 @@ mod tests { ..Default::default() }; assert!(matches!( - compute(&setup_args, None, &mut vec![]), + compute(&setup_args, None, &mut []), Err(Error::NotEnoughFunds { .. }) )); } @@ -680,7 +680,7 @@ mod tests { ..Default::default() }; let expected_fee = my_fee_contribution(0, 2, 1, 2).unwrap(); - let result = compute(&setup_args, None, &mut vec![]).unwrap(); + let result = compute(&setup_args, None, &mut []).unwrap(); assert_eq!( result, ( @@ -712,7 +712,7 @@ mod tests { let expected_fee = my_fee_contribution(3, 1, 1, 2).unwrap(); let expected_output_amounts = vec![ // we expect a single output with change holding 3 - fees - (8_000_000_000 as i64 + setup_args.net_change.unwrap()) as u64 - expected_fee.fee(), + (8_000_000_000_i64 + setup_args.net_change.unwrap()) as u64 - expected_fee.fee(), ]; let result = compute(&setup_args, None, &mut inputs.clone()).unwrap(); @@ -744,10 +744,8 @@ mod tests { 3_000_000_000, // abc2 4_000_000_000, ]); - let msg = format!( - "We have not found all the inputs that have been requested. abc0,abc2,abc5, found only: 2" - ); - let expected_err = Error::GenericError(msg.into()).into(); + let msg = "We have not found all the inputs that have been requested. abc0,abc2,abc5, found only: 2".to_string(); + let expected_err = Error::GenericError(msg); let result = compute(&setup_args, None, &mut inputs.clone()); assert_eq!(result.err().unwrap(), expected_err); diff --git a/libwallet/src/contract/slate.rs b/libwallet/src/contract/slate.rs index f3209b8..30619be 100644 --- a/libwallet/src/contract/slate.rs +++ b/libwallet/src/contract/slate.rs @@ -15,18 +15,19 @@ //! Contract functions on the Slate use crate::backend::WalletBackend; -use crate::grin_core::core::transaction::{Inputs, OutputFeatures, OutputIdentifier}; -use crate::grin_core::libtx::build; -use crate::grin_core::libtx::proof::ProofBuilder; -use crate::grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; -use crate::grin_util::from_hex; -use crate::grin_util::secp::constants::PEDERSEN_COMMITMENT_SIZE; -use crate::grin_util::secp::key::{PublicKey, SecretKey}; -use crate::grin_util::secp::pedersen::Commitment; use crate::slate::{Slate, SlateState}; +use crate::slatepack::SlatepackAddressIndex; use crate::types::{Context, NodeClient, OutputData}; use crate::util::OnionV3Address; use crate::Error; +use grin_core::core::transaction::{Inputs, OutputFeatures, OutputIdentifier}; +use grin_core::libtx::build; +use grin_core::libtx::proof::ProofBuilder; +use grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; +use grin_util::from_hex; +use grin_util::secp::constants::PEDERSEN_COMMITMENT_SIZE; +use grin_util::secp::key::{PublicKey, SecretKey}; +use grin_util::secp::pedersen::Commitment; use std::collections::BTreeSet; use super::types::{OwnCommitmentStatus, ProofArgs}; @@ -88,7 +89,9 @@ where .enumerate() .find_map(|(index, _)| (index != payer_index).then_some(index)) .ok_or_else(|| Error::GenericError("Payment promise has no receiver".to_string()))?; - let derivation_index = context.payment_proof_derivation_index.unwrap_or(0); + let derivation_index = context + .payment_proof_derivation_index + .unwrap_or(SlatepackAddressIndex(0)); let sender_key = crate::address::address_from_derivation_path( keychain, &context.parent_key_id, @@ -560,8 +563,8 @@ where #[cfg(test)] mod tests { use super::*; - use crate::grin_keychain::{ExtKeychain, SwitchCommitmentType}; use crate::slate::ParticipantData; + use grin_keychain::{ExtKeychain, SwitchCommitmentType}; fn keychain_and_context() -> (ExtKeychain, Context) { let keychain = ExtKeychain::from_random_seed(true).unwrap(); diff --git a/libwallet/src/contract/types.rs b/libwallet/src/contract/types.rs index f48f574..07eed92 100644 --- a/libwallet/src/contract/types.rs +++ b/libwallet/src/contract/types.rs @@ -15,10 +15,10 @@ //! Types related to a contract use crate::error::Error; -use crate::grin_core::libtx::secp_ser; pub use crate::slate::{PaymentMemo, PaymentProofType as ProofType}; use crate::slate_versions::ser as dalek_ser; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::libtx::secp_ser; /// Default confirmations for contract inputs /// Keep in sync with contract new in grin-wallet.yml @@ -306,8 +306,10 @@ mod tests { #[test] fn contract_ttl_json() { - let mut args = ContractNewArgsAPI::default(); - args.ttl_blocks = Some(20); + let args = ContractNewArgsAPI { + ttl_blocks: Some(20), + ..Default::default() + }; let mut json = serde_json::to_value(&args).unwrap(); assert_eq!(json["ttl_blocks"], "20"); diff --git a/libwallet/src/contract/utils.rs b/libwallet/src/contract/utils.rs index 1606a0e..e46b37d 100644 --- a/libwallet/src/contract/utils.rs +++ b/libwallet/src/contract/utils.rs @@ -17,14 +17,15 @@ use crate::backend::WalletBackend; use crate::contract::selection::verify_selection_consistency; use crate::contract::types::ContractSetupArgsAPI; -use crate::grin_core::libtx::tx_fee; -use crate::grin_keychain::{Identifier, Keychain}; -use crate::grin_util::secp::key::SecretKey; use crate::slate::{PaymentProofType, Slate}; +use crate::slatepack::SlatepackAddressIndex; use crate::types::{Context, NodeClient, StoredProofInfo, TxLogEntryType}; use crate::util::OnionV3Address; use crate::{address, Error, OutputData, OutputStatus, TxLogEntry}; use grin_core::core::{FeeFields, Transaction}; +use grin_core::libtx::tx_fee; +use grin_keychain::{Identifier, Keychain}; +use grin_util::secp::key::SecretKey; use uuid::Uuid; /// Creates an initial TxLogEntry without input/output or kernel information @@ -92,7 +93,7 @@ where .timestamp .ok_or_else(|| Error::PaymentProof("Missing proof timestamp".to_string()))?; // note we only use a single path for now - let sender_address_path = 0u32; + let sender_address_path = SlatepackAddressIndex(0); let sender_key = address::address_from_derivation_path( keychain, &parent_key_id, diff --git a/libwallet/src/error.rs b/libwallet/src/error.rs index c9248ca..eefdaa7 100644 --- a/libwallet/src/error.rs +++ b/libwallet/src/error.rs @@ -14,16 +14,18 @@ //! Error types for libwallet -use crate::grin_core::core::{amount_to_hr_string, committed, transaction}; -use crate::grin_core::libtx; -use crate::grin_keychain; -use crate::grin_util::secp; use crate::util; -use grin_store; +use grin_core::core::{amount_to_hr_string, committed, transaction}; +use grin_core::libtx; +use grin_util::secp; /// Wallet errors, mostly wrappers around underlying crypto or I/O errors. #[derive(Clone, Eq, PartialEq, Debug, thiserror::Error, Serialize, Deserialize)] pub enum Error { + /// Invalid transaction amount + #[error("Invalid amount (must be greater than zero)")] + InvalidAmount, + /// Not enough funds #[error("Not enough funds. Required: {needed_disp:?}, Available: {available_disp:?}")] NotEnoughFunds { @@ -103,7 +105,7 @@ pub enum Error { /// Other serialization errors #[error("Ser/Deserialization error")] - Deser(crate::grin_core::ser::Error), + Deser(grin_core::ser::Error), /// IO Error #[error("I/O error {0}")] diff --git a/libwallet/src/internal/keys.rs b/libwallet/src/internal/keys.rs index 21c937a..313f8a5 100644 --- a/libwallet/src/internal/keys.rs +++ b/libwallet/src/internal/keys.rs @@ -14,10 +14,10 @@ //! Wallet key management functions use crate::error::Error; -use crate::grin_keychain::{ChildNumber, ExtKeychain, Identifier, Keychain}; -use crate::grin_util::secp::key::SecretKey; use crate::types::{AcctPathMapping, NodeClient}; use crate::WalletBackend; +use grin_keychain::{ChildNumber, ExtKeychain, Identifier, Keychain}; +use grin_util::secp::key::SecretKey; /// Get next available key in the wallet for a given parent pub fn next_available_key( @@ -68,7 +68,7 @@ where K: Keychain, { let label = label.to_owned(); - if wallet.acct_path_iter()?.any(|l| l.label == label) { + if wallet.acct_path_iter()?.any(|a| a.label == label) { return Err(Error::AccountLabelAlreadyExists(label)); } @@ -93,6 +93,8 @@ where let save_path = AcctPathMapping { label, path: return_id.clone(), + info: None, + current: None, }; let mut batch = wallet.batch(keychain_mask)?; @@ -116,6 +118,8 @@ where let save_path = AcctPathMapping { label, path: path.clone(), + info: None, + current: None, }; let mut batch = wallet.batch(keychain_mask)?; diff --git a/libwallet/src/internal/scan.rs b/libwallet/src/internal/scan.rs index fb5ec73..5371a36 100644 --- a/libwallet/src/internal/scan.rs +++ b/libwallet/src/internal/scan.rs @@ -14,44 +14,34 @@ //! Functions to restore a wallet's outputs from just the master seed use crate::api_impl::owner_updater::StatusMessage; -use crate::grin_core::consensus::{valid_header_version, WEEK_HEIGHT}; -use crate::grin_core::core::HeaderVersion; -use crate::grin_core::global; -use crate::grin_core::libtx::proof; -use crate::grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::pedersen; -use crate::grin_util::secp::{ContextFlag, Secp256k1}; -use crate::grin_util::Mutex; -use crate::grin_util::{from_hex, ToHex}; use crate::internal::{keys, updater}; use crate::types::*; use crate::{wallet_lock, Error, OutputCommitMapping}; use blake2_rfc::blake2b::blake2b; +use grin_core::consensus::{valid_header_version, WEEK_HEIGHT}; +use grin_core::core::HeaderVersion; +use grin_core::global; +use grin_core::libtx::proof; +use grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; +use grin_util::secp::key::SecretKey; +use grin_util::secp::pedersen; +use grin_util::secp::{ContextFlag, Secp256k1}; +use grin_util::{from_hex, ToHex}; use rayon::prelude::*; use std::cmp; use std::collections::HashMap; use std::sync::mpsc::Sender; -use std::sync::Arc; /// Utility struct for return values from below #[derive(Debug, Clone)] struct OutputResult { - /// pub commit: pedersen::Commitment, - /// pub key_id: Identifier, - /// pub n_child: u32, - /// pub mmr_index: u64, - /// pub value: u64, - /// pub height: u64, - /// pub lock_height: u64, - /// pub is_coinbase: bool, } @@ -293,7 +283,7 @@ where const MISSING_OUTPUTS_BATCH_SIZE: usize = 1000; fn restore_missing_outputs<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, outputs: Vec, found_parents: &mut HashMap, @@ -359,9 +349,8 @@ where Ok(()) } -/// fn cancel_tx_log_entry<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, output: &OutputData, ) -> Result<(), Error> @@ -406,7 +395,7 @@ where /// Scan outputs with a given rewind hash view wallet. /// Retrieve all outputs information that belongs to it. pub fn scan_rewind_hash<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, rewind_hash: String, start_height: u64, end_height: u64, @@ -463,8 +452,9 @@ where /// The returned `ScannedBlockInfo` is the progress marker to persist after the /// batch. The returned PMMR range can be passed into the next batch to avoid /// looking up the full range again. +#[allow(clippy::too_many_arguments)] pub fn scan<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, delete_unconfirmed: bool, batch_start_height: u64, @@ -642,7 +632,7 @@ where keys::set_acct_path(w, keychain_mask, &label, path)?; acct_index += 1; } - let current_child_index = w.current_child_index(&path)?; + let current_child_index = w.current_child_index(path)?; if *max_child_index >= current_child_index { let mut batch = w.batch(keychain_mask)?; debug!("Next child for account {} is {}", path, max_child_index + 1); diff --git a/libwallet/src/internal/selection.rs b/libwallet/src/internal/selection.rs index bb26b10..8218359 100644 --- a/libwallet/src/internal/selection.rs +++ b/libwallet/src/internal/selection.rs @@ -15,22 +15,22 @@ //! Selection of inputs for building transactions use crate::error::Error; -use crate::grin_core::core::amount_to_hr_string; -use crate::grin_core::libtx::{ - build, - proof::{ProofBuild, ProofBuilder}, - tx_fee, -}; -use crate::grin_keychain::{Identifier, Keychain}; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::pedersen; use crate::internal::keys; use crate::slate::Slate; use crate::types::*; use crate::util::OnionV3Address; use crate::{address, WalletBackend}; +use grin_core::core::amount_to_hr_string; use grin_core::core::Transaction; use grin_core::global; +use grin_core::libtx::{ + build, + proof::{ProofBuild, ProofBuilder}, + tx_fee, +}; +use grin_keychain::{Identifier, Keychain}; +use grin_util::secp::key::SecretKey; +use grin_util::secp::pedersen; use std::collections::HashMap; use std::convert::TryInto; @@ -38,7 +38,7 @@ use std::convert::TryInto; /// libwallet transaction slate with the appropriate inputs selected, /// and saves the private wallet identifiers of our selected outputs /// into our transaction context - +#[allow(clippy::too_many_arguments)] pub fn build_send_tx( wallet: &mut WalletBackend, keychain: &K, @@ -73,9 +73,12 @@ where false, )?; if amount_includes_fee { - slate.amount = slate.amount.checked_sub(fee).ok_or(Error::GenericError( - "Transaction amount is too small to include fee".to_string(), - ))?; + let small_amount_err = + Error::GenericError("Transaction amount is too small to include fee".to_string()); + if slate.amount == fee { + return Err(small_amount_err); + } + slate.amount = slate.amount.checked_sub(fee).ok_or(small_amount_err)?; }; if fixed_fee.map(|f| fee != f).unwrap_or(false) { @@ -104,15 +107,9 @@ where context.add_input(&input.key_id, &input.mmr_index, input.value); } - let mut commits: HashMap> = HashMap::new(); - - // Store change output(s) and cached commits + // Store change output(s) for (change_amount, id, mmr_index) in &change_amounts_derivations { - context.add_output(&id, &mmr_index, *change_amount); - commits.insert( - id.clone(), - wallet.calc_commit_for_cache(keychain_mask, *change_amount, &id)?, - ); + context.add_output(id, mmr_index, *change_amount); } Ok(context) @@ -139,7 +136,7 @@ where output_commits.insert( id.clone(), ( - wallet.calc_commit_for_cache(keychain_mask, *change_amount, &id)?, + wallet.calc_commit_for_cache(keychain_mask, *change_amount, id)?, *change_amount, ), ); @@ -194,8 +191,7 @@ where None => { return Err(Error::PaymentProof( "Payment proof derivation index required".to_owned(), - ) - .into()); + )); } }; let sender_key = address::address_from_derivation_path( @@ -213,11 +209,12 @@ where None, )); }; + t.address_index = context.payment_proof_derivation_index; // write the output representing our change for (id, _, _) in &context.get_outputs() { t.num_outputs += 1; - let (commit, change_amount) = output_commits.get(&id).unwrap().clone(); + let (commit, change_amount) = output_commits.get(id).unwrap().clone(); t.amount_credited += change_amount; batch.save(OutputData { root_key_id: parent_key_id.clone(), @@ -319,6 +316,7 @@ where /// Builds a transaction to send to someone from the HD seed associated with the /// wallet and the amount to send. Handles reading through the wallet data file, /// selecting outputs to spend and building the change. +#[allow(clippy::too_many_arguments, clippy::type_complexity)] pub fn select_send_tx( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -354,7 +352,7 @@ where max_outputs, change_outputs, selection_strategy_is_use_all, - &parent_key_id, + parent_key_id, )?; // build transaction skeleton with inputs and change @@ -372,6 +370,7 @@ where } /// Select outputs and calculating fee. +#[allow(clippy::too_many_arguments)] pub fn select_coins_and_fee( wallet: &mut WalletBackend, amount: u64, @@ -573,6 +572,7 @@ where } /// Selects inputs and change for a transaction +#[allow(clippy::type_complexity)] pub fn inputs_and_change( coins: &[OutputData], wallet: &mut WalletBackend, @@ -762,7 +762,7 @@ where let keychain = wallet.keychain(keychain_mask)?; // restore my signature data - slate.add_participant_info(&keychain, &context, None)?; + slate.add_participant_info(&keychain, context, None)?; let mut parts = vec![]; for (id, mmr_index, value) in &context.get_inputs() { diff --git a/libwallet/src/internal/tx.rs b/libwallet/src/internal/tx.rs index 4c7c8ba..06a97e1 100644 --- a/libwallet/src/internal/tx.rs +++ b/libwallet/src/internal/tx.rs @@ -18,13 +18,9 @@ use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::io::Cursor; use uuid::Uuid; -use crate::grin_core::consensus::header_version; -use crate::grin_keychain::{Identifier, Keychain}; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::pedersen; -use crate::grin_util::Mutex; use crate::internal::{selection, updater}; use crate::slate::{PaymentProofType, Slate}; +use crate::slatepack::SlatepackAddressIndex; use crate::types::{Context, NodeClient, StoredProofInfo, TxLogEntryType}; use crate::util::OnionV3Address; use crate::{address, Error}; @@ -33,7 +29,12 @@ 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::consensus::header_version; use grin_core::core::FeeFields; +use grin_keychain::{Identifier, Keychain}; +use grin_util::secp::key::SecretKey; +use grin_util::secp::pedersen; +use grin_util::Mutex; // static for incrementing test UUIDs lazy_static! { @@ -81,6 +82,7 @@ where } /// Estimates locked amount and fee for the transaction without creating one +#[allow(clippy::too_many_arguments)] pub fn estimate_send_tx( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -132,6 +134,7 @@ where } /// Add inputs to the slate (effectively becoming the sender) +#[allow(clippy::too_many_arguments)] pub fn add_inputs_to_slate( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -236,7 +239,7 @@ where // update excess in stored transaction let mut batch = wallet.batch(keychain_mask)?; tx.kernel_excess = Some(slate.calc_excess(keychain.secp())?); - batch.save_tx_log_entry(tx.clone(), &parent_key_id)?; + batch.save_tx_log_entry(tx, parent_key_id)?; batch.commit()?; } @@ -273,14 +276,14 @@ where init_tx_args.max_outputs as usize, init_tx_args.num_change_outputs as usize, init_tx_args.selection_strategy_is_use_all, - &parent_key_id, + parent_key_id, )?; slate.fee_fields = FeeFields::new(0, fee)?; let keychain = wallet.keychain(keychain_mask)?; // Create our own private context - let mut context = Context::new(keychain.secp(), &parent_key_id, use_test_rng, true); + let mut context = Context::new(keychain.secp(), parent_key_id, use_test_rng, true); context.fee = Some(slate.fee_fields); context.amount = slate.amount; context.late_lock_args = Some(init_tx_args.clone()); @@ -342,14 +345,8 @@ where } else if let Some(tx_slate_id) = tx_slate_id { tx_id_string = tx_slate_id.to_string(); } - let tx_vec = updater::retrieve_txs( - wallet, - tx_id, - tx_slate_id, - None, - Some(&parent_key_id), - false, - )?; + let tx_vec = + updater::retrieve_txs(wallet, tx_id, tx_slate_id, None, Some(parent_key_id), false)?; if tx_vec.is_empty() { return Err(Error::TransactionDoesntExist(tx_id_string)); } @@ -382,7 +379,7 @@ where updater::cancel_txs_and_outputs(wallet, keychain_mask, to_cancel, parent_key_id) } -/// Update the stored transaction (this update needs to happen when the TX is finalised) +/// Update the stored transaction (this update needs to happen when the TX is finalized) pub fn update_stored_tx( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -420,7 +417,9 @@ where if let Some(ref p) = slate.clone().payment_proof { if let Some(saddr) = p.sender_address { - let derivation_index = context.payment_proof_derivation_index.unwrap_or(0); + let derivation_index = context + .payment_proof_derivation_index + .unwrap_or(SlatepackAddressIndex(0)); let keychain = wallet.keychain(keychain_mask)?; let parent_key_id = wallet.parent_key_id(); let excess = slate.calc_excess(keychain.secp())?; @@ -464,12 +463,12 @@ pub fn _decode_payment_proof_message( let mut rdr = Cursor::new(msg); let amount = rdr.read_u64::()?; let mut commit_bytes = [0u8; 33]; - for i in 0..33 { - commit_bytes[i] = rdr.read_u8()?; + for byte in &mut commit_bytes { + *byte = rdr.read_u8()?; } let mut sender_address_bytes = [0u8; 32]; - for i in 0..32 { - sender_address_bytes[i] = rdr.read_u8()?; + for byte in &mut sender_address_bytes { + *byte = rdr.read_u8()?; } Ok(( @@ -511,13 +510,15 @@ where Some(parent_key_id), false, )?; - if tx_vec.is_empty() { - return Err(Error::PaymentProof( - "TxLogEntry with original proof info not found (is account correct?)".to_owned(), - )); - } - - let orig_proof_info = tx_vec[0].clone().payment_proof; + let orig_proof_info = tx_vec + .into_iter() + .find(|tx| tx.tx_type == TxLogEntryType::TxSent) + .ok_or_else(|| { + Error::PaymentProof( + "TxLogEntry with original proof info not found (is account correct?)".to_owned(), + ) + })? + .payment_proof; if orig_proof_info.is_some() && slate.payment_proof.is_none() { return Err(Error::PaymentProof( @@ -566,7 +567,7 @@ where } let msg = payment_proof_message( slate.amount, - &slate.calc_excess(&keychain.secp())?, + &slate.calc_excess(keychain.secp())?, orig_sender_address.to_ed25519()?, )?; let sig = match p.promise_signature { @@ -590,12 +591,12 @@ mod test { use super::*; use rand::rngs::mock::StepRng; - use crate::grin_core::core::{FeeFields, KernelFeatures}; - use crate::grin_core::libtx::{build, ProofBuilder}; - use crate::grin_keychain::{ + use grin_core::core::{FeeFields, KernelFeatures}; + use grin_core::libtx::{build, ProofBuilder}; + use grin_keychain::{ BlindSum, BlindingFactor, ExtKeychain, ExtKeychainPath, Keychain, SwitchCommitmentType, }; - use crate::grin_util::{secp, static_secp_instance}; + use grin_util::{secp, static_secp_instance}; #[test] // demonstrate that input.commitment == referenced output.commitment @@ -655,7 +656,7 @@ mod test { .unwrap(); keychain .secp() - .commit(0, blinding_factor.secret_key(&keychain.secp()).unwrap()) + .commit(0, blinding_factor.secret_key(keychain.secp()).unwrap()) .unwrap() }; diff --git a/libwallet/src/internal/updater.rs b/libwallet/src/internal/updater.rs index 4d63592..ec72d23 100644 --- a/libwallet/src/internal/updater.rs +++ b/libwallet/src/internal/updater.rs @@ -19,22 +19,23 @@ use std::collections::{HashMap, HashSet}; use uuid::Uuid; use crate::error::Error; -use crate::grin_core::consensus::reward; -use crate::grin_core::core::{Output, TxKernel}; -use crate::grin_core::global; -use crate::grin_core::libtx::proof::ProofBuilder; -use crate::grin_core::libtx::reward; -use crate::grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; -use crate::grin_util as util; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::pedersen; -use crate::grin_util::static_secp_instance; use crate::internal::keys; use crate::types::{NodeClient, OutputData, OutputStatus, TxLogEntry, TxLogEntryType, WalletInfo}; +use crate::AcctPathMapping; use crate::{ BlockFees, CbData, OutputCommitMapping, RetrieveTxQueryArgs, RetrieveTxQuerySortField, RetrieveTxQuerySortOrder, WalletBackend, }; +use grin_core::consensus::reward; +use grin_core::core::{Output, TxKernel}; +use grin_core::global; +use grin_core::libtx::proof::ProofBuilder; +use grin_core::libtx::reward; +use grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; +use grin_util as util; +use grin_util::secp::key::SecretKey; +use grin_util::secp::pedersen; +use grin_util::static_secp_instance; use num_bigint::BigInt; @@ -264,7 +265,7 @@ where } }) .filter(|tx_entry| { - if let Some(v) = query_args.min_confirmed_timestamp { + if let Some(v) = query_args.max_creation_timestamp { tx_entry.creation_ts <= v } else { true @@ -336,11 +337,8 @@ where return_txs.sort_by_key(|tx| tx.id); } - if let Some(ref s) = query_args.sort_order { - match s { - RetrieveTxQuerySortOrder::Desc => return_txs.reverse(), - _ => {} - } + if let Some(RetrieveTxQuerySortOrder::Desc) = query_args.sort_order { + return_txs.reverse(); } // Apply limit if requested @@ -368,8 +366,8 @@ where let mut txs; // Adding in new transaction list query logic. If `tx_id` or `tx_slate_id` // is provided, then `query_args` is ignored and old logic is followed. - if query_args.is_some() && tx_id.is_none() && tx_slate_id.is_none() { - txs = apply_advanced_tx_list_filtering(wallet, parent_key_id, &query_args.unwrap())? + if let Some(query_args) = query_args.filter(|_| tx_id.is_none() && tx_slate_id.is_none()) { + txs = apply_advanced_tx_list_filtering(wallet, parent_key_id, &query_args)? } else { let mut bad_records = 0; txs = wallet @@ -442,6 +440,7 @@ where /// transactions for the account and outputs without a transaction log entry. /// Returns mapping of output commit to tuple of derived key for output, /// PMMR index, tx entry log identifier and check if output is unspent +#[allow(clippy::type_complexity)] pub fn map_wallet_outputs( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -459,7 +458,7 @@ where .filter(|x| x.root_key_id == *parent_key_id && x.status != OutputStatus::Spent) .collect(); - let tx_entries = retrieve_txs(wallet, None, None, None, Some(&parent_key_id), true)?; + let tx_entries = retrieve_txs(wallet, None, None, None, Some(parent_key_id), true)?; // Only select outputs that are actually involved in an outstanding transaction let unspents = match update_all { @@ -533,6 +532,7 @@ where } /// Apply refreshed API output data to the wallet +#[allow(clippy::type_complexity)] fn apply_api_outputs( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -564,7 +564,7 @@ where let mut batch = wallet.batch(keychain_mask)?; for (commit, (id, mmr_index, _, _)) in wallet_outputs.iter() { if let Ok(mut output) = batch.get(id, mmr_index) { - match api_outputs.get(&commit) { + match api_outputs.get(commit) { Some(o) => { // if this is a coinbase tx being confirmed, it's recordable in tx log if output.is_coinbase && output.status == OutputStatus::Unconfirmed { @@ -589,7 +589,7 @@ where } t.update_confirmation_ts(); output.tx_log_entry = Some(log_id); - batch.save_tx_log_entry(t, &parent_key_id)?; + batch.save_tx_log_entry(t, parent_key_id)?; } // also mark the transaction in which this output is involved as confirmed // note that one involved input/output confirmation SHOULD be enough @@ -598,14 +598,10 @@ where && (output.status == OutputStatus::Unconfirmed || output.status == OutputStatus::Reverted) { - let tx = batch - .tx_log_iter()? - .filter(|t| t.is_ok()) - .map(|t| t.unwrap()) - .find(|t| { - Some(t.id) == output.tx_log_entry - && t.parent_key_id == *parent_key_id - }); + let tx = batch.tx_log_iter()?.flatten().find(|t| { + Some(t.id) == output.tx_log_entry + && t.parent_key_id == *parent_key_id + }); if let Some(mut t) = tx { if t.tx_type == TxLogEntryType::TxReverted { t.tx_type = TxLogEntryType::TxReceived; @@ -613,7 +609,7 @@ where } t.update_confirmation_ts(); t.confirmed = true; - batch.save_tx_log_entry(t, &parent_key_id)?; + batch.save_tx_log_entry(t, parent_key_id)?; } else { if let Some(tx_id) = output.tx_log_entry { error!("apply_api_outputs: tx with id {:?} not found", tx_id); @@ -654,7 +650,7 @@ where { if reverted_kernels.contains(&tx.id) && tx.parent_key_id == *parent_key_id { tx.tx_type = TxLogEntryType::TxReverted; - tx.reverted_after = tx.confirmation_ts.clone().and_then(|t| { + tx.reverted_after = tx.confirmation_ts.and_then(|t| { let now = chrono::Utc::now(); (now - t).to_std().ok() }); @@ -671,7 +667,7 @@ where } for tx in txs_to_save { - batch.save_tx_log_entry(tx, &parent_key_id)?; + batch.save_tx_log_entry(tx, parent_key_id)?; } { @@ -725,6 +721,7 @@ where Ok(()) } +#[allow(clippy::type_complexity)] fn find_reverted_kernels( wallet: &mut WalletBackend, wallet_outputs: &HashMap, Option, bool)>, @@ -816,22 +813,12 @@ where Ok(()) } -/// Retrieve summary info about the wallet -/// caller should refresh first if desired -pub fn retrieve_info( - wallet: &mut WalletBackend, - parent_key_id: &Identifier, +/// Return summary info about the wallet account from provided outputs. +fn account_outputs_info>( + outputs: impl IntoIterator, + current_height: u64, minimum_confirmations: u64, -) -> Result -where - C: NodeClient, - K: Keychain, -{ - let current_height = wallet.last_confirmed_height_for_parent(parent_key_id)?; - let outputs = wallet - .iter()? - .filter(|out| out.root_key_id == *parent_key_id); - +) -> Result { let mut unspent_total = 0; let mut immature_total = 0; let mut awaiting_finalization_total = 0; @@ -840,6 +827,7 @@ where let mut reverted_total = 0; for out in outputs { + let out = out.borrow(); match out.status { OutputStatus::Unspent => { if out.is_coinbase && out.lock_height > current_height { @@ -882,6 +870,46 @@ where }) } +/// Retrieve summary info about the wallet accounts +/// caller should refresh first if desired +pub fn retrieve_accounts_info( + wallet: &mut WalletBackend, + minimum_confirmations: u64, +) -> Result, Error> +where + C: NodeClient, + K: Keychain, +{ + let outputs: Vec = wallet.iter()?.collect(); + let mut accounts = keys::accounts(wallet)?; + for a in accounts.iter_mut() { + let os = outputs.iter().filter(|out| out.root_key_id == a.path); + let current_height = wallet.last_confirmed_height_for_parent(&a.path)?; + let info = account_outputs_info(os, current_height, minimum_confirmations)?; + a.info = Some(info); + } + Ok(accounts) +} + +/// Retrieve summary info about the wallet +/// caller should refresh first if desired +pub fn retrieve_info( + wallet: &mut WalletBackend, + parent_key_id: &Identifier, + minimum_confirmations: u64, +) -> Result +where + C: NodeClient, + K: Keychain, +{ + let outputs = wallet + .iter()? + .filter(|out| out.root_key_id == *parent_key_id); + let current_height = wallet.last_confirmed_height_for_parent(parent_key_id)?; + let info = account_outputs_info(outputs, current_height, minimum_confirmations)?; + Ok(info) +} + /// Build a coinbase output and insert into wallet pub fn build_coinbase( wallet: &mut WalletBackend, diff --git a/libwallet/src/lib.rs b/libwallet/src/lib.rs index 5505413..d0c05d8 100644 --- a/libwallet/src/lib.rs +++ b/libwallet/src/lib.rs @@ -24,10 +24,6 @@ use grin_wallet_config as config; -use grin_core; -use grin_keychain; -use grin_util; - use grin_wallet_util as util; use blake2_rfc as blake2; @@ -69,8 +65,7 @@ pub use crate::slate_versions::{ GRIN_BLOCK_HEADER_VERSION, }; pub use crate::slatepack::{ - Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, SlatepackMode, Slatepacker, - SlatepackerArgs, + Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, SlatepackMode, }; pub use api_impl::owner_updater::StatusMessage; pub use api_impl::types::{ @@ -90,6 +85,10 @@ pub use types::{ ViewWallet, WalletInfo, WalletInitStatus, WalletInst, WalletLCProvider, }; +/// Shared wallet handle for APIs and workers +pub type WalletHandle<'a, L, C, K> = + std::sync::Arc>>>; + /// Helper for taking a lock on the wallet instance #[macro_export] macro_rules! wallet_lock { diff --git a/libwallet/src/mwixnet/mod.rs b/libwallet/src/mwixnet/mod.rs index ebc5a9c..bb97287 100644 --- a/libwallet/src/mwixnet/mod.rs +++ b/libwallet/src/mwixnet/mod.rs @@ -14,11 +14,16 @@ //! Onion modules for mxmixnet pub mod onion; +mod response; mod types; pub use onion::{ create_onion, onion::Onion, onion::OnionError, util as onion_util, ComSigError, ComSignature, - MwixnetPublicKey, + MAX_MWIXNET_HOPS, }; -pub use types::{Hop, MixnetReqCreationParams, SwapReq}; +pub use response::{parse_mwixnet_response, MwixnetResponse, MwixnetResponseError}; + +pub use types::{ + Hop, MixnetReqCreationParams, MwixnetReqCreationResult, MwixnetServerPublicKey, SwapReq, +}; diff --git a/libwallet/src/mwixnet/onion/crypto/comsig.rs b/libwallet/src/mwixnet/onion/crypto/comsig.rs index 89eb8f8..0df427e 100644 --- a/libwallet/src/mwixnet/onion/crypto/comsig.rs +++ b/libwallet/src/mwixnet/onion/crypto/comsig.rs @@ -63,7 +63,7 @@ impl ComSignature { pub fn sign( amount: u64, blind: &SecretKey, - msg: &Vec, + msg: &[u8], use_test_rng: bool, ) -> Result { let secp = Secp256k1::with_caps(ContextFlag::Commit); @@ -87,13 +87,8 @@ impl ComSignature { let commitment = secp.commit(amount, blind.clone())?; let nonce_commitment = secp.commit_blind(k_1.clone(), k_2.clone())?; - let e = ComSignature::calc_challenge( - &secp, - &commitment, - &nonce_commitment, - &msg, - use_test_rng, - )?; + let e = + ComSignature::calc_challenge(&secp, &commitment, &nonce_commitment, msg, use_test_rng)?; // s = k_1 + (e * amount) let mut s = k_amt.clone(); @@ -109,16 +104,16 @@ impl ComSignature { } /// Verify the commitment signature - pub fn verify(&self, commit: &Commitment, msg: &Vec) -> Result<(), ComSigError> { + pub fn verify(&self, commit: &Commitment, msg: &[u8]) -> Result<(), ComSigError> { let secp = Secp256k1::with_caps(ContextFlag::Commit); let s1 = secp.commit_blind(self.s.clone(), self.t.clone())?; let mut ce = commit.to_pubkey(&secp)?; - let e = ComSignature::calc_challenge(&secp, &commit, &self.pub_nonce, &msg, false)?; + let e = ComSignature::calc_challenge(&secp, commit, &self.pub_nonce, msg, false)?; ce.mul_assign(&secp, &e)?; - let commits = vec![Commitment::from_pubkey(&secp, &ce)?, self.pub_nonce.clone()]; + let commits = vec![Commitment::from_pubkey(&secp, &ce)?, self.pub_nonce]; let s2 = secp.commit_sum(commits, Vec::new())?; if s1 != s2 { @@ -132,7 +127,7 @@ impl ComSignature { secp: &Secp256k1, commit: &Commitment, nonce_commit: &Commitment, - msg: &Vec, + msg: &[u8], use_test_rng: bool, ) -> Result { let mut challenge_hasher = Blake2b::new(32); @@ -146,7 +141,7 @@ impl ComSignature { let mut challenge = [0; 32]; challenge.copy_from_slice(challenge_hasher.finalize().as_bytes()); - Ok(SecretKey::from_slice(&secp, &challenge)?) + Ok(SecretKey::from_slice(secp, &challenge)?) } } @@ -213,16 +208,16 @@ mod tests { let amount = thread_rng().next_u64(); let blind = SecretKey::new(&secp, &mut thread_rng()); 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 comsig = ComSignature::sign(amount, &blind, msg.as_ref(), false)?; let commit = secp.commit(amount, blind.clone())?; - assert!(comsig.verify(&commit, &msg.to_vec()).is_ok()); + assert!(comsig.verify(&commit, msg.as_ref()).is_ok()); 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()); + assert!(comsig.verify(&commit, wrong_msg.as_ref()).is_err()); let wrong_commit = secp.commit(amount, SecretKey::new(&secp, &mut thread_rng()))?; - assert!(comsig.verify(&wrong_commit, &msg.to_vec()).is_err()); + assert!(comsig.verify(&wrong_commit, msg.as_ref()).is_err()); Ok(()) } diff --git a/libwallet/src/mwixnet/onion/crypto/dalek.rs b/libwallet/src/mwixnet/onion/crypto/dalek.rs index adbebd7..66c5f69 100644 --- a/libwallet/src/mwixnet/onion/crypto/dalek.rs +++ b/libwallet/src/mwixnet/onion/crypto/dalek.rs @@ -36,48 +36,51 @@ pub enum DalekError { SigVerifyFailed, } -/// Encapsulates an ed25519_dalek::PublicKey and provides (de-)serialization +/// Ed25519 server identity key #[derive(Clone, Debug, PartialEq)] -pub struct DalekPublicKey(VerifyingKey); +pub struct MwixnetServerIdentityKey(VerifyingKey); -impl DalekPublicKey { - /// Convert DalekPublicKey to hex string +impl MwixnetServerIdentityKey { + /// Convert the identity key to hex pub fn to_hex(&self) -> String { self.0.to_hex() } - /// Convert hex string to DalekPublicKey. + /// Parse an identity key from hex pub fn from_hex(hex: &str) -> Result { 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)) + Ok(MwixnetServerIdentityKey(pk)) } - /// Compute DalekPublicKey from a SecretKey + /// Derive the identity key from a secret key pub fn from_secret(key: &SecretKey) -> Self { let secret = ed25519_dalek::SigningKey::from_bytes(&key.0); let pk: VerifyingKey = (&secret).into(); - DalekPublicKey(pk) + MwixnetServerIdentityKey(pk) } } -impl AsRef for DalekPublicKey { +impl AsRef for MwixnetServerIdentityKey { fn as_ref(&self) -> &VerifyingKey { &self.0 } } -/// Serializes an Option to and from hex +/// Serialize an optional identity key as hex pub mod option_dalek_pubkey_serde { - use super::DalekPublicKey; + use super::MwixnetServerIdentityKey; use grin_util::ToHex; use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; - /// - pub fn serialize(pk: &Option, serializer: S) -> Result + /// Write the Ed25519 public key as hex, or null + pub fn serialize( + pk: &Option, + serializer: S, + ) -> Result where S: Serializer, { @@ -87,30 +90,32 @@ pub mod option_dalek_pubkey_serde { } } - /// - pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + /// Read an optional Ed25519 public key from hex + pub fn deserialize<'de, D>( + deserializer: D, + ) -> Result, D::Error> where D: Deserializer<'de>, { Option::::deserialize(deserializer).and_then(|res| match res { - Some(string) => DalekPublicKey::from_hex(&string) + Some(string) => MwixnetServerIdentityKey::from_hex(&string) .map_err(|e| Error::custom(e.to_string())) - .and_then(|pk: DalekPublicKey| Ok(Some(pk))), + .map(|pk: MwixnetServerIdentityKey| Some(pk)), None => Ok(None), }) } } -impl Readable for DalekPublicKey { +impl Readable for MwixnetServerIdentityKey { fn read(reader: &mut R) -> Result { 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)) + Ok(MwixnetServerIdentityKey(pk)) } } -impl Writeable for DalekPublicKey { +impl Writeable for MwixnetServerIdentityKey { fn write(&self, writer: &mut W) -> Result<(), ser::Error> { writer.write_fixed_bytes(self.0.to_bytes())?; Ok(()) @@ -130,16 +135,15 @@ impl DalekSignature { .map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?; 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)))?; + let sig = ed25519_dalek::Signature::from(b); Ok(DalekSignature(sig)) } /// Verifies DalekSignature #[allow(dead_code)] - pub fn verify(&self, pk: &DalekPublicKey, msg: &[u8]) -> Result<(), DalekError> { + pub fn verify(&self, pk: &MwixnetServerIdentityKey, msg: &[u8]) -> Result<(), DalekError> { pk.as_ref() - .verify(&msg, &self.0) + .verify(msg, &self.0) .map_err(|_| DalekError::SigVerifyFailed) } } @@ -157,7 +161,7 @@ pub mod dalek_sig_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 signature as hex pub fn serialize(sig: &DalekSignature, serializer: S) -> Result where S: Serializer, @@ -165,7 +169,7 @@ pub mod dalek_sig_serde { serializer.serialize_str(&sig.0.to_bytes().to_hex()) } - /// + /// Read an Ed25519 signature from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -180,7 +184,7 @@ pub mod dalek_sig_serde { pub fn sign(sk: &SecretKey, message: &[u8]) -> Result { use ed25519_dalek::{Signer, SigningKey}; let secret = SigningKey::from_bytes(&sk.0); - let sig = secret.sign(&message); + let sig = secret.sign(message); Ok(DalekSignature(sig)) } @@ -197,20 +201,21 @@ mod tests { #[derive(Serialize, Deserialize, PartialEq, Clone, Debug)] struct TestPubKeySerde { #[serde(with = "option_dalek_pubkey_serde", default)] - pk: Option, + pk: Option, } #[test] fn pubkey_test() -> Result<(), Box> { // Test from_hex let rand_pk = rand_keypair().1; - let pk_from_hex = DalekPublicKey::from_hex(rand_pk.0.to_hex().as_str()).unwrap(); + let pk_from_hex = MwixnetServerIdentityKey::from_hex(rand_pk.0.to_hex().as_str()).unwrap(); assert_eq!(rand_pk.0, pk_from_hex.0); // Test ser (de-)serialization let bytes = ser::ser_vec(&rand_pk, ProtocolVersion::local()).unwrap(); assert_eq!(bytes.len(), 32); - let pk_from_deser: DalekPublicKey = ser::deserialize_default(&mut &bytes[..]).unwrap(); + let pk_from_deser: MwixnetServerIdentityKey = + ser::deserialize_default(&mut &bytes[..]).unwrap(); assert_eq!(rand_pk.0, pk_from_deser.0); // Test serde with Some(rand_pk) @@ -261,7 +266,7 @@ mod tests { // Sign a message let s = Secp256k1::new(); let sk = SecretKey::from_slice(&s, &[1; 32]).unwrap(); - let pk = DalekPublicKey::from_secret(&sk); + let pk = MwixnetServerIdentityKey::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(); @@ -275,7 +280,7 @@ mod tests { // Wrong pubkey let wrong_sk = SecretKey::from_slice(&s, &[2; 32]).unwrap(); - let wrong_pk = DalekPublicKey::from_secret(&wrong_sk); + let wrong_pk = MwixnetServerIdentityKey::from_secret(&wrong_sk); assert!(sig.verify(&wrong_pk, &msg).is_err()); // Test from_hex diff --git a/libwallet/src/mwixnet/onion/crypto/secp.rs b/libwallet/src/mwixnet/onion/crypto/secp.rs index 200c24f..19548d8 100644 --- a/libwallet/src/mwixnet/onion/crypto/secp.rs +++ b/libwallet/src/mwixnet/onion/crypto/secp.rs @@ -61,7 +61,7 @@ pub fn add_excess( let secp = Secp256k1::with_caps(ContextFlag::Commit); let excess_commit: Commitment = secp.commit(0, excess.clone())?; - let commits = vec![commitment.clone(), excess_commit.clone()]; + let commits = vec![*commitment, excess_commit]; let sum = secp.commit_sum(commits, Vec::new())?; Ok(sum) } @@ -70,7 +70,7 @@ pub fn add_excess( pub fn sub_value(commitment: &Commitment, value: u64) -> Result { let secp = Secp256k1::with_caps(ContextFlag::Commit); let neg_commit: Commitment = secp.commit(value, ZERO_KEY)?; - let sum = secp.commit_sum(vec![commitment.clone()], vec![neg_commit.clone()])?; + let sum = secp.commit_sum(vec![*commitment], vec![neg_commit])?; Ok(sum) } @@ -81,11 +81,11 @@ pub fn sign( msg: &grin_util::secp::Message, ) -> Result { let secp = Secp256k1::with_caps(ContextFlag::Full); - let pubkey = grin_util::secp::PublicKey::from_secret_key(&secp, &sk)?; + let pubkey = grin_util::secp::PublicKey::from_secret_key(&secp, sk)?; let sig = grin_util::secp::aggsig::sign_single( &secp, - &msg, - &sk, + msg, + sk, None, None, None, diff --git a/libwallet/src/mwixnet/onion/mod.rs b/libwallet/src/mwixnet/onion/mod.rs index e1eb424..c56e69e 100644 --- a/libwallet/src/mwixnet/onion/mod.rs +++ b/libwallet/src/mwixnet/onion/mod.rs @@ -15,12 +15,11 @@ //! Onion module definition pub mod crypto; +#[allow(clippy::module_inception)] pub mod onion; pub mod util; -pub use crypto::{ - comsig_serde, dalek::DalekPublicKey as MwixnetPublicKey, ComSigError, ComSignature, -}; +pub use crypto::{comsig_serde, ComSigError, ComSignature}; use chacha20::cipher::StreamCipher; use grin_core::core::FeeFields; @@ -31,14 +30,18 @@ use grin_util::secp::{ use x25519_dalek::PublicKey as xPublicKey; use x25519_dalek::{SharedSecret, StaticSecret}; +use crate::mwixnet::MwixnetServerPublicKey; use crypto::secp::random_secret; use onion::{new_stream_cipher, Onion, OnionError, Payload, RawBytes}; +/// Maximum route length, including the swap server. +pub const MAX_MWIXNET_HOPS: usize = 8; + /// Onion hop struct #[derive(Clone)] pub struct Hop { /// Comsig server public key - pub server_pubkey: xPublicKey, + pub server_pubkey: MwixnetServerPublicKey, /// Kernel excess pub excess: SecretKey, /// Fee @@ -56,9 +59,9 @@ pub fn new_hop( proof: Option, ) -> Hop { Hop { - server_pubkey: xPublicKey::from(&StaticSecret::from(server_key.0.clone())), + server_pubkey: MwixnetServerPublicKey::from_secret(server_key), excess: hop_excess.clone(), - fee: FeeFields::from(fee as u32), + fee: FeeFields::from(fee), rangeproof: proof, } } @@ -66,13 +69,18 @@ pub fn new_hop( /// Create an Onion for the Commitment, encrypting the payload for each hop pub fn create_onion( commitment: &Commitment, - hops: &Vec, + hops: &[Hop], use_test_rng: bool, ) -> Result { + if hops.len() > MAX_MWIXNET_HOPS { + return Err(OnionError::TooManyHops { + max: MAX_MWIXNET_HOPS, + }); + } if hops.is_empty() { return Ok(Onion { ephemeral_pubkey: xPublicKey::from([0u8; 32]), - commit: commitment.clone(), + commit: *commitment, enc_payloads: vec![], }); } @@ -83,7 +91,10 @@ pub fn create_onion( let onion_ephemeral_pk = xPublicKey::from(&ephemeral_sk); for i in 0..hops.len() { let hop = &hops[i]; - let shared_secret = ephemeral_sk.diffie_hellman(&hop.server_pubkey); + let shared_secret = ephemeral_sk.diffie_hellman(&xPublicKey::from(hop.server_pubkey.0)); + if !shared_secret.was_contributory() { + return Err(OnionError::NonContributorySharedSecret); + } shared_secrets.push(shared_secret); ephemeral_sk = StaticSecret::from(random_secret(use_test_rng).0); @@ -96,22 +107,22 @@ pub fn create_onion( let payload = Payload { next_ephemeral_pk, excess: hop.excess.clone(), - fee: hop.fee.clone(), - rangeproof: hop.rangeproof.clone(), + fee: hop.fee, + rangeproof: hop.rangeproof, }; enc_payloads.push(payload.serialize()?); } for i in (0..shared_secrets.len()).rev() { let mut cipher = new_stream_cipher(&shared_secrets[i])?; - for j in i..shared_secrets.len() { - cipher.apply_keystream(&mut enc_payloads[j]); + for payload in enc_payloads.iter_mut().skip(i) { + cipher.apply_keystream(payload); } } let onion = Onion { ephemeral_pubkey: onion_ephemeral_pk, - commit: commitment.clone(), + commit: *commitment, enc_payloads, }; Ok(onion) @@ -122,7 +133,7 @@ pub fn create_onion( #[cfg(any(test, feature = "mwixnet-test"))] pub mod test_util { use super::*; - use crypto::dalek::DalekPublicKey; + use crypto::dalek::MwixnetServerIdentityKey; use crypto::secp; use grin_core::core::hash::Hash; @@ -153,23 +164,24 @@ pub mod test_util { } pub fn rand_commit() -> Commitment { - secp::commit(rand::thread_rng().next_u64(), &secp::random_secret(false)).unwrap() + secp::commit(thread_rng().next_u64(), &random_secret(false)).unwrap() } pub fn rand_hash() -> Hash { - Hash::from_hex(secp::random_secret(false).to_hex().as_str()).unwrap() + Hash::from_hex(random_secret(false).to_hex().as_str()).unwrap() } pub fn rand_proof() -> RangeProof { let secp = Secp256k1::new(); secp.bullet_proof( - rand::thread_rng().next_u64(), - secp::random_secret(false), - secp::random_secret(false), - secp::random_secret(false), + thread_rng().next_u64(), + random_secret(false), + random_secret(false), + random_secret(false), None, None, ) + .expect("failed to generate test bulletproof") } pub fn proof( @@ -182,26 +194,111 @@ pub mod test_util { let mut blind = input_blind.clone(); for hop_excess in hop_excesses { - blind.add_assign(&secp, &hop_excess).unwrap(); + blind.add_assign(&secp, hop_excess).unwrap(); } let out_value = value - (fee as u64); - let rp = secp.bullet_proof( - out_value, - blind.clone(), - secp::random_secret(false), - secp::random_secret(false), - None, - None, - ); + let rp = secp + .bullet_proof( + out_value, + blind.clone(), + random_secret(false), + random_secret(false), + None, + None, + ) + .expect("failed to generate test bulletproof"); (secp::commit(out_value, &blind).unwrap(), rp) } - pub fn rand_keypair() -> (SecretKey, DalekPublicKey) { + pub fn rand_keypair() -> (SecretKey, MwixnetServerIdentityKey) { let sk = random_secret(false); - let pk = DalekPublicKey::from_secret(&sk); + let pk = MwixnetServerIdentityKey::from_secret(&sk); (sk, pk) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::mwixnet::MwixnetServerPublicKey; + + #[test] + fn rejects_zero_key() { + let commitment = test_util::rand_commit(); + let hop = Hop { + server_pubkey: MwixnetServerPublicKey([0u8; 32]), + excess: random_secret(false), + fee: FeeFields::from(1u32), + rangeproof: None, + }; + + assert_eq!( + create_onion(&commitment, &[hop], false), + Err(OnionError::NonContributorySharedSecret) + ); + } + + #[test] + fn rejects_too_many_hops() { + let commitment = test_util::rand_commit(); + let hops: Vec = (0..=MAX_MWIXNET_HOPS) + .map(|_| new_hop(&random_secret(false), &random_secret(false), 1, None)) + .collect(); + + assert!(create_onion(&commitment, &hops[..MAX_MWIXNET_HOPS], false).is_ok()); + + assert_eq!( + create_onion(&commitment, &hops, false), + Err(OnionError::TooManyHops { + max: MAX_MWIXNET_HOPS + }) + ); + } + + #[test] + fn x25519_key_roundtrip() { + let server_key = SecretKey::from_slice( + &grin_util::secp::Secp256k1::new(), + &grin_util::from_hex( + "a129111d283b13bf93957c06bf6605c3417b4b89db4b5cb2e7dab2c15e36e0a4", + ) + .unwrap(), + ) + .unwrap(); + let public_key = MwixnetServerPublicKey::from_secret(&server_key); + assert_eq!( + public_key.to_hex(), + "96ced236bdf1aca722ef68b818445755e6ed4bacf23e19d7b71c43efc5f0077b" + ); + let identity_key = + crypto::dalek::MwixnetServerIdentityKey::from_secret(&server_key).to_hex(); + assert_ne!(identity_key, public_key.to_hex()); + + let commitment = crypto::secp::commit(1_000, &server_key).unwrap(); + let excess = server_key.clone(); + let hop = Hop { + server_pubkey: public_key, + excess: excess.clone(), + fee: FeeFields::from(1u32), + rangeproof: None, + }; + let onion = create_onion(&commitment, &[hop], true).unwrap(); + let peeled = onion.peel_layer(&server_key).unwrap(); + + assert_eq!(peeled.payload.excess, excess); + assert_eq!(peeled.payload.fee, FeeFields::from(1u32)); + + let identity_key = MwixnetServerPublicKey::from_hex(&identity_key).unwrap(); + let wrong_hop = Hop { + server_pubkey: identity_key, + excess: server_key.clone(), + fee: FeeFields::from(1u32), + rangeproof: None, + }; + let wrong_onion = create_onion(&commitment, &[wrong_hop], true).unwrap(); + assert!(wrong_onion.peel_layer(&server_key).is_err()); + } +} diff --git a/libwallet/src/mwixnet/onion/onion.rs b/libwallet/src/mwixnet/onion/onion.rs index 2540dae..e105f4c 100644 --- a/libwallet/src/mwixnet/onion/onion.rs +++ b/libwallet/src/mwixnet/onion/onion.rs @@ -94,7 +94,7 @@ pub struct Payload { impl Payload { /// Deserialize - pub fn deserialize(bytes: &Vec) -> Result { + pub fn deserialize(bytes: &[u8]) -> Result { let payload: Payload = ser::deserialize_default(&mut &bytes[..])?; Ok(payload) } @@ -131,7 +131,7 @@ impl Readable for Payload { impl Writeable for Payload { fn write(&self, writer: &mut W) -> Result<(), ser::Error> { writer.write_u8(CURRENT_ONION_VERSION)?; - writer.write_fixed_bytes(&self.next_ephemeral_pk.as_bytes())?; + writer.write_fixed_bytes(self.next_ephemeral_pk.as_bytes())?; writer.write_fixed_bytes(&self.excess)?; writer.write_u64(self.fee.into())?; write_optional(writer, &self.rangeproof)?; @@ -163,8 +163,8 @@ impl Onion { let mut decrypted_bytes = self.enc_payloads[0].clone(); cipher.apply_keystream(&mut decrypted_bytes); - let decrypted_payload = Payload::deserialize(&decrypted_bytes) - .map_err(|e| OnionError::DeserializationError(e))?; + let decrypted_payload = + Payload::deserialize(&decrypted_bytes).map_err(OnionError::DeserializationError)?; let enc_payloads: Vec = self .enc_payloads @@ -178,15 +178,15 @@ impl Onion { }) .collect(); - let mut commitment = self.commit.clone(); + let mut commitment = self.commit; commitment = secp::add_excess(&commitment, &decrypted_payload.excess) - .map_err(|e| OnionError::CalcCommitError(e))?; + .map_err(OnionError::CalcCommitError)?; commitment = secp::sub_value(&commitment, decrypted_payload.fee.into()) - .map_err(|e| OnionError::CalcCommitError(e))?; + .map_err(OnionError::CalcCommitError)?; let peeled_onion = Onion { ephemeral_pubkey: decrypted_payload.next_ephemeral_pk, - commit: commitment.clone(), + commit: commitment, enc_payloads, }; Ok(PeeledOnion { @@ -205,13 +205,13 @@ pub fn new_stream_cipher(shared_secret: &SharedSecret) -> Result(&self, writer: &mut W) -> Result<(), ser::Error> { writer.write_fixed_bytes(self.ephemeral_pubkey.as_bytes())?; - writer.write_fixed_bytes(&self.commit)?; + writer.write_fixed_bytes(self.commit)?; writer.write_u64(self.enc_payloads.len() as u64)?; for p in &self.enc_payloads { writer.write_u64(p.len() as u64)?; @@ -326,7 +326,7 @@ impl<'de> serde::de::Deserialize<'de> for Onion { } const FIELDS: &[&str] = &["pubkey", "commit", "data"]; - deserializer.deserialize_struct("Onion", &FIELDS, OnionVisitor) + deserializer.deserialize_struct("Onion", FIELDS, OnionVisitor) } } @@ -336,6 +336,15 @@ pub enum OnionError { /// Invalid Key Length #[error("Invalid key length for MAC initialization")] InvalidKeyLength, + /// Non-contributory X25519 shared secret + #[error("Non-contributory X25519 shared secret")] + NonContributorySharedSecret, + /// Too many hops + #[error("Mwixnet routes support at most {max} hops")] + TooManyHops { + /// Maximum supported number of hops + max: usize, + }, /// Serialization Error #[error("Serialization error occurred: {0:?}")] SerializationError(ser::Error), @@ -366,7 +375,7 @@ impl From for OnionError { } #[cfg(test)] -pub mod tests { +mod tests { use super::*; use crate::mwixnet::onion::crypto::secp::random_secret; use crate::mwixnet::onion::{new_hop, Hop}; @@ -397,14 +406,16 @@ pub mod tests { final_commit = secp::add_excess(&final_commit, &excess).unwrap(); let proof = if i == 4 { let n1 = random_secret(false); - let rp = secp.bullet_proof( - out_value, - final_blind.clone(), - n1.clone(), - n1.clone(), - None, - None, - ); + let rp = secp + .bullet_proof( + out_value, + final_blind.clone(), + n1.clone(), + n1.clone(), + None, + None, + ) + .expect("failed to generate test bulletproof"); assert!(secp.verify_bullet_proof(final_commit, rp, None).is_ok()); Some(rp) } else { @@ -419,13 +430,13 @@ pub mod tests { crate::mwixnet::onion::create_onion(&commitment, &hops, false).unwrap(); let mut payload = Payload { - next_ephemeral_pk: onion_packet.ephemeral_pubkey.clone(), + next_ephemeral_pk: onion_packet.ephemeral_pubkey, excess: random_secret(false), fee: FeeFields::from(fee_per_hop), rangeproof: None, }; - for i in 0..5 { - let peeled = onion_packet.peel_layer(&keys[i]).unwrap(); + for key in &keys { + let peeled = onion_packet.peel_layer(key).unwrap(); payload = peeled.payload; onion_packet = peeled.onion; } diff --git a/libwallet/src/mwixnet/onion/util.rs b/libwallet/src/mwixnet/onion/util.rs index 6661177..a5df490 100644 --- a/libwallet/src/mwixnet/onion/util.rs +++ b/libwallet/src/mwixnet/onion/util.rs @@ -37,7 +37,7 @@ use std::convert::TryInto; /// # Example /// /// ``` -/// use grin_wallet_libwallet::mwixnet::onion_util::write_optional; +/// use grin_wallet_libwallet::mwixnet::onion_util::write_optional; /// let mut writer:Vec = vec![]; /// let optional_value: Option = Some(10); /// //write_optional(&mut writer, &optional_value); @@ -75,7 +75,7 @@ pub fn write_optional( /// # Example /// /// ``` -/// use grin_wallet_libwallet::mwixnet::onion_util::read_optional; +/// use grin_wallet_libwallet::mwixnet::onion_util::read_optional; /// use grin_core::ser::{BinReader, ProtocolVersion, DeserializationMode}; /// let mut buf: &[u8] = &[1, 0, 0, 0, 10]; /// let mut reader = BinReader::new(&mut buf, ProtocolVersion::local(), DeserializationMode::default()); @@ -100,18 +100,18 @@ pub fn read_optional(reader: &mut R) -> Result /// # Returns /// /// * If successful, returns an `Ok` wrapping an array of size `S` containing -/// the first `S` bytes of `vec`. +/// the first `S` bytes of `vec`. /// * If `vec` is smaller than `S`, returns an `Err` indicating a count error. /// /// # Example /// /// ``` -/// use grin_wallet_libwallet::mwixnet::onion_util::vec_to_array; +/// use grin_wallet_libwallet::mwixnet::onion_util::vec_to_array; /// let v = vec![0, 1, 2, 3, 4, 5]; /// let a = vec_to_array::<4>(&v).unwrap(); /// assert_eq!(a, [0, 1, 2, 3]); /// ``` -pub fn vec_to_array(vec: &Vec) -> Result<[u8; S], ser::Error> { +pub fn vec_to_array(vec: &[u8]) -> Result<[u8; S], ser::Error> { if vec.len() < S { return Err(ser::Error::CountError); } diff --git a/libwallet/src/mwixnet/response.rs b/libwallet/src/mwixnet/response.rs new file mode 100644 index 0000000..a2e0c8c --- /dev/null +++ b/libwallet/src/mwixnet/response.rs @@ -0,0 +1,105 @@ +// 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. + +//! Mwixnet response parsing. + +use serde::Deserialize; +use serde_json::{self, Value}; + +/// Result returned by a mwixnet server after submitting a swap request. +#[derive(Debug, Eq, PartialEq)] +pub enum MwixnetResponse { + /// The swap request was accepted. + Accepted, + /// The swap request was rejected with a message. + //TODO: extend it with actual errors from mwixnet + Rejected(String), +} + +/// Error parsing or validating a mwixnet response. +#[derive(Debug, Eq, PartialEq, thiserror::Error)] +#[error("{0}")] +pub struct MwixnetResponseError(String); + +#[derive(Deserialize)] +struct JsonRpcResponse { + result: Option, + error: Option, + id: Value, + jsonrpc: Option, +} + +#[derive(Deserialize)] +struct JsonRpcError { + #[serde(rename = "code")] + _code: i32, + message: String, +} + +/// Parse and validate the JSON-RPC response returned by a mwixnet server. +pub fn parse_mwixnet_response(response: &str) -> Result { + let response: JsonRpcResponse = serde_json::from_str(response) + .map_err(|e| MwixnetResponseError(format!("Invalid mwixnet response: {}", e)))?; + + if response.jsonrpc.as_deref() != Some("2.0") { + return Err(MwixnetResponseError( + "Invalid mwixnet response version".to_string(), + )); + } + if response.id != serde_json::json!(1) { + return Err(MwixnetResponseError( + "Invalid mwixnet response ID".to_string(), + )); + } + if response.result.is_some() && response.error.is_some() { + return Err(MwixnetResponseError( + "Mwixnet response contains both result and error".to_string(), + )); + } + if let Some(error) = response.error { + return Ok(MwixnetResponse::Rejected(error.message)); + } + if response.result == Some(serde_json::json!("success")) { + return Ok(MwixnetResponse::Accepted); + } + + Err(MwixnetResponseError(format!( + "Unexpected mwixnet response result: {:?}", + response.result + ))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_mwixnet_response() { + assert_eq!( + parse_mwixnet_response(r#"{"jsonrpc":"2.0","result":"success","id":1}"#).unwrap(), + MwixnetResponse::Accepted + ); + + assert_eq!( + parse_mwixnet_response( + r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"invalid swap"},"id":1}"#, + ) + .unwrap(), + MwixnetResponse::Rejected("invalid swap".to_string()) + ); + + assert!(parse_mwixnet_response(r#"{"jsonrpc":"2.0","result":"success","id":2}"#).is_err()); + assert!(parse_mwixnet_response(r#"{"jsonrpc":"1.0","result":"success","id":1}"#).is_err()); + } +} diff --git a/libwallet/src/mwixnet/types.rs b/libwallet/src/mwixnet/types.rs index 1213f3a..04c253d 100644 --- a/libwallet/src/mwixnet/types.rs +++ b/libwallet/src/mwixnet/types.rs @@ -13,12 +13,15 @@ // limitations under the License. //! Types related to mwixnet requests required by rest of lib crate apis -//! Should rexport all needed types here +//! Should export all needed types here use super::onion::comsig_serde; -use grin_core::libtx::secp_ser::string_or_u64; +use grin_core::libtx::secp_ser::opt_string_or_u64; use grin_util::secp::key::SecretKey; -use serde::{Deserialize, Serialize}; +use grin_util::ToHex; +use serde::de::Error as SerdeError; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use x25519_dalek::{PublicKey, StaticSecret}; pub use super::onion::{onion::Onion, ComSignature, Hop}; @@ -32,12 +35,67 @@ pub struct SwapReq { pub onion: Onion, } -/// mwixnetRequest Creation Params +/// Result of creating a mwixnet request. +#[derive(Serialize, Deserialize, Debug)] +pub struct MwixnetReqCreationResult { + /// Request to submit to the first mwixnet server. + #[serde(flatten)] + pub request: SwapReq, + /// Transaction log ID when the wallet output was locked. + pub tx_id: Option, +} + +/// Public X25519 key of an mwixnet server. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct MwixnetServerPublicKey(pub(crate) [u8; 32]); + +impl MwixnetServerPublicKey { + /// Derive the public key published by a mwixnet server. + pub fn from_secret(key: &SecretKey) -> Self { + let key = PublicKey::from(&StaticSecret::from(key.0)); + Self(key.to_bytes()) + } + + /// Parse a public key from hexadecimal representation. + pub fn from_hex(value: &str) -> Result { + let bytes = grin_util::from_hex(value).map_err(|e| e.to_string())?; + let bytes: [u8; 32] = bytes + .try_into() + .map_err(|_| "mwixnet server public key must be 32 bytes".to_string())?; + Ok(Self(bytes)) + } + + /// Return the hexadecimal representation. + pub fn to_hex(self) -> String { + self.0.to_hex() + } +} + +impl Serialize for MwixnetServerPublicKey { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&self.to_hex()) + } +} + +impl<'de> Deserialize<'de> for MwixnetServerPublicKey { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let value = String::deserialize(deserializer)?; + Self::from_hex(&value).map_err(D::Error::custom) + } +} + +/// Mwixnet request creation params #[derive(Serialize, Deserialize, Debug)] pub struct MixnetReqCreationParams { - /// List of all the server keys - pub server_keys: Vec, - /// Fees per hop - #[serde(with = "string_or_u64")] - pub fee_per_hop: u64, + /// Ordered public keys of 1 to [`super::MAX_MWIXNET_HOPS`] participating servers + pub server_keys: Vec, + /// Optional fee per hop with the swap minimum as default + #[serde(default, with = "opt_string_or_u64")] + pub fee_per_hop: Option, } diff --git a/libwallet/src/payment_proof.rs b/libwallet/src/payment_proof.rs index 61ee61a..ed829b6 100644 --- a/libwallet/src/payment_proof.rs +++ b/libwallet/src/payment_proof.rs @@ -15,15 +15,6 @@ //! Early payment proof creation and verification. use crate::blake2::blake2b::blake2b; -use crate::grin_core::libtx::aggsig; -use crate::grin_core::libtx::secp_ser; -use crate::grin_core::ser as grin_ser; -use crate::grin_core::ser::{Writeable, Writer}; -use crate::grin_util::secp::key::{PublicKey, SecretKey}; -use crate::grin_util::secp::pedersen::Commitment; -use crate::grin_util::secp::Secp256k1; -use crate::grin_util::secp::Signature; -use crate::grin_util::static_secp_instance; use crate::slate::{PaymentMemo, PaymentProofType, Slate}; use crate::slate_versions::ser::{dalek_pubkey_serde, option_dalek_sig_serde, option_pubkey_serde}; use crate::Error; @@ -31,7 +22,16 @@ 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::libtx::aggsig; +use grin_core::libtx::secp_ser; +use grin_core::ser as grin_ser; +use grin_core::ser::{Writeable, Writer}; +use grin_util::secp::key::{PublicKey, SecretKey}; +use grin_util::secp::pedersen::Commitment; use grin_util::secp::Message; +use grin_util::secp::Secp256k1; +use grin_util::secp::Signature; +use grin_util::static_secp_instance; pub(crate) fn check_proof_type(proof_type: &PaymentProofType) -> Result<(), Error> { match proof_type { @@ -618,7 +618,7 @@ mod tests { #[test] fn proof_promise() -> Result<(), Error> { - use crate::grin_util::ToHex; + use grin_util::ToHex; let mut slate = populate_test_slate()?; slate.amount |= 0xFF00_0000_0000_0000; diff --git a/libwallet/src/slate.rs b/libwallet/src/slate.rs index 71bbe0e..d37ef37 100644 --- a/libwallet/src/slate.rs +++ b/libwallet/src/slate.rs @@ -16,27 +16,7 @@ //! around during an interactive wallet exchange use crate::error::Error; -use crate::grin_core::core::amount_to_hr_string; -use crate::grin_core::core::transaction::{ - FeeFields, Input, Inputs, KernelFeatures, NRDRelativeHeight, Output, OutputFeatures, - Transaction, TxKernel, Weighting, -}; -use crate::grin_core::libtx::{aggsig, build, proof::ProofBuild, tx_fee}; -use crate::grin_core::map_vec; -use crate::grin_keychain::{BlindSum, BlindingFactor, Keychain, SwitchCommitmentType}; -use crate::grin_util::secp::key::{PublicKey, SecretKey}; -use crate::grin_util::secp::pedersen::{Commitment, RangeProof}; -use crate::grin_util::secp::Signature; -use crate::grin_util::{secp, static_secp_instance}; use crate::payment_proof::{check_proof_type, EarlyPaymentProof}; -use chrono::prelude::{DateTime, Utc}; -use ed25519_dalek::Signature as DalekSignature; -use ed25519_dalek::VerifyingKey as DalekPublicKey; -use serde::ser::{Serialize, Serializer}; -use serde_json; -use std::fmt; -use uuid::Uuid; - use crate::slate_versions::v4::{ CommitsV4, KernelFeaturesArgsV4, OutputFeaturesV4, ParticipantDataV4, PaymentInfoV4, SlateStateV4, SlateV4, VersionCompatInfoV4, @@ -47,7 +27,27 @@ use crate::slate_versions::v5::{ }; use crate::slate_versions::VersionedSlate; use crate::slate_versions::{CURRENT_SLATE_VERSION, GRIN_BLOCK_HEADER_VERSION}; -use crate::Context; +use crate::{Context, SlateVersion, Slatepack, SlatepackAddress, VersionedBinSlate}; +use chrono::prelude::{DateTime, Utc}; +use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::amount_to_hr_string; +use grin_core::core::transaction::{ + FeeFields, Input, Inputs, KernelFeatures, NRDRelativeHeight, Output, OutputFeatures, + Transaction, TxKernel, Weighting, +}; +use grin_core::libtx::{aggsig, build, proof::ProofBuild, tx_fee}; +use grin_core::map_vec; +use grin_keychain::{BlindSum, BlindingFactor, Keychain, SwitchCommitmentType}; +use grin_util::secp::key::{PublicKey, SecretKey}; +use grin_util::secp::pedersen::Commitment; +use grin_util::secp::pedersen::RangeProof; +use grin_util::secp::Signature; +use grin_util::{secp, static_secp_instance}; +use grin_wallet_util::byte_ser; +use serde::ser::{Serialize, Serializer}; +use std::fmt; +use uuid::Uuid; /// Payment proof type from https://github.com/mimblewimble/grin-rfcs/pull/70 #[repr(u8)] @@ -231,10 +231,10 @@ pub struct Slate { /// associated outputs pub ttl_cutoff_height: u64, /// Kernel Features flag - - /// 0: plain - /// 1: coinbase (invalid) - /// 2: height_locked - /// 3: NRD + /// 0: plain + /// 1: coinbase (invalid) + /// 2: height_locked + /// 3: NRD pub kernel_features: u8, /// Offset, needed when posting of transaction is deferred pub offset: BlindingFactor, @@ -288,19 +288,13 @@ impl fmt::Display for SlateState { } } -#[derive(Debug, Clone, PartialEq, Eq)] /// Kernel features arguments definition +#[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct KernelFeaturesArgs { /// Lock height, for HeightLocked (also NRD relative lock height) pub lock_height: u64, } -impl Default for KernelFeaturesArgs { - fn default() -> KernelFeaturesArgs { - KernelFeaturesArgs { lock_height: 0 } - } -} - /// Versioning and compatibility info about this slate #[derive(Debug, Clone)] pub struct VersionCompatInfo { @@ -536,8 +530,8 @@ impl Slate { where K: Keychain, { - let pub_nonce = PublicKey::from_secret_key(keychain.secp(), &sec_nonce)?; - let pub_key = PublicKey::from_secret_key(keychain.secp(), &sec_key)?; + let pub_nonce = PublicKey::from_secret_key(keychain.secp(), sec_nonce)?; + let pub_key = PublicKey::from_secret_key(keychain.secp(), sec_key)?; self.participant_data = self .participant_data .clone() @@ -615,14 +609,14 @@ impl Slate { fee: self.fee_fields, lock_height: match &self.kernel_features_args { Some(a) => a.lock_height, - None => return Err(Error::KernelFeaturesMissing(format!("lock_height"))), + None => return Err(Error::KernelFeaturesMissing("lock_height".to_string())), }, }), 3 => Ok(KernelFeatures::NoRecentDuplicate { fee: self.fee_fields, relative_height: match &self.kernel_features_args { Some(a) => NRDRelativeHeight::new(a.lock_height)?, - None => return Err(Error::KernelFeaturesMissing(format!("lock_height"))), + None => return Err(Error::KernelFeaturesMissing("lock_height".to_string())), }, }), n => Err(Error::UnknownKernelFeatures(n)), @@ -681,8 +675,8 @@ impl Slate { Some(&self.pub_blind_sum(keychain.secp())?), &self.msg_to_sign()?, )?; - let pub_excess = PublicKey::from_secret_key(keychain.secp(), &sec_key)?; - let pub_nonce = PublicKey::from_secret_key(keychain.secp(), &sec_nonce)?; + let pub_excess = PublicKey::from_secret_key(keychain.secp(), sec_key)?; + let pub_nonce = PublicKey::from_secret_key(keychain.secp(), sec_nonce)?; // As in find_index_matching_context, iterate the entries we actually have for p in self.participant_data.iter_mut() { // find my entry @@ -711,8 +705,10 @@ impl Slate { .iter() .map(|p| &p.public_nonce) .collect(); - if pub_nonces.len() == 0 { - return Err(Error::Commit(format!("Participant nonces cannot be empty"))); + if pub_nonces.is_empty() { + return Err(Error::Commit( + "Participant nonces cannot be empty".to_string(), + )); } match PublicKey::from_combination(secp, pub_nonces) { Ok(k) => Ok(k), @@ -727,10 +723,10 @@ impl Slate { .iter() .map(|p| &p.public_blind_excess) .collect(); - if pub_blinds.len() == 0 { - return Err(Error::Commit(format!( - "Participant Blind sums cannot be empty" - ))); + if pub_blinds.is_empty() { + return Err(Error::Commit( + "Participant Blind sums cannot be empty".to_string(), + )); } match PublicKey::from_combination(secp, pub_blinds) { Ok(k) => Ok(k), @@ -742,8 +738,7 @@ impl Slate { fn part_sigs(&self) -> Vec<&Signature> { self.participant_data .iter() - .filter(|p| p.part_sig.is_some()) - .map(|p| p.part_sig.as_ref().unwrap()) + .filter_map(|p| p.part_sig.as_ref()) .collect() } @@ -773,7 +768,7 @@ impl Slate { .filter(|v| { if v.public_nonce == pub_nonce && v.public_blind_excess == pub_key - && part_sig == None + && part_sig.is_none() { part_sig = v.part_sig } @@ -784,7 +779,7 @@ impl Slate { self.participant_data.push(ParticipantData { public_blind_excess: pub_key, public_nonce: pub_nonce, - part_sig: part_sig, + part_sig, }); Ok(()) } @@ -883,7 +878,6 @@ impl Slate { /// fee (= M) /// /// Returns completed transaction ready for posting to the chain - fn finalize_signature(&mut self, secp: &secp::Secp256k1) -> Result { self.verify_part_sigs(secp)?; @@ -935,7 +929,7 @@ impl Slate { let mut kernel = final_tx.kernels()[0]; kernel.excess = final_excess; - kernel.excess_sig = final_sig.clone(); + kernel.excess_sig = *final_sig; let final_tx = final_tx.clone().replace_kernel(kernel); @@ -959,6 +953,22 @@ impl Slate { Ok(()) } } + + /// Create slatepack from this slate. + pub fn create_slatepack( + &self, + sender: Option, + recipients: Vec, + ) -> Result { + let version = SlateVersion::output_for(self)?; + let out_slate = VersionedSlate::into_version(self.clone(), version)?; + let bin_slate = VersionedBinSlate::try_from(out_slate).map_err(|_| Error::SlatepackSer)?; + let mut slatepack = Slatepack::default(); + slatepack.payload = byte_ser::to_bytes(&bin_slate).map_err(|_| Error::SlatepackSer)?; + slatepack.sender = sender; + slatepack.try_encrypt_payload(recipients)?; + Ok(slatepack) + } } impl Serialize for Slate { @@ -1264,17 +1274,16 @@ impl TryFrom<&Slate> for SlateV4 { let feat = *kernel_features; let ttl = *ttl; let off = offset.clone(); - let participant_data = map_vec!(participant_data, |data| ParticipantDataV4::from(data)); + let participant_data = map_vec!(participant_data, ParticipantDataV4::from); let ver = VersionCompatInfoV4::from(version_info); let payment_proof = payment_proof .as_ref() .map(PaymentInfoV4::try_from) .transpose()?; let sta = SlateStateV4::from(state); - let feat_args = match kernel_features_args { - Some(a) => Some(KernelFeaturesArgsV4::from(a)), - None => None, - }; + let feat_args = kernel_features_args + .as_ref() + .map(KernelFeaturesArgsV4::from); Ok(SlateV4 { num_parts, id, @@ -1419,16 +1428,10 @@ impl From for Slate { proof: payment_proof, feat_args, } = slate.clone(); - let participant_data = map_vec!(participant_data, |data| ParticipantData::from(data)); + let participant_data = map_vec!(participant_data, ParticipantData::from); let version_info = VersionCompatInfo::from(&ver); - let payment_proof = match &payment_proof { - Some(p) => Some(PaymentInfo::from(p)), - None => None, - }; - let kernel_features_args = match &feat_args { - Some(a) => Some(KernelFeaturesArgs::from(a)), - None => None, - }; + let payment_proof = payment_proof.as_ref().map(PaymentInfo::from); + let kernel_features_args = feat_args.as_ref().map(KernelFeaturesArgs::from); let state = SlateState::from(&sta); Slate { num_participants, @@ -1547,7 +1550,7 @@ impl From for OutputFeatures { fn from(of: OutputFeaturesV4) -> OutputFeatures { match of.0 { 1 => OutputFeatures::Coinbase, - 0 | _ => OutputFeatures::Plain, + _ => OutputFeatures::Plain, } } } @@ -1555,7 +1558,7 @@ impl From for OutputFeatures { #[cfg(test)] mod test { use super::*; - use crate::grin_keychain::ExtKeychain; + use grin_keychain::ExtKeychain; // A counterparty controls the participant list, so it can be shorter than // num_participants claims, or hold an entry that matches only one of our two keys. diff --git a/libwallet/src/slate_versions/common.rs b/libwallet/src/slate_versions/common.rs index 307448c..3e6d472 100644 --- a/libwallet/src/slate_versions/common.rs +++ b/libwallet/src/slate_versions/common.rs @@ -14,14 +14,14 @@ //! Wire types shared by V4 and V5 slates -use crate::grin_core::core::{Input, Output, TxKernel}; -use crate::grin_core::libtx::secp_ser; -use crate::grin_keychain::Identifier; -use crate::grin_util::secp; -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 grin_core::core::{Input, Output, TxKernel}; +use grin_core::libtx::secp_ser; +use grin_keychain::Identifier; +use grin_util::secp; +use grin_util::secp::key::PublicKey; +use grin_util::secp::pedersen::{Commitment, RangeProof}; +use grin_util::secp::Signature; /// Slate state definition #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/libwallet/src/slate_versions/mod.rs b/libwallet/src/slate_versions/mod.rs index 8d3d099..00cf084 100644 --- a/libwallet/src/slate_versions/mod.rs +++ b/libwallet/src/slate_versions/mod.rs @@ -17,7 +17,6 @@ //! Versions earlier than V3 are removed for the 4.0.0 release, but versioning code //! remains for future needs -use crate::grin_core::core::transaction::KernelFeatures; use crate::slate::Slate; use crate::slate_versions::v4::{CoinbaseV4, SlateV4}; use crate::slate_versions::v4_bin::SlateV4Bin; @@ -25,6 +24,7 @@ use crate::slate_versions::v5::{CoinbaseV5, SlateV5}; use crate::slate_versions::v5_bin::SlateV5Bin; use crate::types::CbData; use crate::Error; +use grin_core::core::transaction::KernelFeatures; use std::convert::TryFrom; mod common; @@ -186,26 +186,23 @@ impl VersionedCoinbase { /// Shared slate fixtures, used by the version conversion tests #[cfg(test)] pub mod tests { - use crate::grin_core::core::transaction::{KernelFeatures, NRDRelativeHeight, OutputFeatures}; - use crate::grin_core::core::FeeFields; - use crate::grin_util::from_hex; - use crate::grin_util::secp::key::PublicKey; - use crate::grin_util::secp::pedersen::Commitment; - use crate::grin_util::secp::Signature; use crate::slate::{ KernelFeaturesArgs, ParticipantData, PaymentInfo, PaymentMemo, PaymentProofType, }; use crate::slate_versions::v4::SlateV4; use crate::slate_versions::v5::{CommitsV5, SlateV5}; - use crate::{ - slate, Error, Slate, SlateVersion, Slatepacker, SlatepackerArgs, VersionedBinSlate, - VersionedSlate, - }; + use crate::{slate, Error, Slate, SlateVersion, VersionedBinSlate, VersionedSlate}; use chrono::{DateTime, Utc}; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; + use grin_core::core::transaction::{KernelFeatures, NRDRelativeHeight, OutputFeatures}; + use grin_core::core::FeeFields; use grin_core::global::{set_local_chain_type, ChainTypes}; use grin_keychain::{BlindingFactor, ExtKeychain, Keychain, SwitchCommitmentType}; + use grin_util::from_hex; + use grin_util::secp::key::PublicKey; + use grin_util::secp::pedersen::Commitment; + use grin_util::secp::Signature; use grin_wallet_util::byte_ser; use std::convert::TryInto; @@ -271,7 +268,7 @@ pub mod tests { skey2, None, None, - )), + )?), }; let coms = vec![ @@ -352,16 +349,9 @@ pub mod tests { fn ser_deser_current_slate() -> Result<(), Error> { let slate_internal = populate_test_slate()?; // Serialize slate into slatepack - let slatepacker_args = SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }; + let slate_packed = slate_internal.create_slatepack(None, vec![]).unwrap(); - let slate_packer = Slatepacker::new(slatepacker_args); - let slate_packed = slate_packer.create_slatepack(&slate_internal).unwrap(); - - let slate_unpacked = slate_packer.get_slate(&slate_packed).unwrap(); + let slate_unpacked = slate_packed.get_slate().unwrap(); assert_eq!(slate_internal.payment_proof, slate_unpacked.payment_proof); let version = SlateVersion::output_for(&slate_internal)?; @@ -377,28 +367,25 @@ pub mod tests { #[test] fn create_slatepack_uses_output_version() -> Result<(), Error> { set_local_chain_type(ChainTypes::Mainnet); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); // A slate carrying a payment proof needs V5 (the proof carries memo/timestamp // that V4 can't represent), and the V5 fields survive the round trip. let slate_with_proof = populate_test_slate()?; assert!(slate_with_proof.payment_proof.is_some()); - let recovered_v5 = packer.get_slate(&packer.create_slatepack(&slate_with_proof)?)?; + let recovered_v5 = slate_with_proof + .create_slatepack(None, vec![])? + .get_slate()?; assert_eq!(recovered_v5.version_info.version, 5); assert!(recovered_v5.payment_proof.unwrap().memo.is_some()); // A plain slate keeps its requested version. let mut slate_no_proof = populate_test_slate()?; slate_no_proof.payment_proof = None; - let recovered_v5 = packer.get_slate(&packer.create_slatepack(&slate_no_proof)?)?; + let recovered_v5 = slate_no_proof.create_slatepack(None, vec![])?.get_slate()?; assert_eq!(recovered_v5.version_info.version, 5); slate_no_proof.version_info.version = 4; - let recovered_v4 = packer.get_slate(&packer.create_slatepack(&slate_no_proof)?)?; + let recovered_v4 = slate_no_proof.create_slatepack(None, vec![])?.get_slate()?; assert_eq!(recovered_v4.version_info.version, 4); // A legacy send proof also fits in V4 and survives the round trip intact. @@ -406,7 +393,9 @@ pub mod tests { use_legacy_proof(&mut slate_legacy_proof); slate_legacy_proof.version_info.version = 4; let proof = slate_legacy_proof.payment_proof.clone().unwrap(); - let recovered_legacy = packer.get_slate(&packer.create_slatepack(&slate_legacy_proof)?)?; + let recovered_legacy = slate_legacy_proof + .create_slatepack(None, vec![])? + .get_slate()?; assert_eq!(recovered_legacy.version_info.version, 4); let recovered_proof = recovered_legacy.payment_proof.unwrap(); assert_eq!(recovered_proof.sender_address, proof.sender_address); @@ -420,7 +409,7 @@ pub mod tests { proof.memo = None; proof.promise_signature = None; partial_proof.version_info.version = 4; - let recovered = packer.get_slate(&packer.create_slatepack(&partial_proof)?)?; + let recovered = partial_proof.create_slatepack(None, vec![])?.get_slate()?; assert_eq!(recovered.version_info.version, 5); let proof = recovered.payment_proof.unwrap(); assert!(proof.sender_address.is_none()); @@ -609,9 +598,9 @@ pub mod tests { #[test] fn slate_states() { - use crate::grin_core::ser::{deserialize_default, serialize_default}; use crate::slate::SlateState; use crate::slate_versions::v5::SlateStateV5; + use grin_core::ser::{deserialize_default, serialize_default}; for (state, label, byte) in [ (SlateState::Unknown, "NA", 0), diff --git a/libwallet/src/slate_versions/ser.rs b/libwallet/src/slate_versions/ser.rs index 2dc8825..a4b1834 100644 --- a/libwallet/src/slate_versions/ser.rs +++ b/libwallet/src/slate_versions/ser.rs @@ -34,14 +34,14 @@ where .and_then(|string| base64::decode(&string).map_err(|err| Error::custom(err.to_string()))) } -/// Serializes an Option to and from hex +/// Optional range proof as hex pub mod option_rangeproof_hex { - use crate::grin_util::secp::pedersen::RangeProof; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::secp::pedersen::RangeProof; + use grin_util::{from_hex, ToHex}; use serde::de::{Error, IntoDeserializer}; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the range proof as hex, or null pub fn serialize(proof: &Option, serializer: S) -> Result where S: Serializer, @@ -52,7 +52,7 @@ pub mod option_rangeproof_hex { } } - /// + /// Read an optional range proof from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -66,7 +66,7 @@ pub mod option_rangeproof_hex { } } -/// Serializes an OnionV3Address to and from hex +/// Optional onion address as text pub mod option_ov3_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; @@ -74,7 +74,7 @@ pub mod option_ov3_serde { use crate::util::{OnionV3Address, OnionV3AddressError}; - /// + /// Write the onion address as text, or null pub fn serialize(addr: &Option, serializer: S) -> Result where S: Serializer, @@ -85,7 +85,7 @@ pub mod option_ov3_serde { } } - /// + /// Read an optional onion address pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -93,13 +93,13 @@ pub mod option_ov3_serde { Option::::deserialize(deserializer).and_then(|res| match res { Some(s) => OnionV3Address::try_from(s.as_str()) .map_err(|err: OnionV3AddressError| Error::custom(format!("{:?}", err))) - .and_then(|a| Ok(Some(a))), + .map(Some), None => Ok(None), }) } } -/// Serializes an OnionV3Address to and from hex +/// Onion address as text pub mod ov3_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; @@ -107,7 +107,7 @@ pub mod ov3_serde { use crate::util::{OnionV3Address, OnionV3AddressError}; - /// + /// Write the onion address as text pub fn serialize(addr: &OnionV3Address, serializer: S) -> Result where S: Serializer, @@ -115,7 +115,7 @@ pub mod ov3_serde { serializer.serialize_str(&addr.to_string()) } - /// + /// Read an onion address pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -123,18 +123,17 @@ pub mod ov3_serde { String::deserialize(deserializer).and_then(|s| { OnionV3Address::try_from(s.as_str()) .map_err(|err: OnionV3AddressError| Error::custom(format!("{:?}", err))) - .and_then(Ok) }) } } -/// Serializes an ed25519 PublicKey to and from hex +/// Ed25519 signing key as hex pub mod dalek_seckey_serde { - use crate::grin_util::{from_hex, ToHex}; use ed25519_dalek::SigningKey as DalekSecretKey; + use grin_util::{from_hex, ToHex}; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 signing key as hex pub fn serialize(key: &DalekSecretKey, serializer: S) -> Result where S: Serializer, @@ -142,7 +141,7 @@ pub mod dalek_seckey_serde { serializer.serialize_str(&key.to_bytes().to_hex()) } - /// + /// Read an Ed25519 signing key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -160,11 +159,11 @@ 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::VerifyingKey as DalekPublicKey; + use grin_util::{from_hex, ToHex}; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 public key as hex pub fn serialize(key: &DalekPublicKey, serializer: S) -> Result where S: Serializer, @@ -172,7 +171,7 @@ pub mod dalek_pubkey_serde { serializer.serialize_str(&key.to_bytes().to_hex()) } - /// + /// Read an Ed25519 public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -193,11 +192,11 @@ pub mod dalek_pubkey_serde { /// Serializes a x25519 PublicKey to and from hex pub mod dalek_xpubkey_serde { - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; use serde::{Deserialize, Deserializer, Serializer}; use x25519_dalek::PublicKey as xDalekPublicKey; - /// + /// Write the X25519 public key as hex pub fn serialize(key: &xDalekPublicKey, serializer: S) -> Result where S: Serializer, @@ -205,7 +204,7 @@ pub mod dalek_xpubkey_serde { serializer.serialize_str(&key.as_bytes().to_hex()) } - /// + /// Read an X25519 public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -230,7 +229,7 @@ pub mod dalek_pubkey_base64 { use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 public key as base64 pub fn serialize(key: &DalekPublicKey, serializer: S) -> Result where S: Serializer, @@ -238,7 +237,7 @@ pub mod dalek_pubkey_base64 { serializer.serialize_str(&base64::encode(&key.to_bytes())) } - /// + /// Read an Ed25519 public key from base64 pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -261,8 +260,8 @@ pub mod dalek_pubkey_base64 { /// Serializes an Option to and from hex pub mod option_pubkey_serde { - use crate::grin_util::secp::key::PublicKey; - use crate::grin_util::{from_hex, static_secp_instance, ToHex}; + use grin_util::secp::key::PublicKey; + use grin_util::{from_hex, static_secp_instance, ToHex}; use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; @@ -307,7 +306,7 @@ pub mod option_dalek_pubkey_base64 { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 public key as base64, or null pub fn serialize(key: &Option, serializer: S) -> Result where S: Serializer, @@ -318,7 +317,7 @@ pub mod option_dalek_pubkey_base64 { } } - /// + /// Read an optional Ed25519 public key from base64 pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -350,9 +349,9 @@ pub mod option_dalek_pubkey_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; - /// + /// Write the Ed25519 public key as hex, or null pub fn serialize(key: &Option, serializer: S) -> Result where S: Serializer, @@ -363,7 +362,7 @@ pub mod option_dalek_pubkey_serde { } } - /// + /// Read an optional Ed25519 public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -392,9 +391,9 @@ pub mod option_xdalek_pubkey_serde { use serde::{Deserialize, Deserializer, Serializer}; use x25519_dalek::PublicKey as xDalekPublicKey; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; - /// + /// Write the X25519 public key as hex, or null pub fn serialize(key: &Option, serializer: S) -> Result where S: Serializer, @@ -405,7 +404,7 @@ pub mod option_xdalek_pubkey_serde { } } - /// + /// Read an optional X25519 public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -433,9 +432,9 @@ pub mod dalek_sig_serde { use serde::{Deserialize, Deserializer, Serializer}; use std::convert::TryFrom; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; - /// + /// Write the Ed25519 signature as hex pub fn serialize(sig: &DalekSignature, serializer: S) -> Result where S: Serializer, @@ -443,7 +442,7 @@ pub mod dalek_sig_serde { serializer.serialize_str(&sig.to_bytes().as_ref().to_hex()) } - /// + /// Read an Ed25519 signature from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -453,21 +452,21 @@ pub mod dalek_sig_serde { .and_then(|bytes: Vec| { 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())) + Ok(DalekSignature::from(b)) }) } } -/// Serializes an Option to and from hex +/// Optional Ed25519 signature as hex pub mod option_dalek_sig_serde { use ed25519_dalek::Signature as DalekSignature; use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; use std::convert::TryFrom; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; - /// + /// Write the Ed25519 signature as hex, or null pub fn serialize(sig: &Option, serializer: S) -> Result where S: Serializer, @@ -478,7 +477,7 @@ pub mod option_dalek_sig_serde { } } - /// + /// Read an optional Ed25519 signature from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -489,16 +488,14 @@ pub mod option_dalek_sig_serde { .and_then(|bytes: Vec| { 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())) + Ok(Some(DalekSignature::from(b))) }), None => Ok(None), }) } } -/// Serializes an Option to and from base64 +/// Optional Ed25519 signature as base64 pub mod option_dalek_sig_base64 { use base64; use ed25519_dalek::Signature as DalekSignature; @@ -506,7 +503,7 @@ pub mod option_dalek_sig_base64 { use serde::{Deserialize, Deserializer, Serializer}; use std::convert::TryFrom; - /// + /// Write the Ed25519 signature as base64, or null pub fn serialize(sig: &Option, serializer: S) -> Result where S: Serializer, @@ -517,7 +514,7 @@ pub mod option_dalek_sig_base64 { } } - /// + /// Read an optional Ed25519 signature from base64 pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -528,9 +525,7 @@ pub mod option_dalek_sig_base64 { .and_then(|bytes: Vec| { 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())) + Ok(Some(DalekSignature::from(b))) }), None => Ok(None), }) @@ -544,7 +539,7 @@ pub mod version_info_v4 { use crate::slate_versions::v4::VersionCompatInfoV4; - /// + /// Write the version as `slate_version:block_header_version` pub fn serialize(v: &VersionCompatInfoV4, serializer: S) -> Result where S: Serializer, @@ -552,7 +547,7 @@ pub mod version_info_v4 { serializer.serialize_str(&format!("{}:{}", v.version, v.block_header_version)) } - /// + /// Read `slate_version:block_header_version` pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -644,7 +639,7 @@ pub mod slate_state_v4 { use crate::slate_versions::v4::SlateStateV4; - /// + /// Write the state as `NA`, `S1`–`S3` or `I1`–`I3` pub fn serialize(st: &SlateStateV4, serializer: S) -> Result where S: Serializer, @@ -661,7 +656,7 @@ pub mod slate_state_v4 { serializer.serialize_str(label) } - /// + /// Read a slate state label pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -690,7 +685,7 @@ pub mod uuid_base64 { use serde::{Deserialize, Deserializer, Serializer}; use uuid::Uuid; - /// + /// Write the UUID bytes as base64 pub fn serialize(id: &Uuid, serializer: S) -> Result where S: Serializer, @@ -698,7 +693,7 @@ pub mod uuid_base64 { serializer.serialize_str(&base64::encode(&id.as_bytes())) } - /// + /// Read a UUID from base64 pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -724,11 +719,11 @@ mod test { use super::*; use rand::rngs::mock::StepRng; - use crate::grin_util::{secp, static_secp_instance}; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::Signer; use ed25519_dalek::SigningKey as DalekSecretKey; use ed25519_dalek::VerifyingKey as DalekPublicKey; + use grin_util::{secp, static_secp_instance}; use serde::Deserialize; use serde_json; @@ -758,9 +753,9 @@ mod test { println!("D sig: {:?}", d_sig); SerTest { - pub_key: d_pub_key.clone(), + pub_key: d_pub_key, pub_key_opt: Some(d_pub_key), - sig: d_sig.clone(), + sig: d_sig, sig_opt: Some(d_sig), } } diff --git a/libwallet/src/slate_versions/v4.rs b/libwallet/src/slate_versions/v4.rs index d76885a..690ecfc 100644 --- a/libwallet/src/slate_versions/v4.rs +++ b/libwallet/src/slate_versions/v4.rs @@ -34,7 +34,7 @@ //! * The feat_args struct is added, which may be populated for non-Plain kernels //! * `proof` may be omitted from the slate if it is None (null), //! * `off` (offset) is added, and will be modified by every participant in the transaction with a random -//! value - the value of their inputs' blinding factors +//! value - the value of their inputs' blinding factors //! //! #### Participant Data (`sigs`) //! @@ -53,12 +53,12 @@ //! * The `receiver_signature` field is renamed to `rsig` //! * `rsig` may be omitted if it has not yet been filled out -use crate::grin_core::core::FeeFields; -use crate::grin_core::libtx::secp_ser; -use crate::grin_keychain::BlindingFactor; use crate::slate_versions::ser; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::FeeFields; +use grin_core::libtx::secp_ser; +use grin_keychain::BlindingFactor; use uuid::Uuid; pub use crate::slate_versions::common::{ diff --git a/libwallet/src/slate_versions/v4_bin.rs b/libwallet/src/slate_versions/v4_bin.rs index 3e1760c..66eb130 100644 --- a/libwallet/src/slate_versions/v4_bin.rs +++ b/libwallet/src/slate_versions/v4_bin.rs @@ -14,15 +14,15 @@ //! Wraps a V4 Slate into a V4 Binary slate -use crate::grin_core::core::transaction::{FeeFields, OutputFeatures}; -use crate::grin_core::ser as grin_ser; -use crate::grin_core::ser::{Readable, Reader, Writeable, Writer}; -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::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::transaction::{FeeFields, OutputFeatures}; +use grin_core::ser as grin_ser; +use grin_core::ser::{Readable, Reader, Writeable, Writer}; +use grin_keychain::BlindingFactor; +use grin_util::secp::key::PublicKey; +use grin_util::secp::pedersen::{Commitment, RangeProof}; +use grin_util::secp::Signature; use std::convert::TryFrom; use uuid::Uuid; @@ -68,7 +68,7 @@ pub(crate) struct UuidWrap(pub Uuid); impl Writeable for UuidWrap { fn write(&self, writer: &mut W) -> Result<(), grin_ser::Error> { - writer.write_fixed_bytes(&self.0.as_bytes()) + writer.write_fixed_bytes(self.0.as_bytes()) } } @@ -211,7 +211,7 @@ impl Readable for SigsWrap { nonce: PublicKey::read(reader)?, part: match has_partial { 1 => Some(Signature::read(reader)?), - 0 | _ => None, + _ => None, }, }; ret.push(c); @@ -252,10 +252,10 @@ impl<'a> Writeable for SlateOptStructsRef<'a> { }; writer.write_u8(status)?; if let Some(c) = self.coms { - ComsWrapRef(&c).write(writer)?; + ComsWrapRef(c).write(writer)?; } if let Some(p) = self.proof { - ProofWrapRef(&p).write(writer)?; + ProofWrapRef(p).write(writer)?; } Ok(()) } @@ -314,7 +314,7 @@ impl Readable for ComsWrap { c: Commitment::read(reader)?, p: match is_output { 1 => Some(RangeProof::read(reader)?), - 0 | _ => None, + _ => None, }, }; ret.push(c); @@ -335,7 +335,7 @@ impl<'a> Writeable for ProofWrapRef<'a> { match self.0.rsig { Some(s) => { writer.write_u8(1)?; - writer.write_fixed_bytes(&s.to_bytes().to_vec())?; + writer.write_fixed_bytes(s.to_bytes())?; } None => writer.write_u8(0)?, } @@ -359,7 +359,7 @@ impl Readable for ProofWrap { let rsig = match reader.read_u8()? { 0 => None, - 1 | _ => Some( + _ => Some( DalekSignature::try_from(&reader.read_fixed_bytes(64)?[..]) .map_err(|_| grin_ser::Error::CorruptedData)?, ), @@ -512,11 +512,11 @@ impl Readable for SlateV4Bin { #[test] fn slate_v4_serialize_deserialize() { - use crate::grin_util::from_hex; - use crate::grin_util::secp::key::PublicKey; use crate::Slate; use grin_core::global::{set_local_chain_type, ChainTypes}; use grin_keychain::{ExtKeychain, Keychain, SwitchCommitmentType}; + use grin_util::from_hex; + use grin_util::secp::key::PublicKey; set_local_chain_type(ChainTypes::Mainnet); let slate = Slate::blank(1, false); @@ -556,11 +556,7 @@ fn slate_v4_serialize_deserialize() { c: Commitment::from_vec([4u8; 1].to_vec()), p: Some(RangeProof::zero()), }; - let mut coms = vec![]; - coms.push(com1.clone()); - coms.push(com1.clone()); - coms.push(com1.clone()); - coms.push(com2); + let coms = vec![com1, com1, com1, com2]; v4.coms = Some(coms); v4.amt = 234324899824; @@ -572,7 +568,7 @@ fn slate_v4_serialize_deserialize() { let v4_bin = SlateV4Bin(v4); let mut vec = Vec::new(); - let _ = grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed"); + grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed"); let b4_bin_2: SlateV4Bin = grin_ser::deserialize_default(&mut &vec[..]).unwrap(); let v4_2 = b4_bin_2.0.clone(); assert_eq!(v4_1.ver, v4_2.ver); @@ -595,15 +591,15 @@ fn slate_v4_serialize_deserialize() { 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(), + raddr: d_pkey, + saddr: d_pkey, rsig: None, }); v4.coms = None; let v4_1 = v4.clone(); let v4_bin = SlateV4Bin(v4); let mut vec = Vec::new(); - let _ = grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed"); + grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed"); let b4_bin_2: SlateV4Bin = grin_ser::deserialize_default(&mut &vec[..]).unwrap(); let v4_2 = b4_bin_2.0.clone(); assert_eq!(v4_1.ver, v4_2.ver); diff --git a/libwallet/src/slate_versions/v5.rs b/libwallet/src/slate_versions/v5.rs index 0c32165..b074cb1 100644 --- a/libwallet/src/slate_versions/v5.rs +++ b/libwallet/src/slate_versions/v5.rs @@ -27,14 +27,14 @@ //! * `ts` adds an optional timestamp, serialized as seconds since the epoch //! * `memo` adds optional payment details -use crate::grin_core::core::FeeFields; -use crate::grin_core::libtx::secp_ser; -use crate::grin_keychain::BlindingFactor; use crate::slate::{PaymentMemo, PaymentProofType}; use crate::slate_versions::ser; use chrono::prelude::{DateTime, Utc}; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::FeeFields; +use grin_core::libtx::secp_ser; +use grin_keychain::BlindingFactor; 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 477bf51..f7d9544 100644 --- a/libwallet/src/slate_versions/v5_bin.rs +++ b/libwallet/src/slate_versions/v5_bin.rs @@ -14,13 +14,13 @@ //! Wraps a V5 Slate into a V5 Binary slate -use crate::grin_core::ser as grin_ser; -use crate::grin_core::ser::{Readable, Reader, Writeable, Writer}; -use crate::grin_keychain::BlindingFactor; use crate::slate::{PaymentMemo, PaymentProofType}; use chrono::DateTime; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::ser as grin_ser; +use grin_core::ser::{Readable, Reader, Writeable, Writer}; +use grin_keychain::BlindingFactor; use std::convert::TryFrom; use crate::slate_versions::v5::{ @@ -187,7 +187,7 @@ impl Readable for ProofWrap { #[test] fn rejects_invalid_proof_fields() { - use crate::grin_util::from_hex; + use grin_util::from_hex; let bytes = from_hex("d03c09e9c19bb74aa9ea44e0fe5ae237a9bf40bddf0941064a80913a4459c8bb").unwrap(); @@ -356,16 +356,16 @@ impl Readable for SlateV5Bin { #[test] fn slate_v5_serialize_deserialize() { - use crate::grin_core::core::transaction::OutputFeatures; - use crate::grin_util::from_hex; - 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::v5::ParticipantDataV5; use crate::Slate; use chrono::Utc; + use grin_core::core::transaction::OutputFeatures; use grin_core::global::{set_local_chain_type, ChainTypes}; use grin_keychain::{ExtKeychain, Keychain, SwitchCommitmentType}; + use grin_util::from_hex; + use grin_util::secp::key::PublicKey; + use grin_util::secp::pedersen::{Commitment, RangeProof}; + use grin_util::secp::Signature; set_local_chain_type(ChainTypes::Mainnet); let slate = Slate::blank(1, false); let mut v5 = SlateV5::from(slate); diff --git a/libwallet/src/slatepack/address.rs b/libwallet/src/slatepack/address.rs index 9368e38..4add579 100644 --- a/libwallet/src/slatepack/address.rs +++ b/libwallet/src/slatepack/address.rs @@ -20,11 +20,11 @@ use rand::{thread_rng, Rng}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use x25519_dalek::PublicKey as xDalekPublicKey; -use crate::grin_core::global; -use crate::grin_core::ser::{self, Readable, Reader, Writeable, Writer}; -use crate::grin_util::secp::key::SecretKey; use crate::util::OnionV3Address; use crate::Error; +use grin_core::global; +use grin_core::ser::{self, Readable, Reader, Writeable, Writer}; +use grin_util::secp::key::SecretKey; use std::convert::TryFrom; use std::fmt::{self, Display}; @@ -53,7 +53,7 @@ impl SlatepackAddress { pub fn new(pub_key: &edDalekPublicKey) -> Self { Self { hrp: String::from(slatepack_hrp()), - pub_key: pub_key.clone(), + pub_key: *pub_key, } } @@ -68,7 +68,7 @@ impl SlatepackAddress { pub fn encoded_len(&self) -> Result { let encoded = String::try_from(self)?; // add length byte - Ok(encoded.as_bytes().len() + 1) + Ok(encoded.len() + 1) } /// utility to construct a public key that can be read by age 0.5+, @@ -97,7 +97,7 @@ impl Display for SlatepackAddress { impl TryFrom<&str> for SlatepackAddress { type Error = Error; fn try_from(encoded: &str) -> Result { - let (hrp, data) = bech32::decode(&encoded)?; + let (hrp, data) = bech32::decode(encoded)?; if !valid_network(&hrp) { return Err(Error::SlatepackAddress(format!( "wrong address prefix for chain {:?}", @@ -107,7 +107,7 @@ impl TryFrom<&str> for SlatepackAddress { let bytes = Vec::::from_base32(&data)?; 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) { + let pub_key = match edDalekPublicKey::from_bytes(b) { Ok(k) => k, Err(e) => { return Err(Error::ED25519Key(format!("{}", e))); @@ -170,7 +170,6 @@ impl TryFrom<&SecretKey> for SlatepackAddress { /// Serializes a SlatepackAddress to a bech32 string impl Serialize for SlatepackAddress { - /// fn serialize(&self, serializer: S) -> Result where S: Serializer, @@ -232,7 +231,7 @@ impl Writeable for SlatepackAddress { return Err(ser::Error::CorruptedData); } writer.write_u8(bytes.len() as u8)?; - writer.write_fixed_bytes(&bytes) + writer.write_fixed_bytes(bytes) } } diff --git a/libwallet/src/slatepack/armor.rs b/libwallet/src/slatepack/armor.rs index c8be299..9f4b31f 100644 --- a/libwallet/src/slatepack/armor.rs +++ b/libwallet/src/slatepack/armor.rs @@ -29,9 +29,11 @@ use std::str; use super::types::{Slatepack, SlatepackBin}; -// Framing and formatting for slate armor +/// Slatepack file header. pub static HEADER: &str = "BEGINSLATEPACK."; -static FOOTER: &str = ". ENDSLATEPACK."; +/// Slatepack file footer. +pub static FOOTER: &str = ". ENDSLATEPACK."; + const WORD_LENGTH: usize = 15; const WORDS_PER_LINE: usize = 200; const WEIGHT_RATIO: u64 = 32; @@ -50,11 +52,9 @@ pub fn min_size() -> u64 { } lazy_static! { - static ref HEADER_REGEX: Regex = - Regex::new(concat!(r"^[>\n\r\t ]*BEGINSLATEPACK[>\n\r\t ]*$")).unwrap(); - static ref FOOTER_REGEX: Regex = - Regex::new(concat!(r"^[>\n\r\t ]*ENDSLATEPACK[>\n\r\t ]*$")).unwrap(); - static ref WHITESPACE_LIST: [u8; 5] = [b'>', b'\n', b'\r', b'\t', b' ']; + static ref HEADER_REGEX: Regex = Regex::new(r"^[>\n\r\t ]*BEGINSLATEPACK[>\n\r\t ]*$").unwrap(); + static ref FOOTER_REGEX: Regex = Regex::new(r"^[>\n\r\t ]*ENDSLATEPACK[>\n\r\t ]*$").unwrap(); + static ref WHITESPACE_LIST: [u8; 5] = *b">\n\r\t "; } /// Wrapper for associated functions diff --git a/libwallet/src/slatepack/mod.rs b/libwallet/src/slatepack/mod.rs index 89154d9..d2392fd 100644 --- a/libwallet/src/slatepack/mod.rs +++ b/libwallet/src/slatepack/mod.rs @@ -16,10 +16,31 @@ mod address; mod armor; -mod packer; mod types; pub use self::address::SlatepackAddress; -pub use self::armor::{max_size, min_size, SlatepackArmor}; -pub use self::packer::{Slatepacker, SlatepackerArgs}; -pub use self::types::{Slatepack, SlatepackBin, SlatepackMode}; +pub use self::armor::{max_size, min_size, SlatepackArmor, FOOTER, HEADER}; +pub use self::types::{Slatepack, SlatepackAddressIndex, SlatepackBin, SlatepackMode}; + +use std::fs::{metadata, File}; +use std::io::Read; +use std::path::PathBuf; + +/// Get slatepack file contents. +pub fn get_slatepack_file_contents(path: &PathBuf) -> Result, crate::Error> { + let metadata = metadata(path)?; + let len = metadata.len(); + let min_len = min_size(); + let max_len = max_size(); + if len < min_len || len > max_len { + let msg = format!( + "Data is invalid length: {} | min: {}, max: {} |", + len, min_len, max_len + ); + return Err(crate::Error::SlatepackDeser(msg)); + } + let mut pub_tx_f = File::open(path)?; + let mut data = Vec::new(); + pub_tx_f.read_to_end(&mut data)?; + Ok(data) +} diff --git a/libwallet/src/slatepack/packer.rs b/libwallet/src/slatepack/packer.rs deleted file mode 100644 index a7b4c97..0000000 --- a/libwallet/src/slatepack/packer.rs +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2021 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 std::convert::TryFrom; -use std::str; - -use super::armor::HEADER; -use crate::Error; -use crate::{ - slatepack, Slate, SlateVersion, Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, - VersionedBinSlate, VersionedSlate, -}; - -use grin_wallet_util::byte_ser; - -use ed25519_dalek::SigningKey as edSecretKey; - -#[derive(Clone)] -/// Arguments, mostly for encrypting decrypting a slatepack -pub struct SlatepackerArgs<'a> { - /// Optional sender to include in slatepack - pub sender: Option, - /// Optional list of recipients, for encryption - pub recipients: Vec, - /// Optional decryption key - pub dec_key: Option<&'a edSecretKey>, -} - -/// Helper struct to pack and unpack slatepacks -#[derive(Clone)] -pub struct Slatepacker<'a>(SlatepackerArgs<'a>); - -impl<'a> Slatepacker<'a> { - /// Create with pathbuf and recipients - pub fn new(args: SlatepackerArgs<'a>) -> Self { - Self(args) - } - - /// return slatepack - pub fn deser_slatepack(&self, data: &[u8], decrypt: bool) -> Result { - // check if data is armored, if so, remove and continue - let data_len = data.len() as u64; - if data_len < slatepack::min_size() || data_len > slatepack::max_size() { - let msg = format!("Data invalid length"); - return Err(Error::SlatepackDeser(msg)); - } - - let test_header = &data[..HEADER.len()]; - - let data = match str::from_utf8(test_header) { - Ok(s) => { - if s == HEADER { - SlatepackArmor::decode(data)? - } else { - data.to_vec() - } - } - Err(_) => data.to_vec(), - }; - - // try as bin first, then as json - let mut slatepack = match byte_ser::from_bytes::(&data) { - Ok(s) => s.0, - Err(e) => { - debug!("Not a valid binary slatepack: {} - Will try JSON", e); - let content = String::from_utf8(data).map_err(|e| { - let msg = format!("{}", e); - Error::SlatepackDeser(msg) - })?; - serde_json::from_str(&content).map_err(|e| { - let msg = format!("Error reading JSON slatepack: {}", e); - Error::SlatepackDeser(msg) - })? - } - }; - - slatepack.ver_check_warn(); - if decrypt { - slatepack.try_decrypt_payload(self.0.dec_key)?; - } - Ok(slatepack) - } - - /// Create slatepack from slate and args - pub fn create_slatepack(&self, slate: &Slate) -> Result { - let version = SlateVersion::output_for(slate)?; - let out_slate = VersionedSlate::into_version(slate.clone(), version)?; - let bin_slate = VersionedBinSlate::try_from(out_slate).map_err(|_| Error::SlatepackSer)?; - let mut slatepack = Slatepack::default(); - slatepack.payload = byte_ser::to_bytes(&bin_slate).map_err(|_| Error::SlatepackSer)?; - slatepack.sender = self.0.sender.clone(); - slatepack.try_encrypt_payload(self.0.recipients.clone())?; - Ok(slatepack) - } - - /// Armor a slatepack - pub fn armor_slatepack(&self, slatepack: &Slatepack) -> Result { - SlatepackArmor::encode(&slatepack) - } - - /// Return/upgrade slate from slatepack - pub fn get_slate(&self, slatepack: &Slatepack) -> Result { - let slate_bin = - byte_ser::from_bytes::(&slatepack.payload).map_err(|e| { - error!("Error reading slate from armored slatepack: {}", e); - let msg = format!("{}", e); - Error::SlatepackDeser(msg) - })?; - Ok(Slate::upgrade(slate_bin.into())?) - } -} diff --git a/libwallet/src/slatepack/types.rs b/libwallet/src/slatepack/types.rs index 1d72312..4834764 100644 --- a/libwallet/src/slatepack/types.rs +++ b/libwallet/src/slatepack/types.rs @@ -12,22 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -use bech32::{self, ToBase32}; -use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; -/// Slatepack Types + Serialization implementation -use ed25519_dalek::SigningKey as edSecretKey; -use sha2::{Digest, Sha512}; -use x25519_dalek::StaticSecret; - -use crate::dalek_ser; -use crate::grin_core::ser::{self, Readable, Reader, Writeable, Writer}; +use super::SlatepackAddress; use crate::Error; +use crate::{dalek_ser, Slate, SlatepackArmor, VersionedBinSlate}; +use grin_core::ser::{self, Readable, Reader, Writeable, Writer}; use grin_wallet_util::byte_ser; -use super::SlatepackAddress; - +use bech32::{self, ToBase32}; +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; +use ed25519_dalek::SigningKey as edSecretKey; +use sha2::{Digest, Sha512}; use std::fmt; use std::io::{Cursor, Read, Write}; +use x25519_dalek::StaticSecret; pub const SLATEPACK_MAJOR_VERSION: u8 = 1; pub const SLATEPACK_MINOR_VERSION: u8 = 0; @@ -211,7 +208,7 @@ impl Slatepack { to_encrypt.append(&mut self.payload); - let rec_keys: Result, _> = recipients + let rec_keys: Result, Error> = recipients .into_iter() .map(|addr| { let recp_key: age::x25519::Recipient = addr.to_age_pubkey_str()?.parse()?; @@ -219,10 +216,7 @@ impl Slatepack { }) .collect(); - let keys = match rec_keys { - Ok(k) => k, - Err(e) => return Err(e), - }; + let keys = rec_keys?; let encryptor = age::Encryptor::with_recipients(keys); let mut encrypted = vec![]; @@ -252,7 +246,7 @@ impl Slatepack { let x_dec_secret = StaticSecret::from(b); let x_dec_secret_bech32 = - bech32::encode("age-secret-key-", (&x_dec_secret).to_bytes().to_base32())?; + bech32::encode("age-secret-key-", x_dec_secret.to_bytes().to_base32())?; let key: age::x25519::Identity = x_dec_secret_bech32.parse()?; let decryptor = match age::Decryptor::new(&self.payload[..])? { @@ -323,6 +317,52 @@ impl Slatepack { ); } } + + /// Return/upgrade slate from slatepack. + pub fn get_slate(&self) -> Result { + if self.is_encrypted() { + return Err(Error::SlatepackDecryption( + "Slatepack payload is encrypted".into(), + )); + } + let slate_bin = byte_ser::from_bytes::(&self.payload).map_err(|e| { + error!("Error reading slate from armored slatepack: {}", e); + let msg = format!("{}", e); + Error::SlatepackDeser(msg) + })?; + Slate::upgrade(slate_bin.into()) + } + + /// Armor this slatepack. + pub fn armor(&self) -> Result { + SlatepackArmor::encode(self) + } +} + +/// Slatepack address derivation path index +#[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] +pub struct SlatepackAddressIndex(pub u32); + +impl SlatepackAddressIndex { + /// The max BIP32 index. + pub const MAX: u32 = 2_147_483_647; + + /// Check the index range + pub fn check(self) -> Result { + if self.0 > Self::MAX { + return Err(Error::SlatepackAddress(format!( + "Slatepack index {} is out of bound, maximum value is {}", + self.0, + Self::MAX + ))); + } + Ok(self) + } + + /// Index value. + pub fn value(self) -> u32 { + self.0 + } } /// Wrapper for outputting slate as binary @@ -398,7 +438,7 @@ impl Writeable for SlatepackBin { }; // encrypted metadata is only included in the payload - // on encryption, and is not serialised here + // on encryption, and is not serialized here // Now write payload (length prefixed) writer.write_bytes(sp.payload.clone()) @@ -485,7 +525,7 @@ pub mod slatepack_version { use super::SlatepackVersion; - /// + /// Write the Slatepack version as `major.minor` pub fn serialize(v: &SlatepackVersion, serializer: S) -> Result where S: Serializer, @@ -493,7 +533,7 @@ pub mod slatepack_version { serializer.serialize_str(&format!("{}.{}", v.major, v.minor)) } - /// + /// Read a `major.minor` Slatepack version pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -504,11 +544,11 @@ pub mod slatepack_version { if v.len() != 2 { return Err(Error::custom("Cannot parse version")); } - match u8::from_str_radix(v[0], 10) { + match v[0].parse::() { Ok(u) => retval.major = u, Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } - match u8::from_str_radix(v[1], 10) { + match v[1].parse::() { Ok(u) => retval.minor = u, Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } @@ -631,7 +671,7 @@ impl Writeable for SlatepackEncMetadataBin { if !inner.recipients.is_empty() { let len = inner.recipients.len(); // write number of recipients - if len as u16 > std::u16::MAX { + if len > u16::MAX as usize { error!("Too many recipients: {}", len); return Err(ser::Error::CorruptedData); } @@ -721,7 +761,7 @@ fn slatepack_bin_basic_ser() -> Result<(), grin_wallet_util::byte_ser::Error> { #[test] fn slatepack_bin_opt_fields_ser() -> Result<(), grin_wallet_util::byte_ser::Error> { - use crate::grin_core::global; + use grin_core::global; use grin_wallet_util::byte_ser; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); let mut payload: Vec = Vec::with_capacity(243); @@ -745,9 +785,9 @@ fn slatepack_bin_opt_fields_ser() -> Result<(), grin_wallet_util::byte_ser::Erro // ensure that a slatepack with unknown data in the optional fields can be read #[test] -fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { - use crate::grin_core::global; +fn slatepack_bin_future() -> Result<(), byte_ser::Error> { use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + use grin_core::global; use grin_wallet_util::byte_ser; use rand::{thread_rng, Rng}; use std::io::Cursor; @@ -791,9 +831,7 @@ fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { let end_head_pos = opt_fields_len as usize + 8 + 1; - for i in 0..end_head_pos { - new_bytes.push(ser[i]); - } + new_bytes.extend_from_slice(&ser[..end_head_pos]); for _ in 0..num_extra_bytes { new_bytes.push(thread_rng().gen()); } @@ -811,9 +849,7 @@ fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { let mut wtr = vec![]; wtr.write_u32::(opt_fields_len + num_extra_bytes as u32) .unwrap(); - for i in 0..wtr.len() { - new_bytes[5 + i] = wtr[i]; - } + new_bytes[5..(wtr.len() + 5)].copy_from_slice(&wtr[..]); let deser = byte_ser::from_bytes::(&new_bytes)?.0; assert_eq!(sp, deser); @@ -824,10 +860,10 @@ fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { // in AgeEncrypted mode #[test] fn slatepack_encrypted_meta() -> Result<(), Error> { - use crate::grin_core::global; use crate::{Slate, SlateVersion, VersionedBinSlate, VersionedSlate}; use ed25519_dalek::SigningKey as edDalekSecretKey; use ed25519_dalek::VerifyingKey as edDalekPublicKey; + use grin_core::global; use rand::{thread_rng, Rng}; use std::convert::TryFrom; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); @@ -842,8 +878,10 @@ fn slatepack_encrypted_meta() -> Result<(), Error> { let parsed_addr = SlatepackAddress::try_from(encoded.as_str()).unwrap(); assert_eq!(addr, parsed_addr); - let mut slatepack = super::Slatepack::default(); - slatepack.sender = Some(SlatepackAddress::random()); + let mut slatepack = Slatepack { + sender: Some(SlatepackAddress::random()), + ..Default::default() + }; slatepack.add_recipient(SlatepackAddress::random()); slatepack.add_recipient(SlatepackAddress::random()); @@ -873,10 +911,10 @@ fn slatepack_encrypted_meta() -> Result<(), Error> { // metadata won't break parsing #[test] fn slatepack_encrypted_meta_future() -> Result<(), Error> { - use crate::grin_core::global; use crate::{Slate, SlateVersion, VersionedBinSlate, VersionedSlate}; use ed25519_dalek::SigningKey as edDalekSecretKey; use ed25519_dalek::VerifyingKey as edDalekPublicKey; + use grin_core::global; use rand::{thread_rng, Rng}; use std::convert::TryFrom; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); @@ -891,8 +929,10 @@ fn slatepack_encrypted_meta_future() -> Result<(), Error> { let parsed_addr = SlatepackAddress::try_from(encoded.as_str()).unwrap(); assert_eq!(addr, parsed_addr); - let mut slatepack = Slatepack::default(); - slatepack.sender = Some(SlatepackAddress::random()); + let mut slatepack = Slatepack { + sender: Some(SlatepackAddress::random()), + ..Default::default() + }; slatepack.add_recipient(SlatepackAddress::random()); slatepack.add_recipient(SlatepackAddress::random()); @@ -950,12 +990,12 @@ fn encrypt_plaintext_to_slatepack_recipient( #[test] fn slatepack_decrypt_rejects_malformed_plaintexts() -> Result<(), Error> { - use crate::grin_core::global; + use 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]] { + for plaintext in [vec![], vec![0], vec![0, 0, 0], vec![0xff; 4]] { let mut slatepack = Slatepack { mode: SlatepackMode::AgeEncrypted, payload: encrypt_plaintext_to_slatepack_recipient(&addr, &plaintext)?, @@ -992,3 +1032,16 @@ fn rejects_passphrase_payload() -> Result<(), Error> { Ok(()) } + +#[test] +fn index_bounds() { + for index in [0, SlatepackAddressIndex::MAX] { + assert_eq!(SlatepackAddressIndex(index).check().unwrap().value(), index); + } + for index in [SlatepackAddressIndex::MAX + 1, u32::MAX] { + assert!(matches!( + SlatepackAddressIndex(index).check(), + Err(Error::SlatepackAddress(_)) + )); + } +} diff --git a/libwallet/src/types.rs b/libwallet/src/types.rs index 47446ec..6a6cd96 100644 --- a/libwallet/src/types.rs +++ b/libwallet/src/types.rs @@ -18,26 +18,26 @@ 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; -use crate::grin_core::core::{Output, Transaction, TxKernel}; -use crate::grin_core::libtx::{aggsig, secp_ser}; -use crate::grin_core::{global, ser}; -use crate::grin_keychain::{Identifier, Keychain}; -use crate::grin_util::logger::LoggingConfig; -use crate::grin_util::secp::key::{PublicKey, SecretKey}; -use crate::grin_util::secp::{pedersen, Secp256k1, Signature}; -use crate::grin_util::{ToHex, ZeroingString}; use crate::slate::PaymentMemo; use crate::slate_versions::ser::{dalek_pubkey_serde, option_dalek_sig_serde, option_pubkey_serde}; +use crate::slatepack::SlatepackAddressIndex; use crate::{InitTxArgs, SlateState, WalletBackend}; use chrono::prelude::*; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::hash::Hash; +use grin_core::core::FeeFields; +use grin_core::core::{Output, Transaction, TxKernel}; +use grin_core::libtx::{aggsig, secp_ser}; +use grin_core::{global, ser}; +use grin_keychain::{Identifier, Keychain}; +use grin_util::logger::LoggingConfig; +use grin_util::secp::key::{PublicKey, SecretKey}; +use grin_util::secp::Signature; +use grin_util::secp::{pedersen, Secp256k1}; +use grin_util::{ToHex, ZeroingString}; use rand::rngs::mock::StepRng; use rand::thread_rng; -use serde; -use serde_json; use std::collections::HashMap; use std::time::Duration; use std::{cmp, fmt}; @@ -78,17 +78,17 @@ where tor_config: Option, ) -> Result<(), Error>; - /// + /// Create the seed file and wallet database from a mnemonic or fresh entropy fn create_wallet( &mut self, name: Option<&str>, mnemonic: Option, - mnemonic_length: usize, + entropy_size: usize, password: ZeroingString, test_mode: bool, ) -> Result<(), Error>; - /// + /// Unlock the wallet and optionally mask its keychain fn open_wallet( &mut self, name: Option<&str>, @@ -97,7 +97,7 @@ where use_test_rng: bool, ) -> Result, Error>; - /// + /// Close the wallet and drop its stored keychain fn close_wallet(&mut self, name: Option<&str>) -> Result<(), Error>; /// whether a wallet exists at the given directory @@ -182,6 +182,7 @@ pub trait NodeClient: Send + Sync + Clone { /// Returns /// (last available output index, last insertion index retrieved, /// outputs(commit, proof, is_coinbase, height, mmr_index)) + #[allow(clippy::type_complexity)] fn get_outputs_by_pmmr_index( &self, start_height: u64, @@ -324,9 +325,8 @@ impl OutputData { /// Mark an output as reverted pub fn mark_reverted(&mut self) { - match self.status { - OutputStatus::Unspent => self.status = OutputStatus::Reverted, - _ => (), + if self.status == OutputStatus::Unspent { + self.status = OutputStatus::Reverted } } } @@ -390,7 +390,7 @@ pub struct Context { /// store the calculated fee pub fee: Option, /// Payment proof sender address derivation path, if needed - pub payment_proof_derivation_index: Option, + pub payment_proof_derivation_index: Option, /// If late-locking, store my tranasction creation prefs /// for later pub late_lock_args: Option, @@ -647,14 +647,14 @@ pub enum TxLogEntryType { impl fmt::Display for TxLogEntryType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - TxLogEntryType::ConfirmedCoinbase => write!(f, "Confirmed \nCoinbase"), + TxLogEntryType::ConfirmedCoinbase => write!(f, "Confirmed Coinbase"), TxLogEntryType::TxReceived => write!(f, "Received Tx"), TxLogEntryType::TxSent => write!(f, "Sent Tx"), - TxLogEntryType::TxReceivedCancelled => write!(f, "Received Tx\n- Cancelled"), - TxLogEntryType::TxSentCancelled => write!(f, "Sent Tx\n- Cancelled"), - TxLogEntryType::TxReverted => write!(f, "Received Tx\n- Reverted"), + TxLogEntryType::TxReceivedCancelled => write!(f, "Received Tx - Cancelled"), + TxLogEntryType::TxSentCancelled => write!(f, "Sent Tx - Cancelled"), + TxLogEntryType::TxReverted => write!(f, "Received Tx - Reverted"), TxLogEntryType::TxSelfSpend => write!(f, "Self Spend"), - TxLogEntryType::TxSelfSpendCancelled => write!(f, "Self Spend\n- Cancelled"), + TxLogEntryType::TxSelfSpendCancelled => write!(f, "Self Spend - Cancelled"), } } } @@ -716,6 +716,9 @@ pub struct TxLogEntry { /// Track the time it took for a transaction to get reverted #[serde(with = "option_duration_as_secs", default)] pub reverted_after: Option, + /// Slatepack address derivation path index + #[serde(default)] + pub address_index: Option, } impl ser::Writeable for TxLogEntry { @@ -754,6 +757,7 @@ impl TxLogEntry { kernel_lookup_min_height: None, payment_proof: None, reverted_after: None, + address_index: None, } } @@ -796,7 +800,7 @@ pub struct StoredProofInfo { /// Receiver signature for legacy proofs, or promise signature for early proofs pub receiver_signature: Option, /// sender address derivation path index - pub sender_address_path: u32, + pub sender_address_path: SlatepackAddressIndex, /// sender address #[serde(with = "dalek_pubkey_serde")] pub sender_address: DalekPublicKey, @@ -848,7 +852,7 @@ impl StoredProofInfo { receiver_address: DalekPublicKey, receiver_signature: Option, sender_address: DalekPublicKey, - sender_address_path: u32, + sender_address_path: SlatepackAddressIndex, sender_signature: Option, ) -> Self { Self { @@ -884,10 +888,14 @@ impl ser::Readable for StoredProofInfo { /// Map of named accounts to BIP32 paths #[derive(Clone, Debug, Serialize, Deserialize)] pub struct AcctPathMapping { - /// label used by user + /// Label used by user. pub label: String, - /// Corresponding parent BIP32 derivation path + /// Corresponding parent BIP32 derivation path. pub path: Identifier, + /// Wallet information for this account, can be loaded after deserialization. + pub info: Option, + /// Flag to check if this is current active account. + pub current: Option, } impl ser::Writeable for AcctPathMapping { @@ -988,17 +996,17 @@ pub struct ViewWallet { /// Utility struct for return values from below #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ViewWalletOutputResult { - /// + /// Output commitment as hex pub commit: String, - /// + /// Value in nanogrins pub value: u64, - /// + /// Block height of the output pub height: u64, - /// + /// Output position in the PMMR pub mmr_index: u64, - /// + /// Whether this is a mining reward pub is_coinbase: bool, - /// + /// Earliest spendable height pub lock_height: u64, } @@ -1045,7 +1053,7 @@ pub mod option_duration_as_secs { use serde::{Deserialize, Deserializer, Serializer}; use std::time::Duration; - /// + /// Write whole seconds as a string, or null pub fn serialize(dur: &Option, serializer: S) -> Result where S: Serializer, @@ -1056,7 +1064,7 @@ pub mod option_duration_as_secs { } } - /// + /// Read an optional duration from a seconds string pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -1092,7 +1100,13 @@ mod tests { let key = DalekSecretKey::from_bytes(&[1u8; 32]).verifying_key(); let mut tx = TxLogEntry::new(Identifier::zero(), TxLogEntryType::TxSent, 0); tx.fee = Some(FeeFields::new(0, 23_000_000).unwrap()); - tx.payment_proof = Some(StoredProofInfo::new(key, None, key, 0, None)); + tx.payment_proof = Some(StoredProofInfo::new( + key, + None, + key, + SlatepackAddressIndex(0), + None, + )); // legacy send tx.amount_debited = 1_500_000_000; tx.amount_credited = 477_000_000; @@ -1174,7 +1188,7 @@ mod tests { receiver_public_excess: Some(public_key), sender_public_nonce: Some(public_key), sender_part_sig: Some(signature), - ..StoredProofInfo::new(address, None, address, 0, None) + ..StoredProofInfo::new(address, None, address, SlatepackAddressIndex(0), None) }; let value = serde_json::to_value(&proof).unwrap(); for field in [ diff --git a/libwallet/tests/libwallet.rs b/libwallet/tests/libwallet.rs index 6d392a9..8c41703 100644 --- a/libwallet/tests/libwallet.rs +++ b/libwallet/tests/libwallet.rs @@ -56,7 +56,7 @@ fn aggsig_sender_receiver_interaction() { keychain .secp() - .commit(0, blinding_factor.secret_key(&keychain.secp()).unwrap()) + .commit(0, blinding_factor.secret_key(keychain.secp()).unwrap()) .unwrap() }; @@ -75,10 +75,10 @@ fn aggsig_sender_receiver_interaction() { .blind_sum(&bs.sub_blinding_factor(BlindingFactor::from_secret_key(skey))) .unwrap(); - let blind = blinding_factor.secret_key(&keychain.secp()).unwrap(); + let blind = blinding_factor.secret_key(keychain.secp()).unwrap(); - s_cx = Context::with_excess(&keychain.secp(), blind, &parent, false); - s_cx.get_public_keys(&keychain.secp()) + s_cx = Context::with_excess(keychain.secp(), blind, &parent, false); + s_cx.get_public_keys(keychain.secp()) }; let pub_nonce_sum; @@ -91,8 +91,8 @@ fn aggsig_sender_receiver_interaction() { // let blind = blind_sum.secret_key(&keychain.secp())?; let blind = keychain.derive_key(0, &key_id, switch).unwrap(); - rx_cx = Context::with_excess(&keychain.secp(), blind, &parent, false); - let (pub_excess, pub_nonce) = rx_cx.get_public_keys(&keychain.secp()); + rx_cx = Context::with_excess(keychain.secp(), blind, &parent, false); + let (pub_excess, pub_nonce) = rx_cx.get_public_keys(keychain.secp()); rx_cx.add_output(&key_id, &None, 0); pub_nonce_sum = PublicKey::from_combination( @@ -115,7 +115,7 @@ fn aggsig_sender_receiver_interaction() { let msg = kernel_sig_msg(); let sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_cx.sec_key, &rx_cx.sec_nonce, &pub_nonce_sum, @@ -132,14 +132,14 @@ fn aggsig_sender_receiver_interaction() { let keychain = sender_keychain.clone(); let msg = kernel_sig_msg(); let sig_verifies = aggsig::verify_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_sig_part, &pub_nonce_sum, &receiver_pub_excess, Some(&pub_key_sum), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // now sender signs with their key @@ -147,7 +147,7 @@ fn aggsig_sender_receiver_interaction() { let keychain = sender_keychain.clone(); let msg = kernel_sig_msg(); let sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &s_cx.sec_key, &s_cx.sec_nonce, &pub_nonce_sum, @@ -164,14 +164,14 @@ fn aggsig_sender_receiver_interaction() { let keychain = receiver_keychain.clone(); let msg = kernel_sig_msg(); let sig_verifies = aggsig::verify_partial_sig( - &keychain.secp(), + keychain.secp(), &sender_sig_part, &pub_nonce_sum, &sender_pub_excess, Some(&pub_key_sum), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // Receiver now builds final signature from sender and receiver parts @@ -180,7 +180,7 @@ fn aggsig_sender_receiver_interaction() { let msg = kernel_sig_msg(); let our_sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_cx.sec_key, &rx_cx.sec_nonce, &pub_nonce_sum, @@ -191,7 +191,7 @@ fn aggsig_sender_receiver_interaction() { // Receiver now generates final signature from the two parts let final_sig = aggsig::add_signatures( - &keychain.secp(), + keychain.secp(), vec![&sender_sig_part, &our_sig_part], &pub_nonce_sum, ) @@ -217,13 +217,13 @@ fn aggsig_sender_receiver_interaction() { // Receiver check the final signature verifies let sig_verifies = aggsig::verify_completed_sig( - &keychain.secp(), + keychain.secp(), &final_sig, &final_pubkey, Some(&final_pubkey), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // Check we can verify the sig using the kernel excess @@ -231,9 +231,9 @@ fn aggsig_sender_receiver_interaction() { let keychain = ExtKeychain::from_random_seed(true).unwrap(); let msg = kernel_sig_msg(); let sig_verifies = - aggsig::verify_single_from_commit(&keychain.secp(), &final_sig, &msg, &kernel_excess); + aggsig::verify_single_from_commit(keychain.secp(), &final_sig, &msg, &kernel_excess); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } } @@ -247,7 +247,7 @@ fn aggsig_sender_receiver_interaction_offset() { // This is the kernel offset that we use to split the key // Summing these at the block level prevents the // kernels from being used to reconstruct (or identify) individual transactions - let kernel_offset = SecretKey::new(&sender_keychain.secp(), &mut thread_rng()); + let kernel_offset = SecretKey::new(sender_keychain.secp(), &mut thread_rng()); // Calculate the kernel excess here for convenience. // Normally this would happen during transaction building. @@ -270,7 +270,7 @@ fn aggsig_sender_receiver_interaction_offset() { keychain .secp() - .commit(0, blinding_factor.secret_key(&keychain.secp()).unwrap()) + .commit(0, blinding_factor.secret_key(keychain.secp()).unwrap()) .unwrap() }; @@ -294,10 +294,10 @@ fn aggsig_sender_receiver_interaction_offset() { ) .unwrap(); - let blind = blinding_factor.secret_key(&keychain.secp()).unwrap(); + let blind = blinding_factor.secret_key(keychain.secp()).unwrap(); - s_cx = Context::with_excess(&keychain.secp(), blind, &parent, false); - s_cx.get_public_keys(&keychain.secp()) + s_cx = Context::with_excess(keychain.secp(), blind, &parent, false); + s_cx.get_public_keys(keychain.secp()) }; // receiver receives partial tx @@ -309,8 +309,8 @@ fn aggsig_sender_receiver_interaction_offset() { let blind = keychain.derive_key(0, &key_id, switch).unwrap(); - rx_cx = Context::with_excess(&keychain.secp(), blind, &parent, false); - let (pub_excess, pub_nonce) = rx_cx.get_public_keys(&keychain.secp()); + rx_cx = Context::with_excess(keychain.secp(), blind, &parent, false); + let (pub_excess, pub_nonce) = rx_cx.get_public_keys(keychain.secp()); rx_cx.add_output(&key_id, &None, 0); pub_nonce_sum = PublicKey::from_combination( @@ -333,7 +333,7 @@ fn aggsig_sender_receiver_interaction_offset() { let msg = kernel_sig_msg(); let sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_cx.sec_key, &rx_cx.sec_nonce, &pub_nonce_sum, @@ -350,14 +350,14 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = sender_keychain.clone(); let msg = kernel_sig_msg(); let sig_verifies = aggsig::verify_partial_sig( - &keychain.secp(), + keychain.secp(), &sig_part, &pub_nonce_sum, &receiver_pub_excess, Some(&pub_key_sum), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // now sender signs with their key @@ -365,7 +365,7 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = sender_keychain.clone(); let msg = kernel_sig_msg(); let sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &s_cx.sec_key, &s_cx.sec_nonce, &pub_nonce_sum, @@ -382,14 +382,14 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = receiver_keychain.clone(); let msg = kernel_sig_msg(); let sig_verifies = aggsig::verify_partial_sig( - &keychain.secp(), + keychain.secp(), &sender_sig_part, &pub_nonce_sum, &sender_pub_excess, Some(&pub_key_sum), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // Receiver now builds final signature from sender and receiver parts @@ -397,7 +397,7 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = receiver_keychain.clone(); let msg = kernel_sig_msg(); let our_sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_cx.sec_key, &rx_cx.sec_nonce, &pub_nonce_sum, @@ -408,7 +408,7 @@ fn aggsig_sender_receiver_interaction_offset() { // Receiver now generates final signature from the two parts let final_sig = aggsig::add_signatures( - &keychain.secp(), + keychain.secp(), vec![&sender_sig_part, &our_sig_part], &pub_nonce_sum, ) @@ -434,13 +434,13 @@ fn aggsig_sender_receiver_interaction_offset() { // Receiver check the final signature verifies let sig_verifies = aggsig::verify_completed_sig( - &keychain.secp(), + keychain.secp(), &final_sig, &final_pubkey, Some(&final_pubkey), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // Check we can verify the sig using the kernel excess @@ -448,9 +448,9 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = ExtKeychain::from_random_seed(true).unwrap(); let msg = kernel_sig_msg(); let sig_verifies = - aggsig::verify_single_from_commit(&keychain.secp(), &final_sig, &msg, &kernel_excess); + aggsig::verify_single_from_commit(keychain.secp(), &final_sig, &msg, &kernel_excess); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } } diff --git a/src/bin/grin-wallet.rs b/src/bin/grin-wallet.rs index 709e704..2fdd427 100644 --- a/src/bin/grin-wallet.rs +++ b/src/bin/grin-wallet.rs @@ -58,8 +58,7 @@ pub fn info_strings() -> (String, String) { /// 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); - path + path.replace("/", sep).replace("\\", sep) } fn log_build_info() { @@ -103,16 +102,13 @@ fn real_main() -> i32 { } // special cases for certain lifecycle commands - match args.subcommand() { - ("init", Some(init_args)) => { - if init_args.is_present("here") { - current_dir = Some(env::current_dir().unwrap_or_else(|e| { - panic!("Error creating config file: {}", e); - })); - } - create_path = true; + if let ("init", Some(init_args)) = args.subcommand() { + if init_args.is_present("here") { + current_dir = Some(env::current_dir().unwrap_or_else(|e| { + panic!("Error creating config file: {}", e); + })); } - _ => {} + create_path = true; } // Load relevant config, try and load a wallet config file @@ -147,7 +143,7 @@ fn real_main() -> i32 { ); log_build_info(); - global::init_global_chain_type(config.members.wallet.chain_type.as_ref().unwrap().clone()); + global::init_global_chain_type(*config.members.wallet.chain_type.as_ref().unwrap()); global::init_global_accept_fee_base(config.members.wallet.accept_fee_base()); let wallet_config = config.clone().members.wallet; diff --git a/src/bin/grin-wallet.yml b/src/bin/grin-wallet.yml index 949a359..61cb5a4 100644 --- a/src/bin/grin-wallet.yml +++ b/src/bin/grin-wallet.yml @@ -21,7 +21,6 @@ args: short: a long: account takes_value: true - default_value: default - top_level_dir: help: Top directory in which wallet files are stored (location of 'grin-wallet.toml') short: t @@ -41,13 +40,24 @@ subcommands: - cli: about: Start the wallet in interactive CLI mode (EXPERIMENTAL and UNDER DEVELOPMENT) - account: - about: List wallet accounts or create a new account + about: List accounts, create an account or select the active account args: - create: help: Create a new wallet account with provided name short: c long: create takes_value: true + - minimum_confirmations: + help: Minimum number of confirmations required for an output to be spendable + short: m + long: min_conf + default_value: "10" + takes_value: true + - active: + help: Save the active account, used whenever --account is not given + short: a + long: active + takes_value: true - rewind_hash: about: Return the hash of the wallet root public key. - scan_rewind_hash: @@ -175,6 +185,41 @@ subcommands: - amount_includes_fee: help: Transaction amount includes transaction fee. Recipient will receive (amount - fee). long: amount_includes_fee + - address_index: + help: Slatepack address derivation path index + short: a + long: address_index + takes_value: true + - mwixnet: + about: EXPERIMENTAL - Swap a wallet output through an mwixnet route using Arti only + args: + - output: + help: Commitment or minimum amount of the wallet output to swap, or 'max' for the largest eligible output + index: 1 + required: true + - server: + help: Ed25519 identity key or .onion address of the first mwixnet server + long: server + takes_value: true + required: true + - key: + help: X25519 onion key of an mwixnet server, repeated in route order + long: key + takes_value: true + multiple: true + number_of_values: 1 + required: true + - fee_per_hop: + help: Fee per mwixnet server in Grin, e.g. 0.0125, with the swap minimum as default + long: fee_per_hop + takes_value: true + required: false + - minimum_confirmations: + help: Minimum confirmations required for the selected output + short: c + long: min_conf + default_value: "10" + takes_value: true - unpack: about: Unpack and display an armored Slatepack Message, decrypting if possible args: @@ -254,6 +299,11 @@ subcommands: help: Show slatepack data as QR code short: q long: slatepack_qr + - address_index: + help: Slatepack address derivation path index + short: a + long: address_index + takes_value: true - pay: about: Spend coins to pay the provided invoice transaction args: diff --git a/src/build/build.rs b/src/build/build.rs index 1d3d9bb..52307cc 100644 --- a/src/build/build.rs +++ b/src/build/build.rs @@ -14,7 +14,6 @@ //! Build hooks to spit out version+build time info -use built; use std::env; use std::path::{Path, PathBuf}; use std::process::Command; @@ -28,12 +27,12 @@ fn main() { if cfg!(target_os = "windows") { Command::new("cmd") - .args(&["/C", &git_hooks]) + .args(["/C", &git_hooks]) .output() .expect("failed to execute git config for hooks"); } else { Command::new("sh") - .args(&["-c", &git_hooks]) + .args(["-c", &git_hooks]) .output() .expect("failed to execute git config for hooks"); } diff --git a/src/cli/cli.rs b/src/cli/cli.rs index d410785..612518b 100644 --- a/src/cli/cli.rs +++ b/src/cli/cli.rs @@ -33,12 +33,11 @@ use rustyline::validate::Validator; use rustyline::{CompletionType, Config, Context, EditMode, Editor, Helper, OutputStreamType}; use std::borrow::Cow::{self, Borrowed, Owned}; use std::sync::mpsc::{channel, Receiver}; -use std::sync::Arc; use std::thread; use std::time::Duration; -const COLORED_PROMPT: &'static str = "\x1b[36mgrin-wallet>\x1b[0m "; -const PROMPT: &'static str = "grin-wallet> "; +const COLORED_PROMPT: &str = "\x1b[36mgrin-wallet>\x1b[0m "; +const PROMPT: &str = "grin-wallet> "; //const HISTORY_PATH: &str = ".history"; // static for keeping track of current stdin buffer contents @@ -109,7 +108,7 @@ pub fn start_updater_thread(rx: Receiver) -> Result<(), Error> { pub fn command_loop( config: GlobalWalletConfig, - wallet_inst: Arc>>>, + wallet_inst: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, keychain_mask: Option, global_wallet_args: &GlobalArgs, test_mode: bool, @@ -155,7 +154,7 @@ where start_updater_thread(rx)?; // start the automatic updater - owner_api.start_updater((&keychain_mask).as_ref(), Duration::from_secs(30))?; + owner_api.start_updater(keychain_mask.as_ref(), Duration::from_secs(30))?; let mut wallet_opened = false; loop { match reader.readline(PROMPT) { @@ -178,15 +177,14 @@ where // Just add 'grin-wallet' to each command behind the scenes // so we don't need to maintain a separate definition file let augmented_command = format!("grin-wallet {}", command); - let args = - app.get_matches_from_safe_borrow(augmented_command.trim().split_whitespace()); + let args = app.get_matches_from_safe_borrow(augmented_command.split_whitespace()); let done = match args { Ok(args) => { // handle opening /closing separately keychain_mask = match args.subcommand() { ("open", Some(_)) => { let mut wallet_lock = owner_api.wallet_inst.lock(); - let lc = wallet_lock.lc_provider().unwrap(); + let lc = wallet_lock.lc_provider()?; let mask = match lc.open_wallet( None, wallet_args::prompt_password(&global_wallet_args.password)?, @@ -202,17 +200,20 @@ where None } }; - if let Some(account) = args.value_of("account") { + if let Some(account) = args + .value_of("account") + .or(global_wallet_args.account.as_deref()) + { if wallet_opened { let wallet_inst = lc.wallet_inst()?; - wallet_inst.set_parent_key_id_by_name(account)?; + wallet_inst.set_account_by_name(account)?; } } mask } ("close", Some(_)) => { let mut wallet_lock = owner_api.wallet_inst.lock(); - let lc = wallet_lock.lc_provider().unwrap(); + let lc = wallet_lock.lc_provider()?; lc.close_wallet(None)?; None } @@ -227,7 +228,7 @@ where keychain_mask.clone(), &wallet_config, tor_config, - &global_wallet_args, + global_wallet_args, &args, test_mode, true, diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 7d24895..8ce0617 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[allow(clippy::module_inception)] mod cli; pub use cli::command_loop; diff --git a/src/cmd/wallet.rs b/src/cmd/wallet.rs index b30ed81..1f059d1 100644 --- a/src/cmd/wallet.rs +++ b/src/cmd/wallet.rs @@ -33,7 +33,7 @@ where { let json_output = wallet_args::contract_json_output(wallet_args); // Check the node version info, and exit with report if we're not compatible - let global_wallet_args = wallet_args::parse_global_args(&config.members.wallet, &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()); diff --git a/src/cmd/wallet_args.rs b/src/cmd/wallet_args.rs index fe52627..4a509d7 100644 --- a/src/cmd/wallet_args.rs +++ b/src/cmd/wallet_args.rs @@ -19,17 +19,24 @@ use crate::config::GRIN_WALLET_DIR; use crate::util::file::get_first_line; use crate::util::secp::key::SecretKey; use crate::util::{Mutex, ZeroingString}; -use clap::ArgMatches; + use grin_core as core; use grin_core::core::amount_to_hr_string; use grin_keychain as keychain; +use grin_util::secp::constants::PEDERSEN_COMMITMENT_SIZE; +use grin_util::secp::pedersen::Commitment; use grin_wallet_api::Owner; use grin_wallet_config::{GlobalWalletConfig, TorConfig, WalletConfig}; +use grin_wallet_controller::command::GlobalArgs; use grin_wallet_controller::{command, Error}; use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl}; use grin_wallet_libwallet::contract::types::{PaymentMemo, ProofType}; +use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey}; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; use grin_wallet_libwallet::{self, Slate, SlatepackAddress, SlatepackArmor}; use grin_wallet_libwallet::{IssueInvoiceTxArgs, NodeClient, WalletInst, WalletLCProvider}; + +use clap::ArgMatches; use linefeed::terminal::Signal; use linefeed::{Interface, ReadResult}; use rpassword; @@ -37,6 +44,7 @@ use std::convert::TryFrom; use std::io::{IsTerminal, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; +use uuid::Uuid; // define what to do on argument error macro_rules! arg_parse { @@ -105,7 +113,7 @@ fn prompt_password_confirm() -> Result { } fn prompt_recovery_phrase( - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, ) -> Result where DefaultWalletImpl: WalletInst<'static, L, C, K>, @@ -197,7 +205,7 @@ fn prompt_pay_invoice(slate: &Slate, dest: &str) -> Result { "* {} of your wallet funds will be added to the transaction to pay this invoice.", amount ); - if dest.len() > 0 { + if !dest.is_empty() { println!("* The wallet will IMMEDIATELY attempt to send the resulting transaction to the wallet listening at: '{}'.", dest); println!("* If other wallet is not listening, the resulting transaction will output as a slatepack which you can manually send back to the invoice creator."); } else { @@ -238,7 +246,7 @@ fn prompt_pay_invoice(slate: &Slate, dest: &str) -> Result { pub fn inst_wallet( config: WalletConfig, node_client: C, -) -> Result>>>, ParseError> +) -> Result, ParseError> where DefaultWalletImpl: WalletInst<'static, L, C, K>, L: WalletLCProvider<'static, C, K>, @@ -293,14 +301,7 @@ fn parse_u64(arg: &str, name: &str) -> Result { // As above, but optional fn parse_u64_or_none(arg: Option<&str>) -> Option { - let val = match arg { - Some(a) => a.parse::(), - None => return None, - }; - match val { - Ok(v) => Some(v), - Err(_) => None, - } + arg?.parse().ok() } // Parse a value expressed in Grin (e.g. "1.5") into nanograms. @@ -318,17 +319,18 @@ pub fn parse_global_args( config: &WalletConfig, args: &ArgMatches, ) -> Result { - let account = parse_required(args, "account")?; + let account = if args.subcommand_matches("account").is_some() { + None + } else { + parse_optional(args, "account")? + }; let mut show_spent = false; if args.is_present("show_spent") { show_spent = true; } let api_secret = get_first_line(config.api_secret_path.clone()); let node_api_secret = get_first_line(config.node_api_secret_path.clone()); - let password = match args.value_of("pass") { - None => None, - Some(p) => Some(ZeroingString::from(p)), - }; + let password = args.value_of("pass").map(ZeroingString::from); let tls_conf = match config.tls_certificate_file.clone() { None => None, @@ -345,7 +347,7 @@ pub fn parse_global_args( }; Ok(command::GlobalArgs { - account: account.to_owned(), + account, show_spent, api_secret, node_api_secret, @@ -355,7 +357,7 @@ pub fn parse_global_args( } pub fn parse_init_args( - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, config: &WalletConfig, g_args: &command::GlobalArgs, args: &ArgMatches, @@ -438,11 +440,24 @@ pub fn parse_scan_rewind_hash_args( } pub fn parse_account_args(account_args: &ArgMatches) -> Result { - let create = match account_args.value_of("create") { - None => None, - Some(s) => Some(s.to_owned()), - }; - Ok(command::AccountArgs { create }) + let create = account_args.value_of("create").map(|s| s.to_owned()); + + let active = account_args.value_of("active").map(|s| s.to_owned()); + + if create.is_some() && active.is_some() { + let msg = "create and active cannot both be present".to_string(); + return Err(ParseError::ArgumentError(msg)); + } + + // minimum_confirmations + let min_c = parse_required(account_args, "minimum_confirmations")?; + let min_c = parse_u64(min_c, "minimum_confirmations")?; + + Ok(command::AccountArgs { + create, + minimum_confirmations: min_c, + active, + }) } pub fn parse_send_args(args: &ArgMatches) -> Result { @@ -478,11 +493,7 @@ pub fn parse_send_args(args: &ArgMatches) -> Result Result Some(b.to_string()), - None => None, - }; + let bridge = args.value_of("bridge").map(|b| b.to_string()); let slatepack_qr = args.is_present("slatepack_qr"); + let address_index = parse_address_index_arg(args)?; + Ok(command::SendArgs { amount, amount_includes_fee, @@ -556,23 +566,90 @@ pub fn parse_send_args(args: &ArgMatches) -> Result Result, ParseError> { + let address = if let Some(i) = parse_optional(args, "address_index")? { + let val = i.parse::(); + match val { + Ok(v) => Some( + SlatepackAddressIndex(v) + .check() + .map_err(|e| ParseError::ArgumentError(e.to_string()))?, + ), + Err(e) => { + let msg = format!("Could not parse address_index as a whole number. e={}", e); + return Err(ParseError::ArgumentError(msg)); + } + } + } else { + None + }; + Ok(address) +} + +fn parse_mwixnet_output(output: &str) -> Result { + if output.eq_ignore_ascii_case("max") { + Ok(command::MwixnetOutput::Max) + } else if output.len() == PEDERSEN_COMMITMENT_SIZE * 2 { + let commitment = grin_util::from_hex(output) + .map_err(|e| ParseError::ArgumentError(format!("Invalid output commitment: {}", e)))?; + Ok(command::MwixnetOutput::Commitment(Commitment::from_vec( + commitment, + ))) + } else { + let amount = core::core::amount_from_hr_string(output).map_err(|e| { + ParseError::ArgumentError(format!( + "Output must be a commitment, an amount, or 'max': {}", + e + )) + })?; + Ok(command::MwixnetOutput::MinimumAmount(amount)) + } +} + +pub fn parse_mwixnet_args(args: &ArgMatches) -> Result { + let output = parse_mwixnet_output(parse_required(args, "output")?)?; + + let server = parse_required(args, "server")? + .try_into() + .map_err(|e| ParseError::ArgumentError(format!("Invalid mwixnet server: {}", e)))?; + let server_keys = args + .values_of("key") + .ok_or_else(|| { + ParseError::ArgumentError("At least one server key is required".to_string()) + })? + .map(|key| { + MwixnetServerPublicKey::from_hex(key).map_err(|e| { + ParseError::ArgumentError(format!("Invalid mwixnet server key: {}", e)) + }) + }) + .collect::, _>>()?; + let fee_per_hop = args + .value_of("fee_per_hop") + .map(core::core::amount_from_hr_string) + .transpose() + .map_err(|e| ParseError::ArgumentError(format!("Invalid fee_per_hop: {}", e)))?; + let minimum_confirmations = parse_u64( + parse_required(args, "minimum_confirmations")?, + "minimum_confirmations", + )?; + + Ok(command::MwixnetArgs { + server, + output, + minimum_confirmations, + params: MixnetReqCreationParams { + server_keys, + fee_per_hop, + }, }) } pub fn parse_receive_args(args: &ArgMatches) -> Result { - // input file - let input_file = match args.is_present("input") { - true => { - let file = args.value_of("input").unwrap().to_owned(); - // validate input - if !Path::new(&file).is_file() { - let msg = format!("File {} not found.", &file); - return Err(ParseError::ArgumentError(msg)); - } - Some(file) - } - false => None, - }; + let input_file = parse_input_file_arg(args)?; let mut input_slatepack_message = None; if input_file.is_none() { @@ -601,20 +678,24 @@ pub fn parse_receive_args(args: &ArgMatches) -> Result Result { - // input file +fn parse_input_file_arg(args: &ArgMatches) -> Result, ParseError> { let input_file = match args.is_present("input") { true => { let file = args.value_of("input").unwrap().to_owned(); // validate input if !Path::new(&file).is_file() { - let msg = format!("File {} not found.", &file); + let msg = format!("File {} not found.", file); return Err(ParseError::ArgumentError(msg)); } Some(file) } false => None, }; + Ok(input_file) +} + +pub fn parse_unpack_args(args: &ArgMatches) -> Result { + let input_file = parse_input_file_arg(args)?; let mut input_slatepack_message = None; if input_file.is_none() { @@ -647,18 +728,7 @@ pub fn parse_finalize_args(args: &ArgMatches) -> Result { - let file = args.value_of("input").unwrap().to_owned(); - // validate input - if !Path::new(&file).is_file() { - let msg = format!("File {} not found.", &file); - return Err(ParseError::ArgumentError(msg)); - } - Some(file) - } - false => None, - }; + let input_file = parse_input_file_arg(args)?; let mut input_slatepack_message = None; if input_file.is_none() { @@ -707,22 +777,21 @@ pub fn parse_issue_invoice_args( }; // dest, for encryption - let dest = if let Some(dest) = args.value_of("dest") { - Some(dest.to_owned()) - } else { - None - }; + let dest = args.value_of("dest").map(|dest| dest.to_owned()); let outfile = parse_optional(args, "outfile")?; let slatepack_qr = args.is_present("slatepack_qr"); + let address_index = parse_address_index_arg(args)?; + Ok(command::IssueInvoiceArgs { dest, issue_args: IssueInvoiceTxArgs { dest_acct_name: None, amount, target_slate_version, + address_index, }, outfile, slatepack_qr, @@ -744,7 +813,7 @@ where let file = args.value_of("input").unwrap().to_owned(); // validate input if !Path::new(&file).is_file() { - let msg = format!("File {} not found.", &file); + let msg = format!("File {} not found.", file); return Err(Error::GenericError(msg)); } Some(file) @@ -772,7 +841,7 @@ pub fn parse_process_invoice_args( args: &ArgMatches, prompt: bool, slate: Slate, - ret_address: Option, + mut ret_address: Option, ) -> Result { // minimum_confirmations let min_c = parse_required(args, "minimum_confirmations")?; @@ -791,9 +860,18 @@ pub fn parse_process_invoice_args( let max_outputs = 500; if prompt { - let dest = match ret_address.clone() { - Some(a) => String::try_from(&a).unwrap(), - None => String::from(""), + let dest = parse_optional(args, "dest")?; + let dest = match dest { + Some(dest) => { + ret_address = Some(SlatepackAddress::try_from(dest.as_str()).map_err(|e| { + ParseError::ArgumentError(format!("Can not parse destination address {}", e)) + })?); + dest + } + None => match ret_address.clone() { + Some(a) => String::try_from(&a).unwrap(), + None => String::from(""), + }, }; // Now we need to prompt the user whether they want to do this, prompt_pay_invoice(&slate, &dest)?; @@ -811,11 +889,7 @@ pub fn parse_process_invoice_args( let slatepack_qr = args.is_present("slatepack_qr"); - let ret_address = if let Some(a) = ret_address { - Some(a.to_string()) - } else { - None - }; + let ret_address = ret_address.map(|a| a.to_string()); Ok(command::ProcessInvoiceArgs { minimum_confirmations: min_c, @@ -861,16 +935,7 @@ pub fn parse_txs_args(args: &ArgMatches) -> Result None => None, Some(tx) => Some(parse_u64(tx, "id")? as u32), }; - let tx_slate_id = match args.value_of("txid") { - None => None, - Some(tx) => match tx.parse() { - Ok(t) => Some(t), - Err(e) => { - let msg = format!("Could not parse txid parameter. e={}", e); - return Err(ParseError::ArgumentError(msg)); - } - }, - }; + let tx_slate_id = parse_tx_slate_id_arg(args)?; if tx_id.is_some() && tx_slate_id.is_some() { let msg = "At most one of 'id' (-i) or 'txid' (-t) may be provided.".to_string(); return Err(ParseError::ArgumentError(msg)); @@ -886,22 +951,24 @@ pub fn parse_txs_args(args: &ArgMatches) -> Result }) } +fn parse_tx_slate_id_arg(args: &ArgMatches) -> Result, ParseError> { + let tx_slate_id = match args.value_of("txid") { + None => None, + Some(tx) => match tx.parse() { + Ok(t) => Some(t), + Err(e) => { + let msg = format!("Could not parse txid parameter. e={}", e); + return Err(ParseError::ArgumentError(msg)); + } + }, + }; + Ok(tx_slate_id) +} + pub fn parse_post_args(args: &ArgMatches) -> Result { let fluff = args.is_present("fluff"); - // input file - let input_file = match args.is_present("input") { - true => { - let file = args.value_of("input").unwrap().to_owned(); - // validate input - if !Path::new(&file).is_file() { - let msg = format!("File {} not found.", &file); - return Err(ParseError::ArgumentError(msg)); - } - Some(file) - } - false => None, - }; + let input_file = parse_input_file_arg(args)?; let mut input_slatepack_message = None; if input_file.is_none() { @@ -922,10 +989,7 @@ pub fn parse_repost_args(args: &ArgMatches) -> Result None, - Some(d) => Some(d.to_owned()), - }; + let dump_file = args.value_of("dumpfile").map(|d| d.to_owned()); Ok(command::RepostArgs { id: tx_id.unwrap(), @@ -970,16 +1034,7 @@ pub fn parse_export_proof_args(args: &ArgMatches) -> Result None, Some(tx) => Some(parse_u64(tx, "id")? as u32), }; - let tx_slate_id = match args.value_of("txid") { - None => None, - Some(tx) => match tx.parse() { - Ok(t) => Some(t), - Err(e) => { - let msg = format!("Could not parse txid parameter. e={}", e); - return Err(ParseError::ArgumentError(msg)); - } - }, - }; + let tx_slate_id = parse_tx_slate_id_arg(args)?; if tx_id.is_some() && tx_slate_id.is_some() { let msg = "At most one of 'id' (-i) or 'txid' (-t) may be provided.".to_string(); return Err(ParseError::ArgumentError(msg)); @@ -1096,7 +1151,7 @@ fn parse_contract_selection( pub fn parse_contract_new_args( args: &ArgMatches, - account: &String, + account: &Option, ) -> Result { // Optional: without --encrypt-for the contract slatepack is produced unencrypted. let counterparty_addr = args.value_of("encrypt-for").map(String::from); @@ -1107,7 +1162,7 @@ pub fn parse_contract_new_args( "You must specify either --receive or --send.", ))); }; - let src_acct_name = Some(String::from(account)); + let src_acct_name = account.clone(); let minimum_confirmations = parse_u64( parse_required(args, "minimum_confirmations")?, "minimum_confirmations", @@ -1199,7 +1254,7 @@ pub fn parse_contract_view_args( if !Path::new(&file).is_file() { return Err(ParseError::ArgumentError(format!( "File {} not found.", - &file + file ))); } Some(file) @@ -1253,17 +1308,11 @@ pub fn wallet_command( where C: NodeClient + 'static + Clone, F: FnOnce( - Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - C, - keychain::ExtKeychain, - >, - >, - >, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + C, + keychain::ExtKeychain, >, ), { @@ -1276,7 +1325,7 @@ where wallet_config.check_node_api_http_addr = sa.to_string().clone(); } - let global_wallet_args = arg_parse!(parse_global_args(&wallet_config, &wallet_args)); + let global_wallet_args = arg_parse!(parse_global_args(&wallet_config, wallet_args)); node_client.set_node_url(&wallet_config.check_node_api_http_addr); node_client.set_node_api_secret(global_wallet_args.node_api_secret.clone()); @@ -1312,37 +1361,35 @@ where wallet_inst_cb(wallet.clone()); // don't open wallet for certain lifecycle commands - let mut open_wallet = true; - match wallet_args.subcommand() { - ("init", Some(_)) => open_wallet = false, - ("recover", _) => open_wallet = false, - ("cli", _) => open_wallet = false, + let keychain_mask = match wallet_args.subcommand() { + ("init", Some(_)) => None, + ("recover", _) => None, + ("cli", _) => None, + ("unpack", Some(args)) => { + let args = arg_parse!(parse_unpack_args(args)); + let slatepack = command::read_slatepack(args)?; + let mask = if slatepack.is_encrypted() { + open_wallet(&wallet, &global_wallet_args, wallet_args)? + } else { + None + }; + command::unpack(wallet.clone(), mask.as_ref(), slatepack)?; + return Ok("unpack".to_string()); + } ("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()?; - open_wallet = wallet_args.is_present("pass") && lc.wallet_exists(None)?; - } - _ => {} - } - - let keychain_mask = match open_wallet { - true => { - let mut wallet_lock = wallet.lock(); - let lc = wallet_lock.lc_provider()?; - let mask = lc.open_wallet( - None, - prompt_password(&global_wallet_args.password)?, - false, - false, - )?; - if let Some(account) = wallet_args.value_of("account") { - let wallet_inst = lc.wallet_inst()?; - wallet_inst.set_parent_key_id_by_name(account)?; + let open = { + let mut wallet_lock = wallet.lock(); + let lc = wallet_lock.lc_provider()?; + wallet_args.is_present("pass") && lc.wallet_exists(None)? + }; + if open { + open_wallet(&wallet, &global_wallet_args, wallet_args)? + } else { + None } - mask } - false => None, + _ => open_wallet(&wallet, &global_wallet_args, wallet_args)?, }; let res = match wallet_args.subcommand() { @@ -1362,7 +1409,7 @@ where &wallet_config, tor_config, &global_wallet_args, - &wallet_args, + wallet_args, test_mode, false, ) @@ -1376,6 +1423,32 @@ where } } +fn open_wallet( + wallet: &grin_wallet_libwallet::WalletHandle<'static, L, C, K>, + global_wallet_args: &GlobalArgs, + wallet_args: &ArgMatches, +) -> Result, Error> +where + L: WalletLCProvider<'static, C, K> + 'static, + C: NodeClient + 'static, + K: keychain::Keychain + 'static, +{ + let mut wallet_lock = wallet.lock(); + let lc = wallet_lock.lc_provider()?; + let mask = lc.open_wallet( + None, + prompt_password(&global_wallet_args.password)?, + false, + false, + )?; + if let Some(account) = wallet_args.value_of("account") { + let wallet_inst = lc.wallet_inst()?; + wallet_inst.set_account_by_name(account)?; + } + Ok(mask) +} + +#[allow(clippy::too_many_arguments)] pub fn parse_and_execute( owner_api: &mut Owner, keychain_mask: Option, @@ -1392,7 +1465,7 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let km = (&keychain_mask).as_ref(); + let km = keychain_mask.as_ref(); if test_mode { owner_api.doctest_mode = true; @@ -1405,13 +1478,13 @@ where owner_api.wallet_inst.clone(), wallet_config, global_wallet_args, - &args, + args, test_mode, )); - command::init(owner_api, &global_wallet_args, a, test_mode) + command::init(owner_api, global_wallet_args, a, test_mode) } ("recover", Some(_)) => { - let a = arg_parse!(parse_recover_args(&global_wallet_args,)); + let a = arg_parse!(parse_recover_args(global_wallet_args,)); command::recover(owner_api, a) } ("listen", Some(args)) => { @@ -1419,11 +1492,7 @@ where 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 bridge = args.value_of("bridge").map(|bridge| bridge.into()); let use_tor = if args.is_present("no_tor") { Some(false) } else { @@ -1444,7 +1513,7 @@ where let mut c = wallet_config.clone(); let mut g = global_wallet_args.clone(); g.tls_conf = None; - arg_parse!(parse_owner_api_args(&mut c, &args)); + arg_parse!(parse_owner_api_args(&mut c, args)); command::owner_api(owner_api, keychain_mask, &c, &g, test_mode) } ("web", Some(_)) => command::owner_api( @@ -1456,7 +1525,7 @@ where ), ("rewind_hash", Some(_)) => command::rewind_hash(owner_api, km), ("scan_rewind_hash", Some(args)) => { - let a = arg_parse!(parse_scan_rewind_hash_args(&args)); + let a = arg_parse!(parse_scan_rewind_hash_args(args)); command::scan_rewind_hash( owner_api, a, @@ -1464,11 +1533,11 @@ where ) } ("account", Some(args)) => { - let a = arg_parse!(parse_account_args(&args)); + let a = arg_parse!(parse_account_args(args)); command::account(owner_api, km, a) } ("send", Some(args)) => { - let a = arg_parse!(parse_send_args(&args)); + let a = arg_parse!(parse_send_args(args)); command::send( owner_api, km, @@ -1478,29 +1547,32 @@ where test_mode, ) } + ("mwixnet", Some(args)) => { + let a = arg_parse!(parse_mwixnet_args(args)); + command::mwixnet(owner_api, km, a) + } ("receive", Some(args)) => { - let a = arg_parse!(parse_receive_args(&args)); - command::receive(owner_api, km, &global_wallet_args, a, tor_config, test_mode) + let a = arg_parse!(parse_receive_args(args)); + command::receive(owner_api, km, a, tor_config, test_mode) } ("unpack", Some(args)) => { - let a = arg_parse!(parse_unpack_args(&args)); - command::unpack(owner_api, km, a) + let a = arg_parse!(parse_unpack_args(args)); + let slatepack = command::read_slatepack(a)?; + command::unpack(owner_api.wallet_inst.clone(), km, slatepack) } ("finalize", Some(args)) => { - let a = arg_parse!(parse_finalize_args(&args)); + let a = arg_parse!(parse_finalize_args(args)); command::finalize(owner_api, km, a) } ("invoice", Some(args)) => { - let a = arg_parse!(parse_issue_invoice_args(&args)); + let a = arg_parse!(parse_issue_invoice_args(args)); command::issue_invoice_tx(owner_api, km, a) } ("pay", Some(args)) => { // get slate first let (slate, address) = get_slate(owner_api, km, args)?; - let a = arg_parse!(parse_process_invoice_args( - &args, !test_mode, slate, address - )); + let a = arg_parse!(parse_process_invoice_args(args, !test_mode, slate, address)); command::process_invoice( owner_api, km, @@ -1511,11 +1583,10 @@ where ) } ("info", Some(args)) => { - let a = arg_parse!(parse_info_args(&args)); + let a = arg_parse!(parse_info_args(args)); command::info( owner_api, km, - global_wallet_args, a, wallet_config.dark_background_color_scheme.unwrap_or(true), ) @@ -1523,42 +1594,41 @@ where ("outputs", Some(_)) => command::outputs( owner_api, km, - &global_wallet_args, + global_wallet_args, wallet_config.dark_background_color_scheme.unwrap_or(true), ), ("txs", Some(args)) => { - let a = arg_parse!(parse_txs_args(&args)); + let a = arg_parse!(parse_txs_args(args)); command::txs( owner_api, km, - &global_wallet_args, a, wallet_config.dark_background_color_scheme.unwrap_or(true), ) } ("post", Some(args)) => { - let a = arg_parse!(parse_post_args(&args)); + let a = arg_parse!(parse_post_args(args)); command::post(owner_api, km, a) } ("repost", Some(args)) => { - let a = arg_parse!(parse_repost_args(&args)); + let a = arg_parse!(parse_repost_args(args)); command::repost(owner_api, km, a) } ("cancel", Some(args)) => { - let a = arg_parse!(parse_cancel_args(&args)); + let a = arg_parse!(parse_cancel_args(args)); command::cancel(owner_api, km, a) } ("export_proof", Some(args)) => { - let a = arg_parse!(parse_export_proof_args(&args)); + let a = arg_parse!(parse_export_proof_args(args)); command::proof_export(owner_api, km, a) } ("verify_proof", Some(args)) => { - let a = arg_parse!(parse_verify_proof_args(&args)); + let a = arg_parse!(parse_verify_proof_args(args)); command::proof_verify(owner_api, km, a) } - ("address", Some(_)) => command::address(owner_api, &global_wallet_args, km), + ("address", Some(_)) => command::address(owner_api, km), ("scan", Some(args)) => { - let a = arg_parse!(parse_check_args(&args)); + let a = arg_parse!(parse_check_args(args)); command::scan(owner_api, km, a) } ("open", Some(_)) => { @@ -1599,3 +1669,75 @@ where } } } + +#[cfg(test)] +mod mwixnet_tests { + use super::*; + + #[test] + fn parses_mwixnet_optional_fee() { + let yaml = load_yaml!("../bin/grin-wallet.yml"); + let args = vec![ + "grin-wallet", + "mwixnet", + "max", + "--server", + "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion", + "--key", + "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + ]; + let matches = clap::App::from_yaml(yaml) + .get_matches_from_safe(args.clone()) + .unwrap(); + let parsed = parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap(); + assert_eq!(parsed.params.fee_per_hop, None); + + let mut custom_args = args; + custom_args.extend(["--fee_per_hop", "0.0125"]); + let matches = clap::App::from_yaml(yaml) + .get_matches_from_safe(custom_args) + .unwrap(); + let parsed = parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap(); + assert_eq!(parsed.params.fee_per_hop, Some(12_500_000)); + } + + #[test] + fn mwixnet_args() { + let yaml = load_yaml!("../bin/grin-wallet.yml"); + let key = "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a"; + for keys in [vec!["--key", key], vec!["--key", key, "--key", key]] { + let key_count = keys.len() / 2; + let mut args = vec![ + "grin-wallet", + "mwixnet", + "--server", + "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion", + ]; + args.extend(keys); + args.push("max"); + let matches = clap::App::from_yaml(yaml) + .get_matches_from_safe(args) + .unwrap(); + let parsed = + parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap(); + assert!(matches!(parsed.output, command::MwixnetOutput::Max)); + assert_eq!(parsed.params.server_keys.len(), key_count); + } + } + + #[test] + fn parses_mwixnet_output_selection() { + assert!(matches!( + parse_mwixnet_output("max").unwrap(), + command::MwixnetOutput::Max + )); + assert!(matches!( + parse_mwixnet_output("10").unwrap(), + command::MwixnetOutput::MinimumAmount(10_000_000_000) + )); + assert!(matches!( + parse_mwixnet_output(&format!("08{}", "00".repeat(32))).unwrap(), + command::MwixnetOutput::Commitment(_) + )); + } +} diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index 86f7675..92afa59 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -21,9 +21,11 @@ extern crate log; extern crate grin_wallet; use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy}; -use std::path::PathBuf; +use std::io::Write; +use std::process::{Command, Stdio}; use clap::App; +use std::sync::mpsc; use std::thread; use std::time::Duration; @@ -32,9 +34,23 @@ use grin_wallet_impls::DefaultLCProvider; mod common; use common::{clean_output_dir, execute_command, initial_setup_wallet, instantiate_wallet, setup}; +use grin_wallet_api::Owner; +use grin_wallet_libwallet::{OutputStatus, TxLogEntryType}; /// command line tests fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller::Error> { + let (logs_tx, logs_rx) = mpsc::sync_channel(100); + let panic_hook = std::panic::take_hook(); + grin_util::init_logger( + Some(grin_util::logger::LoggingConfig { + log_to_file: false, + stdout_log_level: log::Level::Error, + tui_running: Some(true), + ..Default::default() + }), + Some(logs_tx), + ); + std::panic::set_hook(panic_hook); setup(test_dir); // Create a new proxy to simulate server and wallet responses let mut wallet_proxy: WalletProxy< @@ -139,6 +155,39 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: ]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + // Check account selection through the CLI loop + let mut cli = Command::new(env!("CARGO_BIN_EXE_grin-wallet")) + .args([ + "-t", + &format!("{}/wallet2", test_dir), + "-p", + "password2", + "-a", + "account_1", + "-r", + "http://127.0.0.1:1", + "cli", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + cli.stdin.take().unwrap().write_all( + b"open\naddress\nclose\n-a default open\naddress\naccount -a account_1\naddress\nexit\n", + ).unwrap(); + let output = cli.wait_with_output().unwrap(); + assert!(output.status.success()); + let output = String::from_utf8(output.stdout).unwrap(); + let accounts: Vec<_> = output + .lines() + .filter_map(|line| { + line.split_once("Address for account - ") + .map(|(_, name)| name) + }) + .collect(); + assert_eq!(accounts, ["account_1", "default", "account_1"]); + // let's see those accounts let arg_vec = vec!["grin-wallet", "-p", "password1", "account"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; @@ -147,21 +196,20 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let arg_vec = vec!["grin-wallet", "-p", "password2", "account"]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + // Return an explained error when trying to send max amount on empty wallet. + let arg_vec = vec!["grin-wallet", "-p", "password2", "send", "max"]; + let err = execute_command(&app, test_dir, "wallet2", &client2, arg_vec).unwrap_err(); + assert!(format!("{}", err).contains("No spendable funds")); + // 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.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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - Ok(()) - }, - )?; + let mask1 = mask1_i.as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); + + api1.set_active_account(mask1, "mining")?; let mut bh = 10u64; let _ = @@ -187,6 +235,12 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; + let args = vec!["grin-wallet", "-p", "unused", "unpack", "-i", &file_name]; + assert_eq!( + execute_command(&app, test_dir, "wallet1", &client1, args)?, + "unpack" + ); + let arg_vec = vec!["grin-wallet", "-a", "mining", "-p", "password1", "txs"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; @@ -200,7 +254,35 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "-i", &file_name, ]; - execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; + // Reuse startup args as in interactive mode + { + let start = app + .clone() + .get_matches_from(vec!["grin-wallet", "-a", "default", "cli"]); + let global_args = + grin_wallet::cmd::wallet_args::parse_global_args(&wallet_config2, &start).unwrap(); + let mut api = Owner::new(wallet2.clone(), None, config2.config_file_path.clone()); + for command in [ + vec!["grin-wallet", "account", "-a", "account_1"], + vec!["grin-wallet", "address"], + vec!["grin-wallet", "receive", "-i", &file_name], + ] { + let args = app.clone().get_matches_from(command); + grin_wallet::cmd::wallet_args::parse_and_execute( + &mut api, + mask2_i.clone(), + &wallet_config2, + config2.tor_config(), + &global_args, + &args, + true, + true, + )?; + } + let (_, txs) = api.retrieve_txs(mask2_i.as_ref(), false, None, None, None)?; + assert_eq!(txs.len(), 1); + api.set_active_account(mask2_i.as_ref(), "default")?; + } // shouldn't be allowed to receive twice assert!(execute_command(&app, test_dir, "wallet2", &client2, arg_vec).is_err()); @@ -230,24 +312,17 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "password1", "default", )?; - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); // Check our transaction log, should have 10 entries - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len(), bh as usize); - for t in txs { - assert!(t.kernel_excess.is_some()); - } - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), bh as usize); + for t in txs { + assert!(t.kernel_excess.is_some()); + } let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false); bh += 10; @@ -267,34 +342,18 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "password2", "default", )?; - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); + let api2 = Owner::new(wallet2.clone(), None, config2.config_file_path.clone()); - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "account_1")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.amount_currently_spendable, 10_000_000_000); - Ok(()) - }, - )?; + api2.set_active_account(mask2, "account_1")?; + let (_, wallet1_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.amount_currently_spendable, 10_000_000_000); // Send to wallet 2 with --amount_includes_fee - let mut old_balance = 0; - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - old_balance = wallet1_info.amount_currently_spendable; - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let old_balance = wallet1_info.amount_currently_spendable; let arg_vec = vec![ "grin-wallet", "-p", @@ -344,22 +403,14 @@ 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - // make sure the new balance is exactly equal to the old balance - the tx amount + the amount mined since then - let amt_mined = 10 * 60_000_000_000; - assert_eq!( - wallet1_info.amount_currently_spendable + 10_000_000_000, - old_balance + amt_mined - ); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + // make sure the new balance is exactly equal to the old balance - the tx amount + the amount mined since then + let amt_mined = 10 * 60_000_000_000; + assert_eq!( + wallet1_info.amount_currently_spendable + 10_000_000_000, + old_balance + amt_mined + ); // Send encrypted from wallet 1 to wallet 2 // output wallet 2's address for test creation purposes, @@ -429,20 +480,13 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "password1", "default", )?; - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len(), bh as usize); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), bh as usize); // Send to self let arg_vec = vec![ @@ -502,20 +546,13 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "password1", "default", )?; - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len(), bh as usize + 1); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), bh as usize + 1); // Another file exchange, don't send, but unlock with repair command let arg_vec = vec![ @@ -559,6 +596,10 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; + // set default account for wallet2 + let arg_vec = vec!["grin-wallet", "-p", "password2", "account", "-a", "default"]; + execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + // issue an invoice tx, wallet 2 let arg_vec = vec!["grin-wallet", "-p", "password2", "invoice", "65"]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; @@ -644,24 +685,15 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; // get tx output via -tx parameter - let mut tx_id = "".to_string(); - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - 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_string().clone(); - Ok(()) - }, - )?; + api2.set_active_account(mask2, "default")?; + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + let some_tx_id = txs[0].tx_slate_id; + assert!(some_tx_id.is_some()); + let tx_id = some_tx_id.unwrap().to_string().clone(); let arg_vec = vec!["grin-wallet", "-p", "password2", "txs", "-t", &tx_id[..]]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; - // bit of mining + // a bit of mining let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false); // Test wallet sweep @@ -712,21 +744,198 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // Check wallet 1 is now empty, except for immature coinbase outputs from recent mining), // 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( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 10)?; - // Entire 'spendable' wallet balance should have been swept, except the coinbase outputs - // which matured in the last batch of mining. Check that the new spendable balance is - // exactly equal to those matured coins. - let amt_mined = 10 * 60_000_000_000; - assert_eq!(wallet1_info.amount_currently_spendable, amt_mined); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 10)?; + // Entire 'spendable' wallet balance should have been swept, except the coinbase outputs + // which matured in the last batch of mining. Check that the new spendable balance is + // exactly equal to those matured coins. + let amt_mined = 10 * 60_000_000_000; + assert_eq!(wallet1_info.amount_currently_spendable, amt_mined); + + // Failed send, with --late-lock, make sure outputs not locked (amount not changed). + api2.set_active_account(mask2, "account_1")?; + let (_, txs_before) = api2.retrieve_txs(mask2, false, None, None, None)?; + let (_, wallet1_info) = api2.retrieve_summary_info(mask2, true, 1)?; + let old_balance = wallet1_info.amount_currently_spendable; + let mut arg_vec = vec![ + "grin-wallet", + "-p", + "password2", + "-a", + "account_1", + "send", + "-d", + "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp", + "1", + "--late-lock", + ]; + let args = app.clone().get_matches_from(arg_vec.clone()); + let mut config = initial_setup_wallet(test_dir, "wallet2"); + config.members.tor = Some(grin_wallet_config::TorConfig { + use_integrated: Some(false), + socks_proxy_addr: "invalid".into(), + ..Default::default() + }); + let send = |args: &clap::ArgMatches| -> Result<(), grin_wallet_controller::Error> { + logs_rx.try_iter().for_each(drop); + grin_wallet::cmd::wallet_args::wallet_command( + args, + config.clone(), + client2.clone(), + false, + |_| {}, + )?; + assert!(logs_rx.try_iter().any(|entry| { + entry.log.contains("Error sending slate sync:") && entry.log.contains("AddrParseError") + })); + Ok(()) + }; + send(&args)?; + api2.set_active_account(mask2, "account_1")?; + let (_, txs_after) = api2.retrieve_txs(mask2, false, None, None, None)?; + assert_eq!(txs_before.len(), txs_after.len()); + let (_, wallet1_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert_eq!(old_balance, wallet1_info.amount_currently_spendable); + + // The same failure without late locking leaves one transaction and locked outputs + arg_vec.pop(); + let args = app.clone().get_matches_from(arg_vec); + send(&args)?; + let (_, txs_after) = api2.retrieve_txs(mask2, false, None, None, None)?; + assert_eq!(txs_after.len(), txs_before.len() + 1); + let tx = txs_after + .iter() + .find(|tx| !txs_before.iter().any(|before| before.id == tx.id)) + .unwrap(); + assert_eq!(tx.tx_type, TxLogEntryType::TxSent); + assert!(tx.tx_slate_id.is_some()); + let (_, outputs) = api2.retrieve_outputs(mask2, false, false, Some(tx.id))?; + assert!(outputs + .iter() + .any(|output| output.output.status == OutputStatus::Locked)); + let (_, wallet_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet_info.amount_currently_spendable < old_balance); + + // Issue encrypted invoice using custom address index, wallet2. + let arg_vec = vec![ + "grin-wallet", + "-a", + "default", + "-p", + "password2", + "invoice", + "--address_index", + "3", + "-d", + "tgrin1fu5z9y4p8atxr83l6nfj0j2m067r9gjfkd6mzeuuz0v6sqftua2quv0ll3", + "1", + ]; + execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + let file_name = format!( + "{}/wallet2/slatepack/0436430c-2b02-624c-2032-570501212b08.I1.slatepack", + test_dir + ); + + // Pay the invoice tx, wallet 1 + let arg_vec = vec![ + "grin-wallet", + "-a", + "default", + "-p", + "password1", + "pay", + "-i", + &file_name, + ]; + execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; + + let file_name = format!( + "{}/wallet1/slatepack/0436430c-2b02-624c-2032-570501212b08.I2.slatepack", + test_dir + ); + + // Finalize the invoice, wallet 2 + let arg_vec = vec![ + "grin-wallet", + "-a", + "default", + "-p", + "password2", + "finalize", + "-i", + &file_name, + ]; + execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + + // Send encrypted to wallet 2 using custom address index + let arg_vec = vec![ + "grin-wallet", + "-p", + "password1", + "-a", + "mining", + "send", + "-d", + "tgrin1ak8aaxpjg6ct5uje4lgzvjp65l0nrmgxndp5xjy74sumzp7wasysje3kmf", + "--address_index", + "5", + "1", + ]; + execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; + + // Receive, wallet 2 + let file_name = format!( + "{}/wallet1/slatepack/0436430c-2b02-624c-2032-570501212b09.S1.slatepack", + test_dir + ); + for (wallet, password, account, client) in [ + ("wallet1", "password1", "mining", &client1), + ("wallet2", "password2", "account_1", &client2), + ] { + let args = vec![ + "grin-wallet", + "-p", + password, + "-a", + account, + "unpack", + "-i", + &file_name, + ]; + assert_eq!( + execute_command(&app, test_dir, wallet, client, args)?, + "unpack" + ); + } + let arg_vec = vec![ + "grin-wallet", + "-p", + "password2", + "-a", + "account_1", + "receive", + "-i", + &file_name, + ]; + execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; + + let file_name = format!( + "{}/wallet2/slatepack/0436430c-2b02-624c-2032-570501212b09.S2.slatepack", + test_dir + ); + + // Finalize the send, wallet 1 + let arg_vec = vec![ + "grin-wallet", + "-a", + "mining", + "-p", + "password1", + "finalize", + "-i", + &file_name, + ]; + execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; // let logging finish thread::sleep(Duration::from_millis(200)); diff --git a/tests/cmd_line_contract.rs b/tests/cmd_line_contract.rs index af75662..381e5b1 100644 --- a/tests/cmd_line_contract.rs +++ b/tests/cmd_line_contract.rs @@ -101,8 +101,8 @@ fn contract_command_test_impl(test_dir: &str) -> Result<(), grin_wallet_controll }); // Mine into wallet 1 so it has something to send - let mask1 = (&mask1_i).as_ref(); - let mask2 = (&mask2_i).as_ref(); + let mask1 = mask1_i.as_ref(); + let mask2 = mask2_i.as_ref(); let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); let fee_rate = 2 * grin_core::global::get_accept_fee_base(); let expected_fee = Transaction::weight_by_iok(1, 1, 0) * fee_rate @@ -131,17 +131,19 @@ fn contract_command_test_impl(test_dir: &str) -> Result<(), grin_wallet_controll assert!(std::path::Path::new(&file_name).is_file()); // Wallet 2 views the contract before signing it - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - std::path::PathBuf::from(test_dir), - |api, m| { - let message = std::fs::read_to_string(&file_name)?; - let slate = api.slate_from_slatepack_message(m, message, vec![0])?; - assert_eq!(slate.fee_fields.fee(), expected_fee); - Ok(()) - }, - )?; + { + let api = + grin_wallet_api::Owner::new(wallet1.clone(), None, std::path::PathBuf::from(test_dir)); + let m = mask1; + let message = + std::fs::read_to_string(&file_name).map_err(grin_wallet_libwallet::Error::from)?; + let slate = api.slate_from_slatepack_message( + m, + message, + vec![grin_wallet_libwallet::slatepack::SlatepackAddressIndex(0)], + )?; + assert_eq!(slate.fee_fields.fee(), expected_fee); + } let arg_vec = vec![ "grin-wallet", "-p", @@ -166,16 +168,19 @@ fn contract_command_test_impl(test_dir: &str) -> Result<(), grin_wallet_controll execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; // Wallet 2 can also view a proof-bearing slatepack encrypted for its address - let mut recipient = None; - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - std::path::PathBuf::from(test_dir), - |api, m| { - recipient = Some(api.get_slatepack_address(m, 0)?.to_string()); - Ok(()) - }, - )?; + let recipient; + { + let api = + grin_wallet_api::Owner::new(wallet2.clone(), None, std::path::PathBuf::from(test_dir)); + let m = mask2; + recipient = Some( + api.get_slatepack_address( + m, + grin_wallet_libwallet::slatepack::SlatepackAddressIndex(0), + )? + .to_string(), + ); + } std::fs::remove_file(file_name).unwrap(); let recipient = recipient.unwrap(); let arg_vec = vec![ @@ -213,18 +218,21 @@ fn contract_command_test_impl(test_dir: &str) -> Result<(), grin_wallet_controll // slatepack for another account needs --account let arg_vec = vec!["grin-wallet", "-p", "password1", "account", "-c", "second"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; - let mut second = None; - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - std::path::PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "second")?; - second = Some(api.get_slatepack_address(m, 0)?.to_string()); - api.set_active_account(m, "default")?; - Ok(()) - }, - )?; + let second; + { + let api = + grin_wallet_api::Owner::new(wallet1.clone(), None, std::path::PathBuf::from(test_dir)); + let m = mask1; + api.set_active_account(m, "second")?; + second = Some( + api.get_slatepack_address( + m, + grin_wallet_libwallet::slatepack::SlatepackAddressIndex(0), + )? + .to_string(), + ); + api.set_active_account(m, "default")?; + } let second = second.unwrap(); let arg_vec = vec![ "grin-wallet", @@ -313,7 +321,11 @@ fn rejects_conflicting_input_options() { let contract = args.subcommand_matches("contract").unwrap(); let new_args = contract.subcommand_matches("new").unwrap(); - assert!(grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &account).is_err()); + assert!(grin_wallet::cmd::wallet_args::parse_contract_new_args( + new_args, + &Some(account.clone()) + ) + .is_err()); let args = app .get_matches_from_safe(vec![ @@ -360,7 +372,8 @@ fn parses_contract_options() { let contract = args.subcommand_matches("contract").unwrap(); let new_args = contract.subcommand_matches("new").unwrap(); let parsed = - grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &account).unwrap(); + grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &Some(account.clone())) + .unwrap(); assert_eq!(parsed.minimum_confirmations, 3); assert_eq!(parsed.fee_rate, Some(2)); assert_eq!(parsed.ttl_blocks, Some(20)); @@ -391,7 +404,7 @@ fn parses_contract_options() { .subcommand_matches("new") .unwrap(); assert!(matches!( - grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &account), + grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &Some(account.clone())), Err(grin_wallet::cmd::wallet_args::ParseError::ArgumentError(message)) if message.contains("Payment memo exceeds 1024 bytes") )); @@ -404,7 +417,8 @@ fn parses_contract_options() { let contract = args.subcommand_matches("contract").unwrap(); let new_args = contract.subcommand_matches("new").unwrap(); let parsed = - grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &account).unwrap(); + grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &Some(account.clone())) + .unwrap(); assert_eq!(parsed.minimum_confirmations, expected); assert_eq!(parsed.fee_rate, None); assert_eq!(parsed.ttl_blocks, None); @@ -414,7 +428,10 @@ fn parses_contract_options() { .unwrap(); let contract = args.subcommand_matches("contract").unwrap(); let new_args = contract.subcommand_matches("new").unwrap(); - let err = match grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &account) { + let err = match grin_wallet::cmd::wallet_args::parse_contract_new_args( + new_args, + &Some(account.clone()), + ) { Err(err) => err, Ok(_) => panic!("zero contract TTL accepted"), }; @@ -445,9 +462,12 @@ fn parses_contract_options() { .unwrap() .subcommand_matches("new") .unwrap(); - let err = grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &account) - .err() - .expect("invalid contract fee rate accepted"); + let err = grin_wallet::cmd::wallet_args::parse_contract_new_args( + new_args, + &Some(account.clone()), + ) + .err() + .expect("invalid contract fee rate accepted"); assert_eq!( err, grin_wallet::cmd::wallet_args::ParseError::ArgumentError(message.to_string()) @@ -529,7 +549,8 @@ fn selection_locks_early() { let args = app.clone().get_matches_from_safe(command).unwrap(); let contract = args.subcommand_matches("contract").unwrap(); let new_args = contract.subcommand_matches("new").unwrap(); - grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &account).unwrap() + grin_wallet::cmd::wallet_args::parse_contract_new_args(new_args, &Some(account.clone())) + .unwrap() }; assert!(!parse(&[]).add_outputs); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 85cbe74..b5a4264 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -160,7 +160,7 @@ pub fn config_command_wallet( let mut config_file_name = current_dir.clone(); config_file_name.push("grin-wallet.toml"); if config_file_name.exists() { - return Err(grin_wallet_controller::Error::ArgumentError( + Err(grin_wallet_controller::Error::ArgumentError( "grin-wallet.toml already exists in the target directory. Please remove it first" .to_owned(), ))?; @@ -217,6 +217,7 @@ fn get_wallet_subcommand<'a>( /// Helper to create an instance of the LMDB wallet #[allow(dead_code)] +#[allow(clippy::type_complexity)] pub fn instantiate_wallet( mut wallet_config: WalletConfig, node_client: LocalWalletClient, @@ -224,24 +225,18 @@ pub fn instantiate_wallet( account: &str, ) -> Result< ( - Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, >, Option, ), grin_wallet_controller::Error, > { wallet_config.chain_type = None; - let mut wallet = Box::new(DefaultWalletImpl::::new(node_client).unwrap()) + let mut wallet = Box::new(DefaultWalletImpl::::new(node_client)?) as Box< dyn WalletInst< DefaultLCProvider, @@ -249,7 +244,7 @@ pub fn instantiate_wallet( ExtKeychain, >, >; - let lc = wallet.lc_provider().unwrap(); + let lc = wallet.lc_provider()?; // legacy hack to avoid the need for changes in existing grin-wallet.toml files // remove `wallet_data` from end of path as // new lifecycle provider assumes grin_wallet.toml is in root of data directory @@ -259,11 +254,9 @@ pub fn instantiate_wallet( wallet_config.data_file_dir = top_level_wallet_dir.to_str().unwrap().into(); } let _ = lc.set_top_level_directory(&wallet_config.data_file_dir); - let keychain_mask = lc - .open_wallet(None, ZeroingString::from(passphrase), true, false) - .unwrap(); + let keychain_mask = lc.open_wallet(None, ZeroingString::from(passphrase), true, false)?; let wallet_inst = lc.wallet_inst()?; - wallet_inst.set_parent_key_id_by_name(account)?; + wallet_inst.set_account_by_name(account)?; Ok((Arc::new(Mutex::new(wallet)), keychain_mask)) } @@ -294,13 +287,21 @@ pub fn execute_command_no_setup( where C: NodeClient + 'static + Clone, F: FnOnce( - Arc, C, ExtKeychain>>>>, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + C, + ExtKeychain, + >, ), { let args = app.clone().get_matches_from(arg_vec); let _ = get_wallet_subcommand(test_dir, wallet_name, args.clone()); + // Avoid conflicts with local wallets + let wallet_dir = PathBuf::from(test_dir).join(format!("{}_bootstrap", wallet_name)); let mut config = - config::initial_setup_wallet(&ChainTypes::AutomatedTesting, None, true).unwrap(); + config::initial_setup_wallet(&ChainTypes::AutomatedTesting, Some(wallet_dir), true) + .unwrap(); let mut wallet_config = config.clone().members.wallet; wallet_config.chain_type = None; wallet_config.api_secret_path = None; @@ -374,7 +375,7 @@ where { let url = Url::parse(dest).unwrap(); let req_val: Value = serde_json::from_str(req).unwrap(); - let req = EncryptedRequest::from_json(sec_req_id, &req_val, &shared_key).unwrap(); + let req = EncryptedRequest::from_json(sec_req_id, &req_val, shared_key).unwrap(); let res = post(&url, None, &req).map_err(|e| { let err_string = format!("{}", e); println!("{}", err_string); @@ -446,7 +447,7 @@ pub fn derive_ecdh_key(sec_key_str: &str, other_pubkey: &PublicKey) -> SecretKey let secp_inst = static_secp_instance(); let secp = secp_inst.lock(); - let mut shared_pubkey = other_pubkey.clone(); + let mut shared_pubkey = *other_pubkey; shared_pubkey.mul_assign(&secp, &sec_key).unwrap(); let x_coord = shared_pubkey.serialize_vec(&secp, true); @@ -462,7 +463,7 @@ pub struct WalletAPIReturnError { impl std::fmt::Display for WalletAPIReturnError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{} - {}", self.code, &self.message) + write!(f, "{} - {}", self.code, self.message) } } diff --git a/tests/owner_v3_init_secure.rs b/tests/owner_v3_init_secure.rs index 1c636ef..5a02f99 100644 --- a/tests/owner_v3_init_secure.rs +++ b/tests/owner_v3_init_secure.rs @@ -30,7 +30,6 @@ use grin_keychain::ExtKeychain; use grin_util::secp::key::SecretKey; use grin_util::{from_hex, static_secp_instance}; use grin_wallet_impls::DefaultLCProvider; -use serde_json; #[macro_use] mod common; @@ -80,7 +79,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::IntId(1), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &sec_key, )?; println!("RES 1: {:?}", res); @@ -88,7 +87,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { assert_eq!(res.unwrap_err().code, -32001); // 2) Call any function on the V3 api without calling 'init_secure_api` first - let res = send_request::(1, "http://127.0.0.1:33420/v3/owner", &req)?; + let res = send_request::(1, "http://127.0.0.1:33420/v3/owner", req)?; println!("RES 2: {:?}", res); assert!(res.is_err()); assert_eq!(res.unwrap_err().code, -32001); @@ -108,7 +107,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 4: {:?}", res); @@ -122,7 +121,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &bad_key, )?; println!("RES 5: {:?}", res); @@ -164,7 +163,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req.to_string(), + req, &shared_key, )?; println!("RES 8: {:?}", res); @@ -178,7 +177,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 9: {:?}", res); @@ -199,7 +198,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 11: {:?}", res); @@ -232,7 +231,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("13")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 13: {:?}", res); diff --git a/tests/owner_v3_lifecycle.rs b/tests/owner_v3_lifecycle.rs index 997bdb3..3369dd1 100644 --- a/tests/owner_v3_lifecycle.rs +++ b/tests/owner_v3_lifecycle.rs @@ -19,7 +19,7 @@ extern crate log; extern crate grin_wallet; -use grin_wallet_api::{ECDHPubkey, JsonId}; +use grin_wallet_api::{ECDHPubkey, JsonId, Owner}; use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy}; use clap::App; @@ -30,7 +30,6 @@ 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; use grin_util::Mutex; use std::path::PathBuf; @@ -55,6 +54,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { let app = App::from_yaml(yml); // Create a new proxy to simulate server and wallet responses + #[allow(clippy::type_complexity)] let wallet_proxy_a: Arc< Mutex< WalletProxy< @@ -64,7 +64,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { >, >, > = Arc::new(Mutex::new(WalletProxy::new(test_dir))); - let (chain, wallet2, mask2_i) = { + let (chain, wallet2, mask2_i, config2) = { let mut wallet_proxy = wallet_proxy_a.lock(); let chain = wallet_proxy.chain.clone(); @@ -118,11 +118,11 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { ) .unwrap(); }); - (chain, wallet2, mask2_i) + (chain, wallet2, mask2_i, config2) }; // give a bit for wallet to init and populate proxy with wallet via callback in thread above thread::sleep(Duration::from_millis(500)); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); let wallet_proxy = wallet_proxy_a.clone(); // Set the wallet proxy listener running @@ -148,18 +148,24 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { let value: ECDHPubkey = res.unwrap(); let shared_key = derive_ecdh_key(sec_key_str, &value.ecdh_pubkey); - // 2) get the top level directory, should default to ~/.grin/auto + // 2) get the top level directory let req = include_str!("data/v3_reqs/get_top_level.req.json"); let res = send_request_enc::( &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 2: {:?}", res); assert!(res.is_ok()); - assert!(res.unwrap().contains("auto")); + assert_eq!( + PathBuf::from(res.unwrap()).canonicalize().unwrap(), + PathBuf::from(test_dir) + .join("wallet1_bootstrap") + .canonicalize() + .unwrap() + ); // 3) now set the top level directory to our test wallet dir let req = serde_json::json!({ @@ -186,7 +192,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 4: {:?}", res); @@ -220,7 +226,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 5: {:?}", res); @@ -232,7 +238,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 6: {:?}", res); @@ -244,7 +250,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 7: {:?}", res); @@ -256,7 +262,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 8: {:?}", res); @@ -313,7 +319,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 11: {:?}", res); @@ -347,7 +353,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 13: {:?}", res); @@ -402,27 +408,20 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { let mut slate: Slate = res.unwrap().into(); // give this slate over to wallet 2 manually - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 1, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let res = api.process_invoice_tx(m, &slate, args); - assert!(res.is_ok()); - slate = res.unwrap(); - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + let api2 = Owner::new(wallet2.clone(), None, config2.config_file_path.clone()); + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let res = api2.process_invoice_tx(mask2, &slate, args); + assert!(res.is_ok()); + slate = res?; + api2.tx_lock_outputs(mask2, &slate)?; //16) Finalize the invoice tx (to foreign api) // (Tests that foreign API on same port also has its stored mask updated) @@ -445,7 +444,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 17: {:?}", res); @@ -456,7 +455,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 17a: {:?}", res); @@ -468,7 +467,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 18: {:?}", res); @@ -586,7 +585,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; assert!(res.is_ok()); @@ -596,7 +595,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 24: {:?}", res); @@ -608,7 +607,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 25: {:?}", res); @@ -620,7 +619,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 26: {:?}", res); @@ -632,7 +631,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 27: {:?}", res); diff --git a/util/Cargo.toml b/util/Cargo.toml index 898522d..a5d48bb 100644 --- a/util/Cargo.toml +++ b/util/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_util" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Util, for generic utilities and to re-export grin crates" license = "Apache-2.0" @@ -19,6 +19,6 @@ thiserror = "1" ##### Grin Imports -grin_util = { path = "../grin/util"} +grin_util = { workspace = true } ###### diff --git a/util/src/byte_ser.rs b/util/src/byte_ser.rs index 8e5a936..7b9a7f7 100644 --- a/util/src/byte_ser.rs +++ b/util/src/byte_ser.rs @@ -63,7 +63,7 @@ where Ok(serializer.output) } -impl<'a> ser::Serializer for &'a mut ByteSerializer { +impl ser::Serializer for &mut ByteSerializer { type Ok = (); type Error = Error; type SerializeSeq = Self; @@ -226,7 +226,7 @@ impl<'a> ser::Serializer for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeSeq for &'a mut ByteSerializer { +impl ser::SerializeSeq for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -242,7 +242,7 @@ impl<'a> ser::SerializeSeq for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeTuple for &'a mut ByteSerializer { +impl ser::SerializeTuple for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -258,7 +258,7 @@ impl<'a> ser::SerializeTuple for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeTupleStruct for &'a mut ByteSerializer { +impl ser::SerializeTupleStruct for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -274,7 +274,7 @@ impl<'a> ser::SerializeTupleStruct for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeTupleVariant for &'a mut ByteSerializer { +impl ser::SerializeTupleVariant for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -290,7 +290,7 @@ impl<'a> ser::SerializeTupleVariant for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeMap for &'a mut ByteSerializer { +impl ser::SerializeMap for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -313,7 +313,7 @@ impl<'a> ser::SerializeMap for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeStruct for &'a mut ByteSerializer { +impl ser::SerializeStruct for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -329,7 +329,7 @@ impl<'a> ser::SerializeStruct for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeStructVariant for &'a mut ByteSerializer { +impl ser::SerializeStructVariant for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -366,7 +366,7 @@ where Ok(t) } -impl<'de, 'a> de::Deserializer<'de> for &'a mut ByteDeserializer<'de> { +impl<'de> de::Deserializer<'de> for &mut ByteDeserializer<'de> { type Error = Error; fn deserialize_any(self, visitor: V) -> Result