diff --git a/.cargo/config.toml b/.cargo/config.toml deleted file mode 100644 index 393611e..0000000 --- a/.cargo/config.toml +++ /dev/null @@ -1,3 +0,0 @@ -[alias] -bd = "make android-dev32" -br = "make" diff --git a/.gitignore b/.gitignore index 557066e..d1ed909 100644 --- a/.gitignore +++ b/.gitignore @@ -44,18 +44,14 @@ android/key.properties # Exceptions to above rules. !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages -# Autogenerated dart/rust binding code -native/dubp_rs/binding.h -packages/dubp_rs/lib/ffi.dart - -# Rust compiled libs for android or ios -**/*.a -**/*.so - # Rust things /target -pubkeys.txt - # Linux builds linux/ + +# Custom +scripts/private/ +AppDir/ +appimage-builder-cache/ +AppImageBuilder.yml diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e92115c..73c5265 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -8,9 +8,6 @@ stages: image: axiomteam/gecko-ci:v0.0.8 tags: - redshift - before_script: - - rustup show - - rustc --version && cargo --version format: extends: .env @@ -20,10 +17,6 @@ format: - if: $CI_COMMIT_TAG || $CI_MERGE_REQUEST_ID - when: manual stage: format - script: - - cargo fmt -- --version - - cargo fmt -- --check - - flutter format --set-exit-if-changed lib packages/dubp_rs/lib/dubp.dart build_and_test: extends: .env @@ -35,11 +28,8 @@ build_and_test: stage: build_and_test tags: - redshift - script: - - RUSTFLAGS="-D warnings" cargo make - - cd packages/dubp_rs && flutter pub get && cd ../.. + script: - flutter analyze - - cargo test # - flutter test lint: @@ -50,9 +40,6 @@ lint: - if: $CI_COMMIT_TAG || $CI_MERGE_REQUEST_ID - when: manual stage: quality - script: - - cargo clippy -- -V - - cargo clippy --all --tests -- -D warnings --verbose audit_dependencies: extends: .env @@ -62,9 +49,6 @@ audit_dependencies: - if: $CI_COMMIT_TAG || $CI_MERGE_REQUEST_ID - when: manual stage: quality - script: - - cargo deny -V - - cargo deny check releases:test: extends: .env diff --git a/.rusty-hook.toml b/.rusty-hook.toml deleted file mode 100644 index aaeaea8..0000000 --- a/.rusty-hook.toml +++ /dev/null @@ -1,5 +0,0 @@ -[hooks] -pre-commit = "cargo fmt -- --check && flutter format --set-exit-if-changed lib packages/dubp_rs/lib/dubp.dart" - -[logging] -verbose = true diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index 6f815cf..0000000 --- a/Cargo.lock +++ /dev/null @@ -1,2026 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "addr2line" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a55f82cfe485775d02112886f4169bde0c5894d75e79ead7eafe7e40a25e45f7" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - -[[package]] -name = "allo-isolate" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff09da612ca86c794c3c8f70613a3e6652b5f1313b938937b32cae80df28fdb1" - -[[package]] -name = "ansi_term" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" -dependencies = [ - "winapi", -] - -[[package]] -name = "arrayref" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" - -[[package]] -name = "arrayvec" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" -dependencies = [ - "serde", -] - -[[package]] -name = "ascii" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eab1c04a571841102f5345a8fc0f6bb3d31c315dec879b5c6e42e40ce7ffa34e" - -[[package]] -name = "assert_matches" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" - -[[package]] -name = "async-compression" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b72c1f1154e234325b50864a349b9c8e56939e266a4c307c0f159812df2f9537" -dependencies = [ - "flate2", - "futures-core", - "memchr", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "async-oneshot" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f4770cbbff928c30a991de67fb3976f44d8e3e202f8c79ef91b47006e04904" -dependencies = [ - "futures-micro", -] - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi", - "libc", - "winapi", -] - -[[package]] -name = "autocfg" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" - -[[package]] -name = "backtrace" -version = "0.3.56" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d117600f438b1707d4e4ae15d3595657288f8235a0eb593e80ecc98ab34e1bc" -dependencies = [ - "addr2line", - "cfg-if 1.0.0", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", -] - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "beef" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6736e2428df2ca2848d846c43e88745121a6654696e349ce0054a420815a7409" - -[[package]] -name = "bincode" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f30d3a39baa26f9651f17b375061f3233dde33424a8b72b0dbe93a68a0bc896d" -dependencies = [ - "byteorder", - "serde", -] - -[[package]] -name = "bitflags" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" - -[[package]] -name = "blake3" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9ff35b701f3914bdb8fad3368d822c766ef2858b2583198e41639b936f09d3f" -dependencies = [ - "arrayref", - "arrayvec", - "cc", - "cfg-if 0.1.10", - "constant_time_eq", - "crypto-mac", - "digest 0.9.0", -] - -[[package]] -name = "block-buffer" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" -dependencies = [ - "block-padding", - "byte-tools", - "byteorder", - "generic-array 0.12.4", -] - -[[package]] -name = "block-padding" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" -dependencies = [ - "byte-tools", -] - -[[package]] -name = "bs58" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3" - -[[package]] -name = "bumpalo" -version = "3.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63396b8a4b9de3f4fdfb320ab6080762242f66a8ef174c49d8e19b674db4cdbe" - -[[package]] -name = "byte-tools" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" - -[[package]] -name = "byteorder" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae44d1a3d5a19df61dd0c8beb138458ac2a53a7ac09eba97d55592540004306b" - -[[package]] -name = "bytes" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040" - -[[package]] -name = "cbindgen" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e03a705df2e735cc5486f104a48e25a8f72ae06eaea5b7753a81270ed00859" -dependencies = [ - "clap", - "heck", - "log", - "proc-macro2", - "quote", - "serde", - "serde_json", - "syn", - "tempfile", - "toml", -] - -[[package]] -name = "cc" -version = "1.0.66" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c0496836a84f8d0495758516b8621a622beb77c0fed418570e50764093ced48" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "ci_info" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24f638c70e8c5753795cc9a8c07c44da91554a09e4cf11a7326e8161b0a3c45e" -dependencies = [ - "envmnt", -] - -[[package]] -name = "clang" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f4d78574d27fc037d9079fbd79a4b092e0ccb6a806756ded47e77e8639a03bd" -dependencies = [ - "clang-sys", - "libc", -] - -[[package]] -name = "clang-sys" -version = "0.29.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe6837df1d5cba2397b835c8530f51723267e16abbf83892e9e5af4f0e5dd10a" -dependencies = [ - "glob", - "libc", -] - -[[package]] -name = "clap" -version = "2.33.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" -dependencies = [ - "ansi_term", - "atty", - "bitflags", - "strsim", - "textwrap", - "unicode-width", - "vec_map", -] - -[[package]] -name = "combine" -version = "3.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3da6baa321ec19e1cc41d31bf599f00c783d0517095cdaf0332e3fe8d20680" -dependencies = [ - "ascii", - "byteorder", - "either", - "memchr", - "unreachable", -] - -[[package]] -name = "constant_time_eq" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" - -[[package]] -name = "crc32fast" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81156fece84ab6a9f2afdb109ce3ae577e42b1228441eded99bd77f627953b1a" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "crypto-mac" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" -dependencies = [ - "generic-array 0.14.4", - "subtle", -] - -[[package]] -name = "cryptoxide" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46212f5d1792f89c3e866fb10636139464060110c568edd7f73ab5e9f736c26d" - -[[package]] -name = "dart-bindgen" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78a5a59086ea83b86183d5ada358815f62ee1842537333fb828ae9a9c896751" -dependencies = [ - "clang", - "log", - "thiserror", -] - -[[package]] -name = "digest" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" -dependencies = [ - "generic-array 0.12.4", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array 0.14.4", -] - -[[package]] -name = "doc-comment" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" - -[[package]] -name = "dubp" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5cee825e59cde21a3622de781d15f74cbea92f01eb1554a8c73818eb61a5998" -dependencies = [ - "dubp-common", - "dubp-documents", - "dubp-documents-parser", - "dubp-wallet", - "dup-crypto", -] - -[[package]] -name = "dubp-client" -version = "0.1.0" -source = "git+https://git.duniter.org/libs/dubp-rs-client-lib?branch=master#8db2379f84006966c80b7488084a7158a6a70302" -dependencies = [ - "arrayvec", - "bincode", - "cfg-if 1.0.0", - "dubp", - "duniter-bca-types", - "fast-threadpool 0.3.1-alpha.0", - "flume", - "graphql_client", - "maybe-async", - "rand", - "reqwest", - "resiter", - "serde", - "static_assertions", - "thiserror", -] - -[[package]] -name = "dubp-common" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dc000f2a3366c1bd985015f95adb3520e8e0b007ca5f77882eea1ea119d84f4" -dependencies = [ - "dup-crypto", - "serde", - "serde_json", - "thiserror", - "zerocopy", -] - -[[package]] -name = "dubp-documents" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e96808a8ced0617ba93ed6fee00d88902f33e2f61a36ec9a841e8972ef5cd3a" -dependencies = [ - "beef", - "dubp-wallet", - "log", - "serde", - "serde_json", - "thiserror", -] - -[[package]] -name = "dubp-documents-parser" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9c60f5c2804a9906777f96a62514c1f9f58abaab4c57f01db4fa7c45624e6fb" -dependencies = [ - "dubp-documents", - "json-pest-parser", - "pest", - "pest_derive", - "serde_json", - "thiserror", -] - -[[package]] -name = "dubp-wallet" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f277bed6bc228981f76f207f4112051656302b5c50c0a858ab138ae2215d49fe" -dependencies = [ - "byteorder", - "dubp-common", - "serde", - "smallvec", - "thiserror", - "zerocopy", -] - -[[package]] -name = "dubp_rs" -version = "0.1.0" -dependencies = [ - "allo-isolate", - "assert_matches", - "cbindgen", - "dart-bindgen", - "dubp-client", - "fast-threadpool 0.3.0", - "once_cell", - "parking_lot", - "rusty-hook", - "thiserror", -] - -[[package]] -name = "duniter-bca-types" -version = "0.1.0" -source = "git+https://git.duniter.org/nodes/rust/modules/duniter-gva#4ee272b85d6420ed6640b9503019cfa04864c851" -dependencies = [ - "arrayvec", - "bincode", - "dubp", - "serde", - "smallvec", - "thiserror", -] - -[[package]] -name = "dup-crypto" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c530e25cc0a03ae36229401ca322002931b55fc180e6001bdab20a9087f297c" -dependencies = [ - "arrayvec", - "base64", - "blake3", - "bs58", - "byteorder", - "cryptoxide", - "ed25519-bip32", - "getrandom", - "hex", - "once_cell", - "ring", - "serde", - "thiserror", - "zerocopy", - "zeroize", -] - -[[package]] -name = "ed25519-bip32" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8827180a2b511141fbe49141e50b31a8d542465e0fb572f81f36feea2addfe92" -dependencies = [ - "cryptoxide", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "encoding_rs" -version = "0.8.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80df024fbc5ac80f87dfef0d9f5209a252f2a497f7f42944cff24d8253cac065" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "envmnt" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2d328fc287c61314c4a61af7cfdcbd7e678e39778488c7cb13ec133ce0f4059" -dependencies = [ - "fsio", - "indexmap", -] - -[[package]] -name = "failure" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86" -dependencies = [ - "backtrace", - "failure_derive", -] - -[[package]] -name = "failure_derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "fake-simd" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" - -[[package]] -name = "fast-threadpool" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cccb66774e02743b4be61c19e09bf59de9058e9a7b4096040689003e7a901a3d" -dependencies = [ - "async-oneshot", - "flume", - "num_cpus", -] - -[[package]] -name = "fast-threadpool" -version = "0.3.1-alpha.0" -source = "git+https://github.com/librelois/fast-threadpool?branch=main#1a271710677ecc43cbfe43234ec21c954dfdbef7" -dependencies = [ - "async-oneshot", - "flume", - "num_cpus", -] - -[[package]] -name = "flate2" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd3aec53de10fe96d7d8c565eb17f2c687bb5518a2ec453b5b1252964526abe0" -dependencies = [ - "cfg-if 1.0.0", - "crc32fast", - "libc", - "miniz_oxide", -] - -[[package]] -name = "flume" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0362ef9c4c1fa854ff95b4cb78045a86e810d804dc04937961988b45427104a9" -dependencies = [ - "futures-core", - "futures-sink", - "nanorand", - "pin-project", - "spinning_top", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" -dependencies = [ - "matches", - "percent-encoding", -] - -[[package]] -name = "fsio" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1fd087255f739f4f1aeea69f11b72f8080e9c2e7645cd06955dad4a178a49e3" - -[[package]] -name = "futures-channel" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c2dd2df839b57db9ab69c2c9d8f3e8c81984781937fe2807dc6dcf3b2ad2939" -dependencies = [ - "futures-core", -] - -[[package]] -name = "futures-core" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15496a72fabf0e62bdc3df11a59a3787429221dd0710ba8ef163d6f7a9112c94" - -[[package]] -name = "futures-io" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71c2c65c57704c32f5241c1223167c2c3294fd34ac020c807ddbe6db287ba59" - -[[package]] -name = "futures-macro" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea405816a5139fb39af82c2beb921d52143f556038378d6db21183a5c37fbfb7" -dependencies = [ - "proc-macro-hack", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "futures-micro" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61e9325be55c5581082cd110294fa988c1f920bc573ec370ef201e33c469a95a" - -[[package]] -name = "futures-sink" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85754d98985841b7d4f5e8e6fbfa4a4ac847916893ec511a2917ccd8525b8bb3" - -[[package]] -name = "futures-task" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa189ef211c15ee602667a6fcfe1c1fd9e07d42250d2156382820fba33c9df80" - -[[package]] -name = "futures-util" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1812c7ab8aedf8d6f2701a43e1243acdbcc2b36ab26e2ad421eb99ac963d96d1" -dependencies = [ - "futures-core", - "futures-io", - "futures-macro", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "proc-macro-hack", - "proc-macro-nested", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" -dependencies = [ - "typenum", -] - -[[package]] -name = "generic-array" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getopts" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" -dependencies = [ - "unicode-width", -] - -[[package]] -name = "getrandom" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9495705279e7140bf035dde1f6e750c162df8b625267cd52cc44e0b156732c8" -dependencies = [ - "cfg-if 1.0.0", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "gimli" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6503fe142514ca4799d4c26297c4248239fe8838d827db6bd6065c6ed29a6ce" - -[[package]] -name = "glob" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" - -[[package]] -name = "graphql-introspection-query" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "610aac641dbd2a457ad4cef34aa2827dae3f035fd214cb38c2d62d8543f3973f" -dependencies = [ - "serde", -] - -[[package]] -name = "graphql-parser" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5613c31f18676f164112732202124f373bb2103ff017b3b85ca954ea6a66ada" -dependencies = [ - "combine", - "failure", -] - -[[package]] -name = "graphql_client" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0bb4f09181e4f80018d01c612125b07e0156f3753bfac37055fe2a25e031ca8" -dependencies = [ - "doc-comment", - "graphql_query_derive", - "serde", - "serde_json", -] - -[[package]] -name = "graphql_client_codegen" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e304c223c809b3bff4614018f8e6d9edb176b31d64ed9ea48b6ae8b1a03abb9" -dependencies = [ - "failure", - "graphql-introspection-query", - "graphql-parser", - "heck", - "lazy_static", - "proc-macro2", - "quote", - "serde", - "serde_json", - "syn", -] - -[[package]] -name = "graphql_query_derive" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1f6b14d5ce549227aa9e649cd9d36d008b91021275a8e0a67d71cef815adc2f" -dependencies = [ - "failure", - "graphql_client_codegen", - "proc-macro2", - "syn", -] - -[[package]] -name = "h2" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc018e188373e2777d0ef2467ebff62a08e66c3f5857b23c8fbec3018210dc00" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "hashbrown" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" - -[[package]] -name = "heck" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cbf45460356b7deeb5e3415b5563308c0a9b057c85e12b06ad551f98d0a6ac" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "hermit-abi" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aca5565f760fb5b220e499d72710ed156fdb74e631659e99377d9ebfbd13ae8" -dependencies = [ - "libc", -] - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "http" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7245cd7449cc792608c3c8a9eaf69bd4eabbabf802713748fd739c98b82f0747" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - -[[package]] -name = "http-body" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfb77c123b4e2f72a2069aeae0b4b4949cc7e966df277813fc16347e7549737" -dependencies = [ - "bytes", - "http", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "615caabe2c3160b313d52ccc905335f4ed5f10881dd63dc5699d47e90be85691" - -[[package]] -name = "httpdate" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494b4d60369511e7dea41cf646832512a94e542f68bb9c49e54518e0f468eb47" - -[[package]] -name = "hyper" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8e946c2b1349055e0b72ae281b238baf1a3ea7307c7e9f9d64673bdd9c26ac7" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project", - "socket2", - "tokio", - "tower-service", - "tracing", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f9f7a97316d44c0af9b0301e65010573a853a9fc97046d7331d7f6bc0fd5a64" -dependencies = [ - "futures-util", - "hyper", - "log", - "rustls", - "tokio", - "tokio-rustls", - "webpki", -] - -[[package]] -name = "idna" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89829a5d69c23d348314a7ac337fe39173b61149a9864deabd260983aed48c21" -dependencies = [ - "matches", - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "indexmap" -version = "1.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3" -dependencies = [ - "autocfg", - "hashbrown", -] - -[[package]] -name = "instant" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61124eeebbd69b8190558df225adf7e4caafce0d743919e5d6b19652314ec5ec" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "ipnet" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47be2f14c678be2fdcab04ab1171db51b2762ce6f0a8ee87c8dd4a04ed216135" - -[[package]] -name = "itoa" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" - -[[package]] -name = "js-sys" -version = "0.3.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cfb73131c35423a367daf8cbd24100af0d077668c8c2943f0e7dd775fef0f65" -dependencies = [ - "wasm-bindgen", -] - -[[package]] -name = "json-pest-parser" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc5c84a2bceeda1ce3bd58497bde2d8cba61ca0b45873ef502401f0ff2ae8ed" -dependencies = [ - "pest", - "pest_derive", - "thiserror", - "unwrap", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1482821306169ec4d07f6aca392a4681f66c75c9918aa49641a2595db64053cb" - -[[package]] -name = "lock_api" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd96ffd135b2fd7b973ac026d28085defbe8983df057ced3eb4f2130b0831312" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b" -dependencies = [ - "cfg-if 0.1.10", -] - -[[package]] -name = "maplit" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" - -[[package]] -name = "matches" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" - -[[package]] -name = "maybe-async" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb8e1fec4e9a343755fdcd6adc9394c0ac0bb764eb36b3aecfdf151a44e8c83" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "memchr" -version = "2.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525" - -[[package]] -name = "mime" -version = "0.3.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" - -[[package]] -name = "miniz_oxide" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" -dependencies = [ - "adler", - "autocfg", -] - -[[package]] -name = "mio" -version = "0.7.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e50ae3f04d169fcc9bde0b547d1c205219b7157e07ded9c5aff03e0637cb3ed7" -dependencies = [ - "libc", - "log", - "miow", - "ntapi", - "winapi", -] - -[[package]] -name = "miow" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" -dependencies = [ - "winapi", -] - -[[package]] -name = "nanorand" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac1378b66f7c93a1c0f8464a19bf47df8795083842e5090f4b7305973d5a22d0" -dependencies = [ - "getrandom", -] - -[[package]] -name = "nias" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab250442c86f1850815b5d268639dff018c0627022bc1940eb2d642ca1ce12f0" - -[[package]] -name = "ntapi" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f6bb902e437b6d86e03cce10a7e2af662292c5dfef23b65899ea3ac9354ad44" -dependencies = [ - "winapi", -] - -[[package]] -name = "num_cpus" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "object" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a7ab5d64814df0fe4a4b5ead45ed6c5f181ee3ff04ba344313a6c80446c5d4" - -[[package]] -name = "once_cell" -version = "1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13bd41f508810a131401606d54ac32a467c97172d74ba7662562ebba5ad07fa0" - -[[package]] -name = "opaque-debug" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" - -[[package]] -name = "parking_lot" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d7744ac029df22dca6284efe4e898991d28e3085c706c972bcd7da4a27a15eb" -dependencies = [ - "instant", - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7a782938e745763fe6907fc6ba86946d72f49fe7e21de074e08128a99fb018" -dependencies = [ - "cfg-if 1.0.0", - "instant", - "libc", - "redox_syscall", - "smallvec", - "winapi", -] - -[[package]] -name = "percent-encoding" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" - -[[package]] -name = "pest" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53" -dependencies = [ - "ucd-trie", -] - -[[package]] -name = "pest_derive" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "833d1ae558dc601e9a60366421196a8d94bc0ac980476d0b67e1d0988d72b2d0" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99b8db626e31e5b81787b9783425769681b347011cc59471e33ea46d2ea0cf55" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "pest_meta" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54be6e404f5317079812fc8f9f5279de376d8856929e21c184ecf6bbd692a11d" -dependencies = [ - "maplit", - "pest", - "sha-1", -] - -[[package]] -name = "pin-project" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc174859768806e91ae575187ada95c91a29e96a98dc5d2cd9a1fed039501ba6" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a490329918e856ed1b083f244e3bfe2d8c4f336407e4ea9e1a9f479ff09049e5" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc0e1f259c92177c30a4c9d177246edd0a3568b25756a977d0632cf8fa37e905" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "ppv-lite86" -version = "0.2.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" - -[[package]] -name = "proc-macro-hack" -version = "0.5.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" - -[[package]] -name = "proc-macro-nested" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc881b2c22681370c6a780e47af9840ef841837bc98118431d4e1868bd0c1086" - -[[package]] -name = "proc-macro2" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "quote" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "991431c3519a3f36861882da93630ce66b52918dcf1b8e2fd66b397fc96f28df" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ef9e7e66b4468674bfcb0c81af8b7fa0bb154fa9f28eb840da5c447baeb8d7e" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", - "rand_hc", -] - -[[package]] -name = "rand_chacha" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e12735cf05c9e10bf21534da50a147b924d555dc7a547c42e6bb2d5b6017ae0d" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34cf66eb183df1c5876e2dcf6b13d57340741e8dc255b48e40a26de954d06ae7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rand_hc" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3190ef7066a446f2e7f42e239d161e905420ccab01eb967c9eb27d21b2322a73" -dependencies = [ - "rand_core", -] - -[[package]] -name = "redox_syscall" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94341e4e44e24f6b591b59e47a8a027df12e008d73fd5672dbea9cc22f4507d9" -dependencies = [ - "bitflags", -] - -[[package]] -name = "remove_dir_all" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" -dependencies = [ - "winapi", -] - -[[package]] -name = "reqwest" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf12057f289428dbf5c591c74bf10392e4a8003f993405a902f20117019022d4" -dependencies = [ - "async-compression", - "base64", - "bytes", - "encoding_rs", - "futures-core", - "futures-util", - "http", - "http-body", - "hyper", - "hyper-rustls", - "ipnet", - "js-sys", - "lazy_static", - "log", - "mime", - "percent-encoding", - "pin-project-lite", - "rustls", - "serde", - "serde_json", - "serde_urlencoded", - "tokio", - "tokio-rustls", - "tokio-util", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "webpki-roots", - "winreg", -] - -[[package]] -name = "resiter" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd69ab1e90258b7769f0b5c46bfd802b8206d0707ced4ca4b9d5681b744de1be" - -[[package]] -name = "ring" -version = "0.16.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" -dependencies = [ - "cc", - "libc", - "once_cell", - "spin", - "untrusted", - "web-sys", - "winapi", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e3bad0ee36814ca07d7968269dd4b7ec89ec2da10c4bb613928d3077083c232" - -[[package]] -name = "rustls" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "064fd21ff87c6e87ed4506e68beb42459caa4a0e2eb144932e6776768556980b" -dependencies = [ - "base64", - "log", - "ring", - "sct", - "webpki", -] - -[[package]] -name = "rusty-hook" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96cee9be61be7e1cbadd851e58ed7449c29c620f00b23df937cb9cbc04ac21a3" -dependencies = [ - "ci_info", - "getopts", - "nias", - "toml", -] - -[[package]] -name = "ryu" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "sct" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3042af939fca8c3453b7af0f1c66e533a15a86169e39de2657310ade8f98d3c" -dependencies = [ - "ring", - "untrusted", -] - -[[package]] -name = "serde" -version = "1.0.123" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d5161132722baa40d802cc70b15262b98258453e85e5d1d365c757c73869ae" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.123" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9391c295d64fc0abb2c556bad848f33cb8296276b1ad2677d1ae1ace4f258f31" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.61" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fceb2595057b6891a4ee808f70054bd2d12f0e97f1cbb78689b59f676df325a" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edfa57a7f8d9c1d260a549e7224100f6c43d43f9103e06dd8b4095a9b2b43ce9" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "sha-1" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d94d0bede923b3cea61f3f1ff57ff8cdfd77b400fb8f9998949e0cf04163df" -dependencies = [ - "block-buffer", - "digest 0.8.1", - "fake-simd", - "opaque-debug", -] - -[[package]] -name = "slab" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" - -[[package]] -name = "smallvec" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e" -dependencies = [ - "serde", -] - -[[package]] -name = "socket2" -version = "0.3.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "122e570113d28d773067fab24266b66753f6ea915758651696b6e35e49f88d6e" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "winapi", -] - -[[package]] -name = "spin" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" - -[[package]] -name = "spinning_top" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e529d73e80d64b5f2631f9035113347c578a1c9c7774b83a2b880788459ab36" -dependencies = [ - "lock_api", -] - -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - -[[package]] -name = "strsim" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" - -[[package]] -name = "subtle" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e81da0851ada1f3e9d4312c704aa4f8806f0f9d69faaf8df2f3464b4a9437c2" - -[[package]] -name = "syn" -version = "1.0.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c700597eca8a5a762beb35753ef6b94df201c81cca676604f547495a0d7f0081" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b834f2d66f734cb897113e34aaff2f1ab4719ca946f9a7358dba8f8064148701" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "unicode-xid", -] - -[[package]] -name = "tempfile" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dac1c663cfc93810f88aed9b8941d48cabf856a1b111c29a40439018d870eb22" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "rand", - "redox_syscall", - "remove_dir_all", - "winapi", -] - -[[package]] -name = "textwrap" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -dependencies = [ - "unicode-width", -] - -[[package]] -name = "thiserror" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0f4a65597094d4483ddaed134f409b2cb7c1beccf25201a9f73c719254fa98e" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7765189610d8241a44529806d6fd1f2e0a08734313a35d5b3a556f92b381f3c0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tinyvec" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "317cca572a0e89c3ce0ca1f1bdc9369547fe318a683418e42ac8f59d14701023" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" - -[[package]] -name = "tokio" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "134af885d758d645f0f0505c9a8b3f9bf8a348fd822e112ab5248138348f1722" -dependencies = [ - "autocfg", - "bytes", - "libc", - "memchr", - "mio", - "num_cpus", - "pin-project-lite", -] - -[[package]] -name = "tokio-rustls" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc6844de72e57df1980054b38be3a9f4702aba4858be64dd700181a8a6d0e1b6" -dependencies = [ - "rustls", - "tokio", - "webpki", -] - -[[package]] -name = "tokio-util" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5143d049e85af7fbc36f5454d990e62c2df705b3589f123b71f441b6b59f443f" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "log", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" -dependencies = [ - "serde", -] - -[[package]] -name = "tower-service" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6" - -[[package]] -name = "tracing" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01ebdc2bb4498ab1ab5f5b73c5803825e60199229ccba0698170e3be0e7f959f" -dependencies = [ - "cfg-if 1.0.0", - "pin-project-lite", - "tracing-core", -] - -[[package]] -name = "tracing-core" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f50de3927f93d202783f4513cda820ab47ef17f624b03c096e86ef00c67e6b5f" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "try-lock" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" - -[[package]] -name = "typenum" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "373c8a200f9e67a0c95e62a4f52fbf80c23b4381c05a17845531982fa99e6b33" - -[[package]] -name = "ucd-trie" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" - -[[package]] -name = "unicode-bidi" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" -dependencies = [ - "matches", -] - -[[package]] -name = "unicode-normalization" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07fbfce1c8a97d547e8b5334978438d9d6ec8c20e38f56d4a4374d181493eaef" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-segmentation" -version = "1.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0d2e7be6ae3a5fa87eed5fb451aff96f2573d2694942e40543ae0bbe19c796" - -[[package]] -name = "unicode-width" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" - -[[package]] -name = "unicode-xid" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" - -[[package]] -name = "unreachable" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" -dependencies = [ - "void", -] - -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - -[[package]] -name = "unwrap" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e33648dd74328e622c7be51f3b40a303c63f93e6fa5f08778b6203a4c25c20f" - -[[package]] -name = "url" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ccd964113622c8e9322cfac19eb1004a07e636c545f325da085d5cdde6f1f8b" -dependencies = [ - "form_urlencoded", - "idna", - "matches", - "percent-encoding", -] - -[[package]] -name = "vec_map" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" - -[[package]] -name = "version_check" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed" - -[[package]] -name = "void" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" - -[[package]] -name = "want" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" -dependencies = [ - "log", - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.10.2+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" - -[[package]] -name = "wasm-bindgen" -version = "0.2.70" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55c0f7123de74f0dab9b7d00fd614e7b19349cd1e2f5252bbe9b1754b59433be" -dependencies = [ - "cfg-if 1.0.0", - "serde", - "serde_json", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.70" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bc45447f0d4573f3d65720f636bbcc3dd6ce920ed704670118650bcd47764c7" -dependencies = [ - "bumpalo", - "lazy_static", - "log", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3de431a2910c86679c34283a33f66f4e4abd7e0aec27b6669060148872aadf94" -dependencies = [ - "cfg-if 1.0.0", - "js-sys", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.70" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b8853882eef39593ad4174dd26fc9865a64e84026d223f63bb2c42affcbba2c" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.70" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4133b5e7f2a531fa413b3a1695e925038a05a71cf67e87dafa295cb645a01385" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.70" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd4945e4943ae02d15c13962b38a5b1e81eadd4b71214eee75af64a4d6a4fd64" - -[[package]] -name = "web-sys" -version = "0.3.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c40dc691fc48003eba817c38da7113c15698142da971298003cac3ef175680b3" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki" -version = "0.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea" -dependencies = [ - "ring", - "untrusted", -] - -[[package]] -name = "webpki-roots" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82015b7e0b8bad8185994674a13a93306bea76cf5a16c5a181382fd3a5ec2376" -dependencies = [ - "webpki", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "winreg" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0120db82e8a1e0b9fb3345a539c478767c0048d842860994d96113d5b667bd69" -dependencies = [ - "winapi", -] - -[[package]] -name = "zerocopy" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6580539ad917b7c026220c4b3f2c08d52ce54d6ce0dc491e66002e35388fab46" -dependencies = [ - "byteorder", - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d498dbd1fd7beb83c86709ae1c33ca50942889473473d287d56ce4770a18edfb" -dependencies = [ - "proc-macro2", - "syn", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81a974bcdd357f0dca4d41677db03436324d45a4c9ed2d0b873a5a360ce41c36" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3f369ddb18862aba61aa49bf31e74d29f0f162dec753063200e1dc084345d16" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] diff --git a/Cargo.toml b/Cargo.toml deleted file mode 100644 index 90c3171..0000000 --- a/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[workspace] -members = ["native/dubp_rs"] - -[profile.release] -lto = true -codegen-units = 1 -debug = true - -[patch.crates-io] -#dup-crypto = { path = "/home/elois/dev/duniter/libs/dubp-rs-libs/crypto" } diff --git a/Makefile.toml b/Makefile.toml deleted file mode 100644 index 76ead5d..0000000 --- a/Makefile.toml +++ /dev/null @@ -1,369 +0,0 @@ -[env] -CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true -CARGO_MAKE_WORKSPACE_INCLUDE_MEMBERS = ["native/dubp_rs"] -ANDROID_PLATFORM_VERSION = "21" -TARGET_OS = "unknown" -RELEASE = true -DEV = false -LIB_OUT_DIR = "release" - -[env.debug] -DEV = true -RELEASE = false -LIB_OUT_DIR = "debug" - -[tasks.test-flow] -disabled = true - -[tasks.android-dev32] -description = "development android i686 emulator" -category = "Build" -dependencies = [ - "setup-crate-type-android", - "pre-android", - "android-i686", - "android-i686-release", - "post-android-i686", - "post-android", - ] - -[tasks.android-dev] -description = "development android x86_64 emulator" -category = "Build" -dependencies = [ - "setup-crate-type-android", - "pre-android", - "android-x86_64", - "android-x86_64-release", - "post-android-x86_64", - "post-android", - ] - -[tasks.android-arm] -description = "build android ARM64 for actual device" -category = "Build" -dependencies = [ - "setup-crate-type-android", - "pre-android", - "android-aarch64", - "android-aarch64-release", - "post-android-aarch64", - "post-android", - ] - - -[tasks.build] -description = "Runs the rust compiler." -category = "Build" -dependencies = ["android"] - -[tasks.build.mac] -description = "Runs the rust compiler." -category = "Build" -dependencies = ["android", "ios"] - -# ANDROID - -[tasks.android] -description = "Build android targets." -category = "Build" -dependencies = [ - "setup-crate-type-android", - "pre-android", - "android-aarch64", - "android-aarch64-release", - "post-android-aarch64", - "android-armv7", - "android-armv7-release", - "post-android-armv7", - #"android-i686", - #"android-i686-release", - #"post-android-i686", - #"android-x86_64", - #"android-x86_64-release", - #"post-android-x86_64", - "post-android" -] - -[tasks.android-build] -private = true -condition = { env_true = ["DEV"], env_set = ["ANDROID_TARGET"] } -command = "cargo" -args = [ - "ndk", - "--platform", - "${ANDROID_PLATFORM_VERSION}", - "--target", - "${ANDROID_TARGET}", - "build", -] - -[tasks.android-build-release] -private = true -condition = { env_true = ["RELEASE"], env_set = ["ANDROID_TARGET"] } -command = "cargo" -args = [ - "ndk", - "--platform", - "${ANDROID_PLATFORM_VERSION}", - "--target", - "${ANDROID_TARGET}", - "build", - "--release" -] - -[tasks.android-aarch64] -private = true -condition = { env_true = ["DEV"] } -env = { ANDROID_TARGET = "aarch64-linux-android" } -run_task = "android-build" - -[tasks.android-armv7] -private = true -condition = { env_true = ["DEV"] } -env = { ANDROID_TARGET = "armv7-linux-androideabi" } -run_task = "android-build" - -[tasks.android-i686] -private = true -condition = { env_true = ["DEV"] } -env = { ANDROID_TARGET = "i686-linux-android" } -run_task = "android-build" - -[tasks.android-x86_64] -private = true -condition = { env_true = ["DEV"] } -env = { ANDROID_TARGET = "x86_64-linux-android" } -run_task = "android-build" - -[tasks.android-aarch64-release] -private = true -condition = { env_true = ["RELEASE"] } -env = { ANDROID_TARGET = "aarch64-linux-android" } -run_task = "android-build-release" - -[tasks.android-armv7-release] -private = true -condition = { env_true = ["RELEASE"] } -env = { ANDROID_TARGET = "armv7-linux-androideabi" } -run_task = "android-build-release" - -[tasks.android-i686-release] -private = true -condition = { env_true = ["RELEASE"] } -env = { ANDROID_TARGET = "i686-linux-android" } -run_task = "android-build-release" - -[tasks.android-x86_64-release] -private = true -condition = { env_true = ["RELEASE"] } -env = { ANDROID_TARGET = "x86_64-linux-android" } -run_task = "android-build-release" - -[tasks.pre-android] -private = true -script_runner = "@duckscript" -script = [ - "mkdir ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/packages/${CARGO_MAKE_CRATE_FS_NAME}/android/src/main/jniLibs/arm64-v8a", - "mkdir ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/packages/${CARGO_MAKE_CRATE_FS_NAME}/android/src/main/jniLibs/armeabi-v7a", - "mkdir ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/packages/${CARGO_MAKE_CRATE_FS_NAME}/android/src/main/jniLibs/x86", - "mkdir ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/packages/${CARGO_MAKE_CRATE_FS_NAME}/android/src/main/jniLibs/x86_64", -] - -[tasks.android-copy-lib] -private = true -condition = { env_set = ["ANDROID_TARGET", "JNI_LIB_DIR"] } -script_runner = "@duckscript" -script = [ - """ - cp ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/target/${ANDROID_TARGET}/${LIB_OUT_DIR}/lib${CARGO_MAKE_CRATE_FS_NAME}.so \ - ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/packages/${CARGO_MAKE_CRATE_FS_NAME}/android/src/main/jniLibs/${JNI_LIB_DIR}/lib${CARGO_MAKE_CRATE_FS_NAME}.so - """, -] - -[tasks.post-android-aarch64] -private = true -env = { ANDROID_TARGET = "aarch64-linux-android", JNI_LIB_DIR = "arm64-v8a" } -run_task = "android-copy-lib" - -[tasks.post-android-armv7] -private = true -env = { ANDROID_TARGET = "armv7-linux-androideabi", JNI_LIB_DIR = "armeabi-v7a" } -run_task = "android-copy-lib" - -[tasks.post-android-i686] -private = true -env = { ANDROID_TARGET = "i686-linux-android", JNI_LIB_DIR = "x86" } -run_task = "android-copy-lib" - -[tasks.post-android-x86_64] -private = true -env = { ANDROID_TARGET = "x86_64-linux-android", JNI_LIB_DIR = "x86_64" } -run_task = "android-copy-lib" - -[tasks.post-android] -dependencies = ["restore-crate-type"] - -# IOS - -[tasks.ios] -description = "build iOS targets" -category = "Build" -dependencies = ["ios-build", "ios-release", "post-ios"] - -[tasks.ios-build] -condition = { platforms = ["mac"], env_true = ["DEV"] } -description = "Build ios targets." -category = "Build" -command = "cargo" -args = ["lipo"] -dependencies = [ - "setup-crate-type-ios", -] - -[tasks.ios-release] -condition = { platforms = ["mac"], env_true = ["RELEASE"] } -description = "Build ios targets." -category = "Build" -command = "cargo" -args = ["lipo", "--release"] -dependencies = [ - "setup-crate-type-ios", -] - -[tasks.post-ios] -script_runner = "@duckscript" -condition = { platforms = ["mac"] } -script = [ - """ - cp ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/target/universal/${LIB_OUT_DIR}/lib${CARGO_MAKE_CRATE_FS_NAME}.a \ - ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/packages/${CARGO_MAKE_CRATE_FS_NAME}/ios/lib${CARGO_MAKE_CRATE_FS_NAME}.a - """, - """ - cp ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/native/${CARGO_MAKE_CRATE_CURRENT_WORKSPACE_MEMBER}/binding.h \ - ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/packages/${CARGO_MAKE_CRATE_FS_NAME}/ios/Classes/binding.h - """, -] -dependencies = ["restore-crate-type"] - -# LINUX - -[tasks.linux] -description = "Build linux targets." -category = "Build" -dependencies = [ - "setup-crate-type-linux", - "pre-linux", - "linux-x86_64-release", - "linux-copy-lib", - "post-linux" -] - -[tasks.pre-linux] -private = true -script_runner = "@duckscript" -script = [ - "mkdir ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/packages/${CARGO_MAKE_CRATE_FS_NAME}/linux", -] - -[tasks.linux-x86_64-release] -private = true -condition = { env_true = ["RELEASE"] } -env = { LINUX_TARGET = "x86_64-unknown-linux-gnu" } -run_task = "linux-build-release" - -[tasks.linux-build-release] -private = true -condition = { env_true = ["RELEASE"], env_set = ["LINUX_TARGET"] } -command = "cargo" -args = [ - "build", - "--release", - "--target", - "${LINUX_TARGET}" -] - -[tasks.linux-copy-lib] -private = true -condition = { env_set = ["LINUX_TARGET"] } -script_runner = "@duckscript" -script = [ - """ - cp ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/target/${LINUX_TARGET}/${LIB_OUT_DIR}/lib${CARGO_MAKE_CRATE_FS_NAME}.so \ - ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/packages/${CARGO_MAKE_CRATE_FS_NAME}/linux/lib${CARGO_MAKE_CRATE_FS_NAME}.so - """, -] - -[tasks.post-linux] -dependencies = ["restore-crate-type"] - -# SETUP CRATE TYPE - -[tasks.setup-crate-type-android] -private = true -env = { TARGET_OS = "android" } -run_task = "setup-crate-type" - -[tasks.setup-crate-type-ios] -private = true -env = { TARGET_OS = "ios" } -run_task = "setup-crate-type" - -[tasks.setup-crate-type-linux] -private = true -env = { TARGET_OS = "linux" } -run_task = "setup-crate-type" - -[tasks.setup-crate-type] -private = true -script_runner = "@duckscript" -script = [ - """ - toml = readfile ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/native/${CARGO_MAKE_CRATE_CURRENT_WORKSPACE_MEMBER}/Cargo.toml - crate_type = set "" - os = get_env TARGET_OS - is_android = eq ${os} "android" - is_ios = eq ${os} "ios" - is_linux = eq ${os} "linux" - if ${is_android} - crate_type = set "cdylib" - elseif ${is_ios} - crate_type = set "staticlib" - elseif ${is_linux} - crate_type = set "cdylib" - else - crate_type = set "rlib" - end - val = replace ${toml} "rlib" ${crate_type} - result = writefile ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/native/${CARGO_MAKE_CRATE_CURRENT_WORKSPACE_MEMBER}/Cargo.toml ${val} - assert ${result} - """, -] - -# RESTORE CRATE TYPE - -[tasks.restore-crate-type] -private = true -script_runner = "@duckscript" -script = [ - """ - toml = readfile ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/native/${CARGO_MAKE_CRATE_CURRENT_WORKSPACE_MEMBER}/Cargo.toml - crate_type = set "" - os = get_env TARGET_OS - is_android = eq ${os} "android" - is_ios = eq ${os} "ios" - is_linux = eq ${os} "linux" - if ${is_android} - crate_type = set "cdylib" - elseif ${is_ios} - crate_type = set "staticlib" - elseif ${is_linux} - crate_type = set "cdylib" - else - crate_type = set "rlib" - end - val = replace ${toml} ${crate_type} "rlib" - result = writefile ${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/native/${CARGO_MAKE_CRATE_CURRENT_WORKSPACE_MEMBER}/Cargo.toml ${val} - assert ${result} - """, -] \ No newline at end of file diff --git a/README.md b/README.md index 27ed9d8..d674e01 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Ğecko -Ğecko is a transaction client owned by [Axiom-Team association] and written in Dart. It is fast and secure thanks to native code compilation, Rust cryptography bindings and Duniter's new GraphQL API (GVA). It is not intended to manage member accounts, but rather simple wallets. +Ğecko is a transaction client owned by [Axiom-Team association] and written in Dart. It is fast and secure thanks to native code compilation. It is not intended to manage member accounts, but rather simple wallets. The development is quite early, you can participate in the discussion [on the Duniter forum](https://forum.duniter.org/t/gecko-nouveau-client-de-paiements-1-sur-mobile-en-cours-de-developpement-dart-flutter/7857) (mostly FR) @@ -27,7 +27,6 @@ To contribute to the code, we advise you to install the following development en - Android NDK 1. Flutter SDK 1. VSCode/Codium Flutter extension -1. Rust toolchain This will take about 12GB on your drive and 30 min of your time (with a good connection). Don't hesitate to ask on the forum for a peer-coding session if you are stuck. @@ -58,12 +57,6 @@ Flutter is a powerfull SDK to develop Android apps. [Install it](https://flutter We are using VSCode and therefore document the process for this IDE. Of course you're free to use whatever you want. Clone the ğecko repo and open a dart file (e.g. `lib/main.dart`). VSCode will suggest you to insall relevant extensions. -### Rust toolchain - -After installing Rust with the standard [rustup install script](https://www.rust-lang.org/tools/install), -follow the instructions to build Rust dependencies [in this separate README](./packages/dubp_rs/README.md). -If you installed a 32bits VM, use the 32bits build command. - ### Build the app In a dart file (e.g. `lib/main.dart`), type the `F5` key to build the code. The app should open automatically in your VM which is running. diff --git a/android/app/build.gradle b/android/app/build.gradle index a1989bf..55d3b2d 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -32,7 +32,7 @@ if (keystorePropertiesFile.exists()) { } android { - compileSdkVersion 29 + compileSdkVersion 30 sourceSets { main.java.srcDirs += 'src/main/kotlin' @@ -44,9 +44,9 @@ android { defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.example.gecko" + applicationId "gecko.axiomteam.fr" minSdkVersion 16 - targetSdkVersion 29 + targetSdkVersion 30 versionCode flutterVersionCode.toInteger() versionName flutterVersionName multiDexEnabled true diff --git a/android/build.gradle b/android/build.gradle index 3100ad2..dc5cdbc 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -6,7 +6,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.5.0' + classpath 'com.android.tools.build:gradle:4.0.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index 296b146..493072b 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip diff --git a/assets/avatars/trunc/0.png b/assets/avatars/trunc/0.png deleted file mode 100755 index c379552..0000000 Binary files a/assets/avatars/trunc/0.png and /dev/null differ diff --git a/assets/avatars/trunc/1.png b/assets/avatars/trunc/1.png deleted file mode 100755 index 49023c9..0000000 Binary files a/assets/avatars/trunc/1.png and /dev/null differ diff --git a/assets/avatars/trunc/2.png b/assets/avatars/trunc/2.png deleted file mode 100755 index f9546ef..0000000 Binary files a/assets/avatars/trunc/2.png and /dev/null differ diff --git a/deny.toml b/deny.toml deleted file mode 100644 index e214658..0000000 --- a/deny.toml +++ /dev/null @@ -1,55 +0,0 @@ -[bans] -multiple-versions = "warn" -deny = [ - # color-backtrace is nice but brings in too many dependencies and that are often outdated, so not worth it for us. - { name = "color-backtrace" }, - - # deprecated - { name = "quickersort" }, - - # term is not fully maintained, and termcolor is replacing it - { name = "term" }, -] -skip-tree = [ - { name = "winapi", version = "<= 0.3" }, -] - -[licenses] -unlicensed = "deny" -# We want really high confidence when inferring licenses from text -confidence-threshold = 0.8 -allow = [ - "AGPL-3.0", - "Apache-2.0", - "BSD-2-Clause", - "BSD-3-Clause", - "CC0-1.0", - "ISC", - "MIT", - "MPL-2.0", - "OpenSSL", - "Zlib" -] - -[[licenses.clarify]] -name = "ring" -# SPDX considers OpenSSL to encompass both the OpenSSL and SSLeay licenses -# https://spdx.org/licenses/OpenSSL.html -# ISC - Both BoringSSL and ring use this for their new files -# MIT - "Files in third_party/ have their own licenses, as described therein. The MIT -# license, for third_party/fiat, which, unlike other third_party directories, is -# compiled into non-test libraries, is included below." -# OpenSSL - Obviously -expression = "ISC AND MIT AND OpenSSL" -license-files = [ - { path = "LICENSE", hash = 0xbd0eed23 }, -] - -[sources] -unknown-registry = "deny" -unknown-git = "deny" -allow-git = [ - "https://git.duniter.org/libs/dubp-rs-client-lib", - "https://git.duniter.org/nodes/rust/modules/duniter-gva", - "https://github.com/librelois/fast-threadpool" -] \ No newline at end of file diff --git a/lib/globals.dart b/lib/globals.dart index 70cd2ae..abbaf47 100644 --- a/lib/globals.dart +++ b/lib/globals.dart @@ -8,23 +8,25 @@ import 'package:logger/logger.dart'; import 'package:shared_preferences/shared_preferences.dart'; // Files paths -Directory appPath; +Directory? appPath; -String appVersion; -SharedPreferences prefs; -String endPointGVA; -int ramSys; -Box walletBox; -Box chestBox; -Box configBox; -Box g1WalletsBox; +late String appVersion; +late SharedPreferences prefs; +late String endPointGVA; +const int pinLength = 5; +const String appLang = 'french'; + +late Box walletBox; +late Box chestBox; +late Box configBox; +late Box g1WalletsBox; String cesiumPod = "https://g1.data.le-sou.org"; // String cesiumPod = "https://g1.data.e-is.pro"; // Responsive ratios -bool isTall; -double ratio; +late bool isTall; +late double ratio; // Logger var log = Logger(); diff --git a/lib/main.dart b/lib/main.dart index 14a98a5..e59041f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -19,18 +19,18 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/cesium_plus.dart'; -import 'package:gecko/models/change_pin.dart'; +import 'package:gecko/providers/cesium_plus.dart'; +import 'package:gecko/providers/change_pin.dart'; import 'package:gecko/models/chest_data.dart'; -import 'package:gecko/models/chest_provider.dart'; +import 'package:gecko/providers/chest_provider.dart'; import 'package:gecko/models/g1_wallets_list.dart'; -import 'package:gecko/models/generate_wallets.dart'; -import 'package:gecko/models/wallets_profiles.dart'; -import 'package:gecko/models/home.dart'; -import 'package:gecko/models/my_wallets.dart'; -import 'package:gecko/models/search.dart'; +import 'package:gecko/providers/generate_wallets.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; +import 'package:gecko/providers/home.dart'; +import 'package:gecko/providers/my_wallets.dart'; +import 'package:gecko/providers/search.dart'; import 'package:gecko/models/wallet_data.dart'; -import 'package:gecko/models/wallet_options.dart'; +import 'package:gecko/providers/wallet_options.dart'; import 'package:gecko/screens/home.dart'; import 'package:flutter/material.dart'; import 'package:gecko/screens/myWallets/wallets_home.dart'; @@ -38,25 +38,29 @@ import 'package:gecko/screens/search.dart'; import 'package:gecko/screens/search_result.dart'; import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:hive_flutter/hive_flutter.dart'; -import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; import 'package:flutter/foundation.dart'; import 'package:responsive_framework/responsive_framework.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:sentry_flutter/sentry_flutter.dart'; +import 'package:window_size/window_size.dart'; const bool enableSentry = true; Future main() async { WidgetsFlutterBinding.ensureInitialized(); + if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) { + setWindowTitle('Ğecko'); + setWindowMinSize(const Size(400, 700)); + setWindowMaxSize(const Size(800, 1000)); + } HomeProvider _homeProvider = HomeProvider(); - appPath = await getApplicationDocumentsDirectory(); + await _homeProvider.initHive(); appVersion = await _homeProvider.getAppVersion(); prefs = await SharedPreferences.getInstance(); // Configure Hive and open boxes - await Hive.initFlutter(appPath.path); Hive.registerAdapter(WalletDataAdapter()); Hive.registerAdapter(ChestDataAdapter()); Hive.registerAdapter(G1WalletsListAdapter()); @@ -120,14 +124,14 @@ Future main() async { } class Gecko extends StatelessWidget { - const Gecko(this.randomEndpoint, {Key key}) : super(key: key); - final String randomEndpoint; + const Gecko(this.randomEndpoint, {Key? key}) : super(key: key); + final String? randomEndpoint; @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); final _httpLink = HttpLink( - randomEndpoint, + randomEndpoint!, ); final _client = ValueNotifier( @@ -156,7 +160,7 @@ class Gecko extends StatelessWidget { client: _client, child: MaterialApp( builder: (context, widget) => ResponsiveWrapper.builder( - BouncingScrollWrapper.builder(context, widget), + BouncingScrollWrapper.builder(context, widget!), maxWidth: 1200, minWidth: 480, defaultScale: true, @@ -185,7 +189,7 @@ class Gecko extends StatelessWidget { home: const HomeScreen(), initialRoute: "/", routes: { - '/mywallets': (context) => WalletsHome(), + '/mywallets': (context) => const WalletsHome(), '/search': (context) => const SearchScreen(), '/searchResult': (context) => const SearchResultScreen(), }, @@ -198,7 +202,7 @@ class Gecko extends StatelessWidget { // This http overriding is needed to fix fail certifcat checking for Duniter node on old Android version class MyHttpOverrides extends HttpOverrides { @override - HttpClient createHttpClient(SecurityContext context) { + HttpClient createHttpClient(SecurityContext? context) { return super.createHttpClient(context) ..badCertificateCallback = (X509Certificate cert, String host, int port) => true; diff --git a/lib/models/change_pin.dart b/lib/models/change_pin.dart deleted file mode 100644 index 43f8bc4..0000000 --- a/lib/models/change_pin.dart +++ /dev/null @@ -1,42 +0,0 @@ -import 'package:dubp/dubp.dart'; -import 'package:flutter/material.dart'; -import 'dart:async'; -import 'package:gecko/globals.dart'; - -class ChangePinProvider with ChangeNotifier { - bool ischangedPin = false; - TextEditingController newPin = TextEditingController(); - String pinToGive; - - Future get badWallet => null; - - Future changePin(String _oldPin) async { - try { - final _dewif = chestBox.get(configBox.get('currentChest')).dewif; - - NewWallet newWalletFile = await DubpRust.changeDewifPin( - dewif: _dewif, - oldPin: _oldPin.toUpperCase(), - ); - - newPin.text = pinToGive = newWalletFile.pin; - ischangedPin = true; - notifyListeners(); - return newWalletFile; - } catch (e) { - log.e('Impossible de changer le code PIN.'); - return badWallet; - } - } - - void storeNewPinChest(context, NewWallet _newWalletFile) { - // ChestData currentChest = chestBox.getAt(configBox.get('currentChest')); - // currentChest.dewif = _newWalletFile.dewif; - // await chestBox.add(currentChest); - - chestBox.get(configBox.get('currentChest')).dewif = _newWalletFile.dewif; - - Navigator.pop(context, pinToGive); - pinToGive = ''; - } -} diff --git a/lib/models/chest_data.dart b/lib/models/chest_data.dart index 9e01d9a..48f5579 100644 --- a/lib/models/chest_data.dart +++ b/lib/models/chest_data.dart @@ -7,22 +7,22 @@ part 'chest_data.g.dart'; @HiveType(typeId: 1) class ChestData extends HiveObject { @HiveField(0) - String dewif; + String? dewif; @HiveField(2) - String name; + String? name; @HiveField(3) - int defaultWallet; + int? defaultWallet; @HiveField(4) - String imageName; + String? imageName; @HiveField(5) - File imageFile; + File? imageFile; @HiveField(6) - bool isCesium; + bool? isCesium; ChestData({ this.dewif, @@ -35,6 +35,6 @@ class ChestData extends HiveObject { @override String toString() { - return name; + return name!; } } diff --git a/lib/models/chest_data.g.dart b/lib/models/chest_data.g.dart index 1d0be58..33cbaf3 100644 --- a/lib/models/chest_data.g.dart +++ b/lib/models/chest_data.g.dart @@ -17,12 +17,12 @@ class ChestDataAdapter extends TypeAdapter { for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return ChestData( - dewif: fields[0] as String, - name: fields[2] as String, - defaultWallet: fields[3] as int, - imageName: fields[4] as String, - imageFile: fields[5] as File, - isCesium: fields[6] as bool, + dewif: fields[0] as String?, + name: fields[2] as String?, + defaultWallet: fields[3] as int?, + imageName: fields[4] as String?, + imageFile: fields[5] as File?, + isCesium: fields[6] as bool?, ); } diff --git a/lib/models/g1_wallets_list.dart b/lib/models/g1_wallets_list.dart index 98fef2b..1cc62ab 100644 --- a/lib/models/g1_wallets_list.dart +++ b/lib/models/g1_wallets_list.dart @@ -6,25 +6,25 @@ part 'g1_wallets_list.g.dart'; @HiveType(typeId: 2) class G1WalletsList { @HiveField(0) - String pubkey; + String? pubkey; @HiveField(1) - double balance; + double? balance; @HiveField(3) - Id id; + Id? id; @HiveField(4) - Image avatar; + Image? avatar; @HiveField(5) - String username; + String? username; @HiveField(6) - String csName; + String? csName; @HiveField(7) - bool isMembre; + bool? isMembre; G1WalletsList({ this.pubkey, @@ -47,7 +47,7 @@ class G1WalletsList { data['pubkey'] = pubkey; data['balance'] = balance; if (id != null) { - data['id'] = id.toJson(); + data['id'] = id!.toJson(); } return data; } @@ -55,8 +55,8 @@ class G1WalletsList { @HiveType(typeId: 3) class Id { - bool isMember; - String username; + bool? isMember; + String? username; Id({this.isMember, this.username}); diff --git a/lib/models/g1_wallets_list.g.dart b/lib/models/g1_wallets_list.g.dart index 266daed..bb7c15d 100644 --- a/lib/models/g1_wallets_list.g.dart +++ b/lib/models/g1_wallets_list.g.dart @@ -19,13 +19,13 @@ class G1WalletsListAdapter extends TypeAdapter { for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return G1WalletsList( - pubkey: fields[0] as String, - balance: fields[1] as double, - id: fields[3] as Id, - avatar: fields[4] as Image, - username: fields[5] as String, - csName: fields[6] as String, - isMembre: fields[7] as bool, + pubkey: fields[0] as String?, + balance: fields[1] as double?, + id: fields[3] as Id?, + avatar: fields[4] as Image?, + username: fields[5] as String?, + csName: fields[6] as String?, + isMembre: fields[7] as bool?, ); } diff --git a/lib/models/wallet_data.dart b/lib/models/wallet_data.dart index 20ea9ef..fc7cf51 100644 --- a/lib/models/wallet_data.dart +++ b/lib/models/wallet_data.dart @@ -7,22 +7,22 @@ part 'wallet_data.g.dart'; @HiveType(typeId: 0) class WalletData extends HiveObject { @HiveField(0) - int chest; + int? chest; @HiveField(1) - int number; + int? number; @HiveField(2) - String name; + String? name; @HiveField(3) - int derivation; + int? derivation; @HiveField(4) - String imageName; + String? imageName; @HiveField(5) - File imageFile; + File? imageFile; WalletData( {this.chest, @@ -35,7 +35,7 @@ class WalletData extends HiveObject { // representation of WalletData when debugging @override String toString() { - return name; + return name!; } // creates the ':'-separated string from the WalletData @@ -44,7 +44,7 @@ class WalletData extends HiveObject { } // returns only the id part of the ':'-separated string - List id() { + List id() { return [chest, number]; } } diff --git a/lib/models/wallet_data.g.dart b/lib/models/wallet_data.g.dart index 3f8ee52..56f2ce8 100644 --- a/lib/models/wallet_data.g.dart +++ b/lib/models/wallet_data.g.dart @@ -17,12 +17,12 @@ class WalletDataAdapter extends TypeAdapter { for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return WalletData( - chest: fields[0] as int, - number: fields[1] as int, - name: fields[2] as String, - derivation: fields[3] as int, - imageName: fields[4] as String, - imageFile: fields[5] as File, + chest: fields[0] as int?, + number: fields[1] as int?, + name: fields[2] as String?, + derivation: fields[3] as int?, + imageName: fields[4] as String?, + imageFile: fields[5] as File?, ); } diff --git a/lib/models/cesium_plus.dart b/lib/providers/cesium_plus.dart similarity index 86% rename from lib/models/cesium_plus.dart rename to lib/providers/cesium_plus.dart index 7bae7b3..72c35cc 100644 --- a/lib/models/cesium_plus.dart +++ b/lib/providers/cesium_plus.dart @@ -8,7 +8,7 @@ import 'package:path_provider/path_provider.dart'; class CesiumPlusProvider with ChangeNotifier { TextEditingController cesiumName = TextEditingController(); - Image defaultAvatar(double size) => + Image defaultAvatar(double? size) => Image.asset(('assets/icon_user.png'), height: size); CancelToken avatarCancelToken = CancelToken(); @@ -60,17 +60,17 @@ class CesiumPlusProvider with ChangeNotifier { return [podRequest, queryGetAvatar, headers]; } - Future getName(String _pubkey) async { - String _name; + Future getName(String? _pubkey) async { + String? _name; - if (g1WalletsBox.get(_pubkey).csName != null) { - return g1WalletsBox.get(_pubkey).csName; + if (g1WalletsBox.get(_pubkey)!.csName != null) { + return g1WalletsBox.get(_pubkey)!.csName!; } List queryOptions = await _buildQuery(_pubkey); var dio = Dio(); - Response response; + late Response response; try { response = await dio.post( queryOptions[0], @@ -97,14 +97,15 @@ class CesiumPlusProvider with ChangeNotifier { } _name = response.data['hits']['hits'][0]['_source']['title']; - g1WalletsBox.get(_pubkey).csName = _name; + _name ??= ''; + g1WalletsBox.get(_pubkey)!.csName = _name; return _name; } - Future getAvatar(String _pubkey, double size) async { - if (g1WalletsBox.get(_pubkey).avatar != null) { - return g1WalletsBox.get(_pubkey).avatar; + Future getAvatar(String? _pubkey, double size) async { + if (g1WalletsBox.get(_pubkey)?.avatar != null) { + return g1WalletsBox.get(_pubkey)!.avatar; } var dio = Dio(); @@ -112,7 +113,7 @@ class CesiumPlusProvider with ChangeNotifier { List queryOptions = await _buildQuery(_pubkey); - Response response; + late Response response; try { response = await dio .post(queryOptions[0], @@ -150,7 +151,7 @@ class CesiumPlusProvider with ChangeNotifier { fit: BoxFit.fitWidth, ); - g1WalletsBox.get(_pubkey).avatar = finalAvatar; + g1WalletsBox.get(_pubkey)!.avatar = finalAvatar; return finalAvatar; } diff --git a/lib/providers/change_pin.dart b/lib/providers/change_pin.dart new file mode 100644 index 0000000..422cf2b --- /dev/null +++ b/lib/providers/change_pin.dart @@ -0,0 +1,48 @@ +import 'package:durt/durt.dart'; +import 'package:flutter/material.dart'; +import 'package:gecko/globals.dart'; + +class ChangePinProvider with ChangeNotifier { + bool ischangedPin = false; + TextEditingController newPin = TextEditingController(); + String? pinToGive; + + NewWallet? get badWallet => null; + + Future changePin(String _oldPin, {String? newCustomPin}) async { + final NewWallet newWalletFile; + try { + final _chest = chestBox.get(configBox.get('currentChest'))!; + + if (_chest.isCesium!) { + newWalletFile = await Dewif().changeCesiumPassword( + dewif: _chest.dewif!, + oldPassword: _oldPin.toUpperCase(), + newPassword: newCustomPin); + } else { + newWalletFile = await Dewif().changePassword( + dewif: _chest.dewif!, + oldPassword: _oldPin.toUpperCase(), + newPassword: newCustomPin); + } + newPin.text = pinToGive = newWalletFile.password; + ischangedPin = true; + // notifyListeners(); + return newWalletFile; + } catch (e) { + log.e('Impossible de changer le code PIN: $e'); + return badWallet; + } + } + + void storeNewPinChest(context, NewWallet _newWalletFile) { + // ChestData currentChest = chestBox.getAt(configBox.get('currentChest')); + // currentChest.dewif = _newWalletFile.dewif; + // await chestBox.add(currentChest); + + chestBox.get(configBox.get('currentChest'))!.dewif = _newWalletFile.dewif; + + Navigator.pop(context, pinToGive); + pinToGive = ''; + } +} diff --git a/lib/models/chest_provider.dart b/lib/providers/chest_provider.dart similarity index 84% rename from lib/models/chest_provider.dart rename to lib/providers/chest_provider.dart index 9af37a4..9c7250b 100644 --- a/lib/models/chest_provider.dart +++ b/lib/providers/chest_provider.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; import 'package:gecko/models/chest_data.dart'; @@ -8,14 +9,14 @@ class ChestProvider with ChangeNotifier { } Future deleteChest(context, ChestData _chest) async { - final bool _answer = await _confirmDeletingChest(context, _chest.name); + final bool? _answer = await (_confirmDeletingChest(context, _chest.name)); - if (_answer) { + if (_answer!) { await chestBox.delete(_chest.key); if (chestBox.isEmpty) { await configBox.put('currentChest', 0); } else { - int lastChest = chestBox.toMap().keys.first; + int? lastChest = chestBox.toMap().keys.first; await configBox.put('currentChest', lastChest); } @@ -27,7 +28,7 @@ class ChestProvider with ChangeNotifier { } } - Future _confirmDeletingChest(context, String _walletName) async { + Future _confirmDeletingChest(context, String? _walletName) async { return showDialog( context: context, barrierDismissible: true, // user must tap button! diff --git a/lib/models/generate_wallets.dart b/lib/providers/generate_wallets.dart similarity index 82% rename from lib/models/generate_wallets.dart rename to lib/providers/generate_wallets.dart index 57d3d3b..43a389a 100644 --- a/lib/models/generate_wallets.dart +++ b/lib/providers/generate_wallets.dart @@ -1,6 +1,6 @@ import 'dart:math'; import 'dart:typed_data'; -import 'package:dubp/dubp.dart'; +import 'package:durt/durt.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; @@ -15,16 +15,16 @@ import "package:unorm_dart/unorm_dart.dart" as unorm; class GenerateWalletsProvider with ChangeNotifier { GenerateWalletsProvider(); // NewWallet generatedWallet; - NewWallet actualWallet; + NewWallet? actualWallet; FocusNode walletNameFocus = FocusNode(); - Color askedWordColor = Colors.black; + Color? askedWordColor = Colors.black; bool isAskedWordValid = false; - int nbrWord; - String nbrWordAlpha; + late int nbrWord; + String? nbrWordAlpha; - String generatedMnemonic; + String? generatedMnemonic; bool walletIsGenerated = true; TextEditingController mnemonicController = TextEditingController(); @@ -37,7 +37,7 @@ class GenerateWalletsProvider with ChangeNotifier { bool isCesiumIDVisible = false; bool isCesiumPWDVisible = false; bool canImport = false; - bool isPinChanged = false; + late CesiumWallet cesiumWallet; // Import Chest TextEditingController cellController0 = TextEditingController(); @@ -58,7 +58,7 @@ class GenerateWalletsProvider with ChangeNotifier { NewWallet _wallet, String _name, BuildContext context) async { int chestNumber = 0; chestBox.toMap().forEach((key, value) { - if (!value.isCesium) { + if (!value.isCesium!) { chestNumber++; } }); @@ -77,7 +77,7 @@ class GenerateWalletsProvider with ChangeNotifier { isCesium: false, ); await chestBox.add(thisChest); - int chestKey = chestBox.keys.last; + int? chestKey = chestBox.keys.last; WalletData myWallet = WalletData( chest: chestKey, @@ -128,7 +128,7 @@ class GenerateWalletsProvider with ChangeNotifier { return rng.nextInt(12); } - String intToString(int _nbr) { + String? intToString(int _nbr) { Map nbrToString = {}; nbrToString[1] = 'Premier'; nbrToString[2] = 'Deuxième'; @@ -152,53 +152,34 @@ class GenerateWalletsProvider with ChangeNotifier { notifyListeners(); } - Future generateMnemonic() async { + Future generateWallet(String generatedMnemonic, + {required bool isImport}) async { try { - generatedMnemonic = await DubpRust.genMnemonic(language: Language.french); - actualWallet = await generateWallet(generatedMnemonic, isImport: false); - walletIsGenerated = true; - } catch (e) { - log.e(e); - } - return generatedMnemonic; - } - - Future generateWallet(String generatedMnemonic, - {@required bool isImport}) async { - try { - actualWallet = await DubpRust.genWalletFromMnemonic( - language: Language.french, - mnemonic: generatedMnemonic, - secretCodeType: SecretCodeType.letters, - ); + actualWallet = await Dewif().generateDewif( + generatedMnemonic, randomSecretCode(pinLength), + lang: appLang); } catch (e) { log.e(e); } if (!isImport) { mnemonicController.text = generatedMnemonic; - pin.text = actualWallet.pin; + pin.text = actualWallet!.password; } // notifyListeners(); return actualWallet; } - Future changePinCode({bool reload}) async { - actualWallet = await DubpRust.changeDewifPin( - dewif: actualWallet.dewif, - oldPin: actualWallet.pin, - ); - - pin.text = actualWallet.pin; - isPinChanged = true; + String changePinCode({required bool reload}) { + pin.text = randomSecretCode(pinLength); if (reload) { notifyListeners(); } - return actualWallet; + return pin.text; } - Future printWallet(String _title) async { + Future printWallet(String? _title) async { final ByteData fontData = await rootBundle.load("assets/OpenSans-Regular.ttf"); final pw.Font ttf = pw.Font.ttf(fontData.buffer.asByteData()); @@ -216,7 +197,7 @@ class GenerateWalletsProvider with ChangeNotifier { pw.Text("Phrase de restauration:", style: pw.TextStyle(fontSize: 20, font: ttf)), pw.SizedBox(height: 10), - pw.Text(_title, + pw.Text(_title!, style: pw.TextStyle(fontSize: 15, font: ttf), textAlign: pw.TextAlign.center), pw.Expanded( @@ -238,18 +219,14 @@ class GenerateWalletsProvider with ChangeNotifier { Future generateCesiumWalletPubkey( String _cesiumID, String _cesiumPWD) async { - actualWallet = await DubpRust.genWalletFromDeprecatedSaltPassword( - salt: _cesiumID, password: _cesiumPWD); - String _walletPubkey = await DubpRust.getLegacyPublicKey( - salt: _cesiumID, password: _cesiumPWD); + cesiumWallet = CesiumWallet(_cesiumID, _cesiumPWD); + String _walletPubkey = cesiumWallet.pubkey; cesiumPubkey.text = _walletPubkey; - pin.text = actualWallet.pin; - isPinChanged = true; log.d(_walletPubkey); } - Future importCesiumWallet() async { + Future importCesiumWallet() async { // String _walletPubkey = await DubpRust.getLegacyPublicKey( // salt: _cesiumID, password: _cesiumPWD); // String shortPubkey = truncate(_walletPubkey, 9, @@ -262,14 +239,12 @@ class GenerateWalletsProvider with ChangeNotifier { cesiumPWD.text = ''; cesiumPubkey.text = ''; canImport = false; - isPinChanged = false; - pin.text = ''; isCesiumIDVisible = false; isCesiumPWDVisible = false; int chestNumber = 0; chestBox.toMap().forEach((key, value) { - if (value.isCesium) { + if (value.isCesium!) { chestNumber++; } }); @@ -281,19 +256,24 @@ class GenerateWalletsProvider with ChangeNotifier { chestName = 'Coffre à Césium ${chestNumber + 1}'; } + log.d(pin.text); + NewWallet cesiumDewif = + await Dewif().generateCesiumDewif(cesiumWallet.seed, pin.text); + ChestData cesiumChest = ChestData( - dewif: actualWallet.dewif, + dewif: cesiumDewif.dewif, name: chestName, imageName: 'cesium.png', defaultWallet: 0, isCesium: true); await chestBox.add(cesiumChest).then((value) => null); - int chestKey = await chestBox.toMap().keys.last; + int? chestKey = await chestBox.toMap().keys.last; // chestBox.toMap(). await configBox.put('currentChest', chestKey); - notifyListeners(); + pin.text = ''; + return chestKey; } void cesiumIDisVisible() { @@ -308,18 +288,18 @@ class GenerateWalletsProvider with ChangeNotifier { void resetCesiumImportView() { cesiumID.text = cesiumPWD.text = cesiumPubkey.text = pin.text = ''; - canImport = isPinChanged = isCesiumIDVisible = isCesiumPWDVisible = false; + canImport = isCesiumIDVisible = isCesiumPWDVisible = false; actualWallet = null; notifyListeners(); } - Future> generateWordList() async { - final String _sentance = await generateMnemonic(); + List generateWordList() { + generatedMnemonic = generateMnemonic(lang: appLang); List _wordsList = []; String word; int _nbr = 1; - for (word in _sentance.split(' ')) { + for (word in generatedMnemonic!.split(' ')) { _wordsList.add("$_nbr:$word"); _nbr++; } @@ -336,7 +316,7 @@ class GenerateWalletsProvider with ChangeNotifier { return bip39Words.contains(word); } - bool isBipWordsList(List words) { + bool isBipWordsList(List words) { bool isValid = true; for (String word in words) { // Needed for bad encoding of UTF-8 @@ -353,8 +333,8 @@ class GenerateWalletsProvider with ChangeNotifier { cellController0.text = cellController1.text = cellController2.text = cellController3.text = cellController4.text = cellController5.text = cellController6.text = cellController7.text = cellController8.text = - cellController9.text = - cellController10.text = cellController11.text = ''; + cellController9.text = cellController10.text = + cellController11.text = ''; isFirstTimeSentenceComplete = true; notifyListeners(); } @@ -394,12 +374,13 @@ class GenerateWalletsProvider with ChangeNotifier { inputMnemonic = inputMnemonic.replaceAll('é', 'é'); inputMnemonic = inputMnemonic.replaceAll('è', 'è'); - NewWallet generatedWallet = + NewWallet? generatedWallet = await generateWallet(inputMnemonic, isImport: true); if (generatedWallet == null) { return false; } else { + generatedMnemonic = inputMnemonic; return true; } } diff --git a/lib/models/home.dart b/lib/providers/home.dart similarity index 74% rename from lib/models/home.dart rename to lib/providers/home.dart index 6b19b19..07f0a6b 100644 --- a/lib/models/home.dart +++ b/lib/providers/home.dart @@ -7,54 +7,64 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'dart:async'; import 'package:gecko/globals.dart'; -import 'package:gecko/screens/old_history_pay.dart'; -import 'package:gecko/screens/myWallets/wallets_home.dart'; -import 'package:package_info/package_info.dart'; +import 'package:hive_flutter/hive_flutter.dart'; +import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:path_provider/path_provider.dart' as pp; +import 'package:package_info_plus/package_info_plus.dart'; class HomeProvider with ChangeNotifier { - int _currentIndex = 0; - bool isSearching; + bool? isSearching; Icon searchIcon = const Icon(Icons.search); final TextEditingController searchQuery = TextEditingController(); Widget appBarTitle = Text('Ğecko', style: TextStyle(color: Colors.grey[850])); Widget appBarExplorer = Text('Explorateur', style: TextStyle(color: Colors.grey[850])); - List currentTab = [OldHistoryScreen(), WalletsHome()]; bool isFirstBuild = true; // AudioCache player = AudioCache(prefix: 'sounds/'); - get currentIndex => _currentIndex; + Future initHive() async { + late Directory hivePath; - set currentIndex(int index) { - _currentIndex = index; - notifyListeners(); + if (!kIsWeb) { + if (Platform.isLinux || Platform.isMacOS) { + final home = Platform.environment['HOME']; + hivePath = Directory('$home/.gecko/db'); + } else if (Platform.isWindows) { + final home = Platform.environment['UserProfile']; + hivePath = Directory('$home/.gecko/db'); + } else if (Platform.isAndroid || Platform.isIOS) { + final home = await pp.getApplicationDocumentsDirectory(); + hivePath = Directory('${home.path}/db'); + } + if (!await hivePath.exists()) { + await hivePath.create(recursive: true); + } + await Hive.initFlutter(hivePath.path); + } else { + await Hive.initFlutter(); + } } Future getAppVersion() async { String version; String buildNumber; - if (Platform.isLinux) { - version = "undefined"; - buildNumber = "undefined"; - } else { - PackageInfo packageInfo = await PackageInfo.fromPlatform(); - version = packageInfo.version; - buildNumber = packageInfo.buildNumber; - } + PackageInfo packageInfo = await PackageInfo.fromPlatform(); + version = packageInfo.version; + buildNumber = packageInfo.buildNumber; notifyListeners(); return version + '+' + buildNumber; } - Future getValidEndpoint() async { + Future getValidEndpoint() async { List _listEndpoints = await rootBundle .loadString('config/gva_endpoints.json') .then((jsonStr) => jsonDecode(jsonStr)); _listEndpoints.shuffle(); int i = 0; - String _endpoint; + String? _endpoint; int _statusCode = 0; final _client = HttpClient(); @@ -95,7 +105,7 @@ class HomeProvider with ChangeNotifier { } } while (_statusCode != 400); - log.i('ENDPOINT: ' + _endpoint); + log.i('ENDPOINT: ' + _endpoint!); return _endpoint; } diff --git a/lib/models/my_wallets.dart b/lib/providers/my_wallets.dart similarity index 70% rename from lib/models/my_wallets.dart rename to lib/providers/my_wallets.dart index 8a45bb0..e826a83 100644 --- a/lib/models/my_wallets.dart +++ b/lib/providers/my_wallets.dart @@ -1,3 +1,6 @@ +import 'dart:typed_data'; + +import 'package:durt/durt.dart'; import 'package:flutter/material.dart'; import 'dart:async'; import 'package:gecko/globals.dart'; @@ -5,10 +8,12 @@ import 'package:gecko/models/wallet_data.dart'; class MyWalletsProvider with ChangeNotifier { List listWallets = []; - String pinCode; - int pinLenght; + late String pinCode; + late String mnemonic; + late Uint8List cesiumSeed; + int? pinLenght; - int getCurrentChest() { + int? getCurrentChest() { if (configBox.get('currentChest') == null) { configBox.put('currentChest', 0); } @@ -16,6 +21,24 @@ class MyWalletsProvider with ChangeNotifier { return configBox.get('currentChest'); } + String dewifToMnemonic(context, WalletData _wallet, String _pin) { + String _mnemonic; + + try { + String _localDewif = chestBox.get(_wallet.chest)!.dewif!; + _mnemonic = Dewif() + .mnemonicFromDewif(_localDewif, _pin.toUpperCase(), lang: appLang); + } on ChecksumException catch (e) { + log.e(e.cause); + return 'bad'; + } catch (e) { + // _homeProvider.playSound('non', 0.6); + log.e('ERROR READING FILE: $e'); + return 'bad'; + } + return _mnemonic; + } + bool checkIfWalletExist() { if (chestBox.isEmpty) { log.i('No wallets detected'); @@ -25,7 +48,7 @@ class MyWalletsProvider with ChangeNotifier { } } - List readAllWallets(int _chest) { + List readAllWallets(int? _chest) { listWallets.clear(); walletBox.toMap().forEach((key, value) { if (value.chest == _chest) { @@ -36,11 +59,11 @@ class MyWalletsProvider with ChangeNotifier { return listWallets; } - WalletData getWalletData(List _id) { + WalletData? getWalletData(List _id) { if (_id.isEmpty) return WalletData(); - int _chest = _id[0]; - int _nbr = _id[1]; - WalletData _targetedWallet; + int? _chest = _id[0]; + int? _nbr = _id[1]; + WalletData? _targetedWallet; walletBox.toMap().forEach((key, value) { if (value.chest == _chest && value.number == _nbr) { @@ -52,11 +75,11 @@ class MyWalletsProvider with ChangeNotifier { return _targetedWallet; } - WalletData getDefaultWallet(int chest) { + WalletData? getDefaultWallet(int? chest) { if (chestBox.isEmpty) { return WalletData(chest: 0, number: 0); } else { - int defaultWalletNumber = chestBox.get(chest).defaultWallet; + int? defaultWalletNumber = chestBox.get(chest)!.defaultWallet; return getWalletData([chest, defaultWalletNumber]); } } @@ -65,8 +88,8 @@ class MyWalletsProvider with ChangeNotifier { try { log.w('DELETE ALL WALLETS ?'); - final bool _answer = await _confirmDeletingAllWallets(context); - if (_answer) { + final bool? _answer = await (_confirmDeletingAllWallets(context)); + if (_answer!) { await walletBox.clear(); await chestBox.clear(); await configBox.delete('defaultWallet'); @@ -84,7 +107,7 @@ class MyWalletsProvider with ChangeNotifier { } } - Future _confirmDeletingAllWallets(context) async { + Future _confirmDeletingAllWallets(context) async { return showDialog( context: context, barrierDismissible: true, // user must tap button! @@ -116,15 +139,15 @@ class MyWalletsProvider with ChangeNotifier { Future generateNewDerivation(context, String _name) async { int _newDerivationNbr; int _newWalletNbr; - int _chest = getCurrentChest(); + int? _chest = getCurrentChest(); List _walletConfig = readAllWallets(_chest); if (_walletConfig.isEmpty) { _newDerivationNbr = 3; _newWalletNbr = 0; } else { - _newDerivationNbr = _walletConfig.last.derivation + 3; - _newWalletNbr = _walletConfig.last.number + 1; + _newDerivationNbr = _walletConfig.last.derivation! + 3; + _newWalletNbr = _walletConfig.last.number! + 1; } WalletData newWallet = WalletData( diff --git a/lib/models/search.dart b/lib/providers/search.dart similarity index 86% rename from lib/models/search.dart rename to lib/providers/search.dart index f17b7e1..bacad73 100644 --- a/lib/models/search.dart +++ b/lib/providers/search.dart @@ -2,7 +2,7 @@ import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; import 'package:gecko/models/g1_wallets_list.dart'; -import 'package:gecko/models/wallets_profiles.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; class SearchProvider with ChangeNotifier { TextEditingController searchController = TextEditingController(); @@ -25,7 +25,7 @@ class SearchProvider with ChangeNotifier { // final response = await http.get(url); var dio = Dio(); - Response response; + late Response response; try { response = await dio.get( 'https://g1-stats.axiom-team.fr/data/forbes.json', @@ -40,8 +40,8 @@ class SearchProvider with ChangeNotifier { log.e(e); } - List _listWallets = _parseG1Wallets(response.data); - Map _mapWallets = { + List _listWallets = _parseG1Wallets(response.data)!; + Map _mapWallets = { for (var e in _listWallets) e.pubkey: e }; @@ -51,11 +51,11 @@ class SearchProvider with ChangeNotifier { g1WalletsBox.toMap().forEach((key, value) { if ((value.id != null && - value.id.username != null && - value.id.username + value.id!.username != null && + value.id!.username! .toLowerCase() .contains(searchController.text)) || - value.pubkey.contains(searchController.text)) { + value.pubkey!.contains(searchController.text)) { searchResult.add(value); return; } @@ -70,7 +70,7 @@ class SearchProvider with ChangeNotifier { } } -List _parseG1Wallets(var responseBody) { +List? _parseG1Wallets(var responseBody) { final parsed = responseBody.cast>(); return parsed diff --git a/lib/models/wallet_options.dart b/lib/providers/wallet_options.dart similarity index 68% rename from lib/models/wallet_options.dart rename to lib/providers/wallet_options.dart index a1c3582..1056d7c 100644 --- a/lib/models/wallet_options.dart +++ b/lib/providers/wallet_options.dart @@ -1,18 +1,15 @@ -// import 'dart:ffi'; import 'dart:io'; -import 'dart:typed_data'; import 'package:crypto/crypto.dart'; -import 'package:dubp/dubp.dart'; +import 'package:durt/durt.dart'; import 'package:fast_base58/fast_base58.dart'; import 'package:flutter/material.dart'; import 'dart:async'; import 'package:gecko/globals.dart'; import 'package:gecko/models/chest_data.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/models/wallet_data.dart'; import 'package:image_picker/image_picker.dart'; import 'package:truncate/truncate.dart'; -import 'package:qrscan/qrscan.dart' as scanner; class WalletOptionsProvider with ChangeNotifier { TextEditingController pubkey = TextEditingController(); @@ -24,13 +21,12 @@ class WalletOptionsProvider with ChangeNotifier { bool isBalanceBlur = true; FocusNode walletNameFocus = FocusNode(); TextEditingController nameController = TextEditingController(); - bool isDefaultWallet; + late bool isDefaultWallet; - Future get badWallet => null; + Future? get badWallet => null; - Future _getPubkeyFromDewif( - String _dewif, _pin, int _pinLenght, int derivation) async { - String _pubkey; + String _getPubkeyFromDewif( + String? _dewif, _pin, int _pinLenght, int? derivation) { RegExp regExp = RegExp( r'^[A-Z0-9]+$', caseSensitive: false, @@ -43,27 +39,25 @@ class WalletOptionsProvider with ChangeNotifier { } if (derivation != -1) { try { - List _pubkeysTmp = await DubpRust.getBip32DewifAccountsPublicKeys( - dewif: _dewif, secretCode: _pin, accountsIndex: [derivation]); - _pubkey = _pubkeysTmp[0]; - pubkey.text = _pubkey; + final _wallet = HdWallet.fromDewif(_dewif!, _pin, lang: appLang); + pubkey.text = _wallet.getPubkey(derivation!); + log.d(pubkey.text); notifyListeners(); - return _pubkey; + return pubkey.text; } catch (e) { - log.w('Bad PIN code !\n' + e); + log.w('Bad PIN code !\n' + e.toString()); notifyListeners(); return 'false'; } } else { try { - _pubkey = await DubpRust.getDewifPublicKey(dewif: _dewif, pin: _pin); - pubkey.text = _pubkey; + pubkey.text = CesiumWallet.fromDewif(_dewif!, _pin).pubkey; notifyListeners(); - return _pubkey; + return pubkey.text; } catch (e) { - log.w('Bad PIN code !\n' + e); + log.w('Bad PIN code !\n' + e.toString()); notifyListeners(); return 'false'; @@ -71,22 +65,34 @@ class WalletOptionsProvider with ChangeNotifier { } } - Future readLocalWallet( - context, WalletData _wallet, String _pin, int _pinLenght) async { + String? readLocalWallet( + context, WalletData _wallet, String _pin, int _pinLenght, + {String? mnemonic}) { isWalletUnlock = false; - try { - String _localDewif = chestBox.get(_wallet.chest).dewif; - String _localPubkey; + final String _localPubkey; - if ((_localPubkey = await _getPubkeyFromDewif( - _localDewif, _pin, _pinLenght, _wallet.derivation)) != - 'false') { + try { + String? _localDewif = chestBox.get(_wallet.chest)!.dewif; + + if (mnemonic == null) { + _localPubkey = _getPubkeyFromDewif( + _localDewif, _pin.toUpperCase(), _pinLenght, _wallet.derivation); + } else { + final _hdwallet = HdWallet.fromMnemonic(mnemonic); + _localPubkey = _hdwallet.getPubkey(_wallet.derivation!); + } + + if (_localPubkey != 'false') { pubkey.text = _localPubkey; isWalletUnlock = true; + log.d(pubkey.text); return _localDewif; } else { throw 'Bad pubkey'; } + } on ChecksumException catch (e) { + log.e(e.cause); + return 'bad'; } catch (e) { // _homeProvider.playSound('non', 0.6); log.e('ERROR READING FILE: $e'); @@ -95,44 +101,36 @@ class WalletOptionsProvider with ChangeNotifier { } } - Future checkPinOK(String _createdDewif, String _pin, int _pinLenght) async { - isWalletUnlock = false; - try { - if (await _getPubkeyFromDewif(_createdDewif, _pin, _pinLenght, 3) != - 'false') { - return true; - } else { - throw false; - } - } catch (e) { - log.e('ERROR READING FILE: $e'); - return false; - } - } - int getPinLenght(_walletNbr) { - String _localDewif; - if (_walletNbr is int || _walletNbr == null) { - _localDewif = chestBox.get(configBox.get('currentChest')).dewif; - } else { - _localDewif = _walletNbr; - } + // TODOo: Get real Dewif lenght + // String _localDewif; + // if (_walletNbr is int || _walletNbr == null) { + // _localDewif = chestBox.get(configBox.get('currentChest')).dewif; + // } else { + // _localDewif = _walletNbr; + // } - final int _pinLenght = DubpRust.getDewifSecretCodeLen( - dewif: _localDewif, secretCodeType: SecretCodeType.letters); + // final int _pinLenght = DubpRust.getDewifSecretCodeLen( + // dewif: _localDewif, secretCodeType: SecretCodeType.letters); - return _pinLenght; + return pinLength; } - void _renameWallet(List _walletID, _newName, {bool isCesium}) async { + Future getBalance(String pubkey, {bool isUd = false}) async { + final node = Gva(node: endPointGVA); + return await node.balance(pubkey, ud: isUd); + } + + void _renameWallet(List _walletID, _newName, + {required bool isCesium}) async { if (isCesium) { - ChestData _chestTarget = chestBox.get(_walletID[0]); + ChestData _chestTarget = chestBox.get(_walletID[0])!; _chestTarget.name = _newName; await chestBox.put(_chestTarget.key, _chestTarget); } else { MyWalletsProvider myWalletClass = MyWalletsProvider(); - WalletData _walletTarget = myWalletClass.getWalletData(_walletID); + WalletData _walletTarget = myWalletClass.getWalletData(_walletID)!; _walletTarget.name = _newName; await walletBox.put(_walletTarget.key, _walletTarget); } @@ -140,12 +138,12 @@ class WalletOptionsProvider with ChangeNotifier { _newWalletName.text = ''; } - bool editWalletName(List _wID, {bool isCesium}) { + bool editWalletName(List _wID, {bool? isCesium}) { bool nameState; if (isEditing) { if (!nameController.text.contains(':') && nameController.text.length <= 39) { - _renameWallet(_wID, nameController.text, isCesium: isCesium); + _renameWallet(_wID, nameController.text, isCesium: isCesium!); nameState = true; } else { nameState = false; @@ -160,9 +158,9 @@ class WalletOptionsProvider with ChangeNotifier { } Future deleteWallet(context, WalletData wallet) async { - final bool _answer = await _confirmDeletingWallet(context, wallet.name); + final bool? _answer = await (_confirmDeletingWallet(context, wallet.name)); - if (_answer) { + if (_answer!) { walletBox.delete(wallet.key); Navigator.popUntil( @@ -173,7 +171,7 @@ class WalletOptionsProvider with ChangeNotifier { return 0; } - Future _confirmDeletingWallet(context, _walletName) async { + Future _confirmDeletingWallet(context, _walletName) async { return showDialog( context: context, barrierDismissible: true, // user must tap button! @@ -216,7 +214,6 @@ class WalletOptionsProvider with ChangeNotifier { } String getShortPubkey(String pubkey) { - log.d(pubkey); List pubkeyByte = Base58Decode(pubkey); Digest pubkeyS256 = sha256.convert(sha256.convert(pubkeyByte).bytes); String pubkeyCheksum = Base58Encode(pubkeyS256.bytes); @@ -237,15 +234,11 @@ class WalletOptionsProvider with ChangeNotifier { notifyListeners(); } - Future generateQRcode(String _pubkey) async { - return await scanner.generateBarCode(_pubkey); - } - Future changeAvatar() async { File _image; final picker = ImagePicker(); - XFile pickedFile = await picker.pickImage(source: ImageSource.gallery); + XFile? pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile != null) { _image = File(pickedFile.path); diff --git a/lib/models/wallets_profiles.dart b/lib/providers/wallets_profiles.dart similarity index 82% rename from lib/models/wallets_profiles.dart rename to lib/providers/wallets_profiles.dart index 21e0b05..3e09355 100644 --- a/lib/models/wallets_profiles.dart +++ b/lib/providers/wallets_profiles.dart @@ -1,12 +1,14 @@ -import 'package:dubp/dubp.dart'; +import 'dart:io'; + +import 'package:durt/durt.dart'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/my_wallets.dart'; -import 'package:gecko/models/wallet_data.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/screens/wallet_view.dart'; import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:jdenticon_dart/jdenticon_dart.dart'; import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; import 'package:qrscan/qrscan.dart' as scanner; import 'dart:math'; import 'package:intl/intl.dart'; @@ -17,24 +19,26 @@ import 'package:fast_base58/fast_base58.dart'; class WalletsProfilesProvider with ChangeNotifier { WalletsProfilesProvider(this.pubkey); - String pubkey = ''; + String? pubkey = ''; String pubkeyShort = ''; final TextEditingController outputPubkey = TextEditingController(); - List transBC; - String fetchMoreCursor; - Map pageInfo; + List? transBC; + String? fetchMoreCursor; + Map? pageInfo; bool isHistoryScreen = false; String historySwitchButtun = "Voir l'historique"; - String rawSvg; + String? rawSvg; TextEditingController payAmount = TextEditingController(); TextEditingController payComment = TextEditingController(); - num balance; + num? balance; int nRepositories = 20; int nPage = 1; Future scan(context) async { - await Permission.camera.request(); - String barcode; + if (Platform.isAndroid || Platform.isIOS) { + await Permission.camera.request(); + } + String? barcode; try { barcode = await scanner.scan(); } catch (e) { @@ -55,35 +59,33 @@ class WalletsProfilesProvider with ChangeNotifier { return barcode; } - Future pay(BuildContext context, String pinCode) async { - MyWalletsProvider _myWalletModel = MyWalletsProvider(); - int currentChest = configBox.get('currentChest'); - WalletData defaultWallet = _myWalletModel.getDefaultWallet(currentChest); + Future pay(BuildContext context, {int? derivation}) async { + MyWalletsProvider _myWalletProvider = + Provider.of(context, listen: false); + int? currentChest = configBox.get('currentChest'); + String result; - String dewif = chestBox.get(currentChest).dewif; - int derivation; - - if (chestBox.get(currentChest).isCesium) { - derivation = 0; - } else { - derivation = defaultWallet.derivation; - } - - try { - await DubpRust.simplePaymentFromTransparentAccount( - accountIndex: derivation, + if (chestBox.get(currentChest)!.isCesium!) { + result = await Gva(node: endPointGVA).pay( + recipient: pubkey!, amount: double.parse(payAmount.text), - txComment: payComment.text, - dewif: dewif, - gvaEndpoint: endPointGVA, - secretCode: pinCode, - recipient: pubkey); - return "Success"; - } catch (e) { - log.e("ERROR DUBP PAYMENTS"); - log.e(e); - return "Payments errors: $e"; + cesiumSeed: _myWalletProvider.cesiumSeed, + comment: payComment.text, + derivation: -1, + lang: appLang); + } else { + derivation ??= + _myWalletProvider.getDefaultWallet(currentChest)!.derivation!; + result = await Gva(node: endPointGVA).pay( + recipient: pubkey!, + amount: double.parse(payAmount.text), + mnemonic: _myWalletProvider.mnemonic, + comment: payComment.text, + derivation: derivation, + lang: appLang); } + + return result; } bool isPubkey(pubkey) { @@ -149,7 +151,7 @@ class WalletsProfilesProvider with ChangeNotifier { for (final trans in txs) { var direction = trans['direction']; final transaction = trans['node']; - String output; + String? output; if (direction == "RECEIVED") { for (String line in transaction['outputs']) { if (line.contains(_pubkey)) { @@ -196,14 +198,14 @@ class WalletsProfilesProvider with ChangeNotifier { return transBC; } - FetchMoreOptions checkQueryResult(result, opts, _pubkey) { - final List blockchainTX = - (result.data['txsHistoryBc']['both']['edges'] as List); + FetchMoreOptions? checkQueryResult(result, opts, _pubkey) { + final List? blockchainTX = + (result.data['txsHistoryBc']['both']['edges'] as List?); // final List mempoolTX = // (result.data['txsHistoryMp']['receiving'] as List); pageInfo = result.data['txsHistoryBc']['both']['pageInfo']; - fetchMoreCursor = pageInfo['endCursor']; + fetchMoreCursor = pageInfo!['endCursor']; if (fetchMoreCursor == null) nPage = 1; if (nPage == 1) { @@ -211,8 +213,6 @@ class WalletsProfilesProvider with ChangeNotifier { } else if (nPage == 2) { nRepositories = 100; } - log.d(nPage); - log.d(nRepositories); nPage++; if (fetchMoreCursor != null) { @@ -220,9 +220,9 @@ class WalletsProfilesProvider with ChangeNotifier { variables: {'cursor': fetchMoreCursor, 'number': nRepositories}, updateQuery: (previousResultData, fetchMoreResultData) { final List repos = [ - ...previousResultData['txsHistoryBc']['both']['edges'] + ...previousResultData!['txsHistoryBc']['both']['edges'] as List, - ...fetchMoreResultData['txsHistoryBc']['both']['edges'] + ...fetchMoreResultData!['txsHistoryBc']['both']['edges'] as List ]; @@ -291,7 +291,7 @@ class WalletsProfilesProvider with ChangeNotifier { // return balance; // } - Future getBalance(String _pubkey) async { + Future getBalance(String? _pubkey) async { while (balance == null) { await Future.delayed(const Duration(milliseconds: 50)); } diff --git a/lib/screens/avatar_fullscreen.dart b/lib/screens/avatar_fullscreen.dart index 8f833dc..682e290 100644 --- a/lib/screens/avatar_fullscreen.dart +++ b/lib/screens/avatar_fullscreen.dart @@ -8,11 +8,11 @@ import 'package:flutter/material.dart'; class AvatarFullscreen extends StatelessWidget { TextEditingController tplController = TextEditingController(); - AvatarFullscreen(this.avatar, {this.title, this.color, Key key}) + AvatarFullscreen(this.avatar, {this.title, this.color, Key? key}) : super(key: key); - final Image avatar; - final String title; - final Color color; + final Image? avatar; + final String? title; + final Color? color; @override Widget build(BuildContext context) { @@ -43,8 +43,8 @@ class AvatarFullscreen extends StatelessWidget { // height: MediaQuery.of(context).size.height, // width: MediaQuery.of(context).size.width, child: Image( - image: avatar.image, - height: avatar.height, + image: avatar!.image, + height: avatar!.height, fit: BoxFit.fitWidth), ), ), diff --git a/lib/screens/common_elements.dart b/lib/screens/common_elements.dart index bb36379..009eb48 100644 --- a/lib/screens/common_elements.dart +++ b/lib/screens/common_elements.dart @@ -8,39 +8,46 @@ class CommonElements { return const Text('Coucou'); } - Widget bubbleSpeak(String text, {double long, Key textKey}) { - return Bubble( - padding: long == null - ? const BubbleEdges.all(18) - : BubbleEdges.symmetric(horizontal: long, vertical: 30), - elevation: 5, - color: Colors.white, - margin: const BubbleEdges.fromLTRB(10, 0, 20, 10), - // nip: BubbleNip.leftTop, - child: Text( - text, - key: textKey, - style: const TextStyle( - color: Colors.black, fontSize: 18, fontWeight: FontWeight.w400), + Widget bubbleSpeak(String text, + {double? long, Key? textKey, bool isMaxWidth = true}) { + return SizedBox( + width: isMaxWidth ? double.infinity : 300, + child: Bubble( + padding: long == null + ? const BubbleEdges.all(18) + : BubbleEdges.symmetric(horizontal: long, vertical: 30), + elevation: 5, + color: Colors.white, + margin: const BubbleEdges.fromLTRB(10, 0, 20, 10), + // nip: BubbleNip.leftTop, + child: Text( + text, + key: textKey, + style: const TextStyle( + color: Colors.black, fontSize: 18, fontWeight: FontWeight.w400), + ), ), ); } - Widget bubbleSpeakRich(List text, {Key textKey}) { - return Bubble( - padding: const BubbleEdges.all(18), - elevation: 5, - color: Colors.white, - margin: const BubbleEdges.fromLTRB(10, 0, 20, 10), - // nip: BubbleNip.leftTop, - child: RichText( - key: textKey, - text: TextSpan( - style: const TextStyle( - fontSize: 18.0, - color: Colors.black, + Widget bubbleSpeakRich(List text, {Key? textKey}) { + return SizedBox( + width: double.infinity, + child: Bubble( + padding: const BubbleEdges.all(18), + elevation: 5, + color: Colors.white, + margin: const BubbleEdges.fromLTRB(10, 0, 20, 10), + // nip: BubbleNip.leftTop, + child: RichText( + key: textKey, + text: TextSpan( + style: const TextStyle( + fontSize: 18.0, + color: Colors.black, + ), + children: text, ), - children: text, ), ), ); @@ -130,7 +137,7 @@ class CommonElements { } class SmoothTransition extends PageRouteBuilder { - final Widget page; + final Widget? page; SmoothTransition({this.page}) : super( pageBuilder: ( @@ -141,8 +148,8 @@ class SmoothTransition extends PageRouteBuilder { TweenAnimationBuilder( duration: const Duration(seconds: 5), tween: Tween(begin: 200, end: 200), - builder: (BuildContext context, dynamic value, Widget child) { - return page; + builder: (BuildContext context, dynamic value, Widget? child) { + return page!; }, ), ); @@ -152,7 +159,7 @@ class FaderTransition extends PageRouteBuilder { final Widget page; final bool isFast; - FaderTransition({@required this.page, @required this.isFast}) + FaderTransition({required this.page, required this.isFast}) : super( pageBuilder: ( BuildContext context, @@ -175,7 +182,7 @@ class FaderTransition extends PageRouteBuilder { } class SlideLeftRoute extends PageRouteBuilder { - final Widget page; + final Widget? page; SlideLeftRoute({this.page}) : super( pageBuilder: ( @@ -183,7 +190,7 @@ class SlideLeftRoute extends PageRouteBuilder { Animation animation, Animation secondaryAnimation, ) => - page, + page!, transitionsBuilder: ( BuildContext context, Animation animation, @@ -207,7 +214,7 @@ class GeckoSpeechAppBar extends StatelessWidget with PreferredSizeWidget { GeckoSpeechAppBar( this.title, { - Key key, + Key? key, }) : preferredSize = const Size.fromHeight(105.4), super(key: key); diff --git a/lib/screens/history.dart b/lib/screens/history.dart index 075479b..88f133c 100644 --- a/lib/screens/history.dart +++ b/lib/screens/history.dart @@ -1,8 +1,8 @@ import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/cesium_plus.dart'; +import 'package:gecko/providers/cesium_plus.dart'; import 'package:gecko/models/queries.dart'; -import 'package:gecko/models/wallets_profiles.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; import 'package:flutter/material.dart'; import 'package:gecko/screens/avatar_fullscreen.dart'; import 'package:gecko/screens/wallet_view.dart'; @@ -12,16 +12,16 @@ import 'package:provider/provider.dart'; // ignore: must_be_immutable class HistoryScreen extends StatelessWidget with ChangeNotifier { - HistoryScreen({@required this.pubkey, this.avatar, this.username, Key key}) + HistoryScreen({required this.pubkey, this.avatar, this.username, Key? key}) : super(key: key); final ScrollController scrollController = ScrollController(); final double avatarsSize = 80; - final String pubkey; - final String username; - final Image avatar; + final String? pubkey; + final String? username; + final Image? avatar; - FetchMore fetchMore; - FetchMoreOptions opts; + FetchMore? fetchMore; + FetchMoreOptions? opts; final GlobalKey _scaffoldKey = GlobalKey(); @@ -32,8 +32,8 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { Provider.of(context, listen: false); CesiumPlusProvider _cesiumPlusProvider = Provider.of(context, listen: false); - log.i('Build pubkey : ' + pubkey); - WidgetsBinding.instance.addPostFrameCallback((_) {}); + log.i('Build pubkey : ' + pubkey!); + WidgetsBinding.instance!.addPostFrameCallback((_) {}); _historyProvider.balance = _historyProvider.transBC = null; @@ -97,11 +97,11 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { ]); } - if (result.data['balance'] == null) { + if (result.data!['balance'] == null) { _historyProvider.balance = 0.0; } else { _historyProvider.balance = _historyProvider - .removeDecimalZero(result.data['balance']['amount'] / 100); + .removeDecimalZero(result.data!['balance']['amount'] / 100); } if (result.isNotLoading) { @@ -120,12 +120,13 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { ), ), ), - onNotification: (t) { + onNotification: (dynamic t) { if (t is ScrollEndNotification && scrollController.position.pixels >= scrollController.position.maxScrollExtent * 0.7 && - _historyProvider.pageInfo['hasPreviousPage']) { - fetchMore(opts); + _historyProvider.pageInfo!['hasPreviousPage'] && + result.isNotLoading) { + fetchMore!(opts!); } return true; }); @@ -150,14 +151,14 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { : Column(children: [ getTransactionTile(context, _historyProvider), if (result.isLoading && - _historyProvider.pageInfo['hasPreviousPage']) + _historyProvider.pageInfo!['hasPreviousPage']) Row( mainAxisAlignment: MainAxisAlignment.center, children: const [ CircularProgressIndicator(), ], ), - if (!_historyProvider.pageInfo['hasPreviousPage']) + if (!_historyProvider.pageInfo!['hasPreviousPage']) Column( children: const [ SizedBox(height: 15), @@ -175,8 +176,8 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { CesiumPlusProvider _cesiumPlusProvider = Provider.of(context, listen: false); int keyID = 0; - String dateDelimiter; - String lastDateDelimiter; + String? dateDelimiter; + String? lastDateDelimiter; const double _avatarSize = 200; bool isTody = false; @@ -199,15 +200,15 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { }; return Column( - children: _historyProvider.transBC.map((repository) { + children: _historyProvider.transBC!.map((repository) { DateTime now = DateTime.now(); DateTime date = DateTime.fromMillisecondsSinceEpoch(repository[0] * 1000); String dateForm; if ({4, 10, 11, 12}.contains(date.month)) { - dateForm = "${date.day} ${monthsInYear[date.month].substring(0, 3)}."; + dateForm = "${date.day} ${monthsInYear[date.month]!.substring(0, 3)}."; } else if ({1, 2, 7, 9}.contains(date.month)) { - dateForm = "${date.day} ${monthsInYear[date.month].substring(0, 4)}."; + dateForm = "${date.day} ${monthsInYear[date.month]!.substring(0, 4)}."; } else { dateForm = "${date.day} ${monthsInYear[date.month]}"; } @@ -217,30 +218,28 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { return ((dayOfYear - date.weekday + 10) / 7).floor(); } - if (DateTime(date.year, date.month, date.day) == - DateTime(now.year, now.month, now.day) && - !isTody) { + final transactionDate = DateTime(date.year, date.month, date.day); + final todayDate = DateTime(now.year, now.month, now.day); + final yesterdayDate = DateTime(now.year, now.month, now.day - 1); + + if (transactionDate == todayDate && !isTody) { dateDelimiter = lastDateDelimiter = "Aujourd'hui"; isTody = true; - } else if (DateTime(date.year, date.month, date.day) == - DateTime(now.year, now.month, now.day - 1) && - !isYesterday) { + } else if (transactionDate == yesterdayDate && !isYesterday) { dateDelimiter = lastDateDelimiter = "Hier"; isYesterday = true; } else if (weekNumber(date) == weekNumber(now) && date.year == now.year && lastDateDelimiter != "Cette semaine" && - DateTime(date.year, date.month, date.day) != - DateTime(now.year, now.month, now.day - 1) && + transactionDate != yesterdayDate && + transactionDate != todayDate && !isThisWeek) { dateDelimiter = lastDateDelimiter = "Cette semaine"; isThisWeek = true; } else if (lastDateDelimiter != monthsInYear[date.month] && lastDateDelimiter != "${monthsInYear[date.month]} ${date.year}" && - DateTime(date.year, date.month, date.day) != - DateTime(now.year, now.month, now.day) && - DateTime(date.year, date.month, date.day) != - DateTime(now.year, now.month, now.day - 1) && + transactionDate != todayDate && + transactionDate != yesterdayDate && !(weekNumber(date) == weekNumber(now) && date.year == now.year)) { if (date.year == now.year) { dateDelimiter = lastDateDelimiter = monthsInYear[date.month]; @@ -257,7 +256,7 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { Padding( padding: const EdgeInsets.symmetric(vertical: 30), child: Text( - dateDelimiter, + dateDelimiter!, style: TextStyle( fontSize: 23, color: orangeC, fontWeight: FontWeight.w300), ), @@ -275,7 +274,7 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { future: _cesiumPlusProvider.getAvatar( repository[2], _avatarSize), builder: (BuildContext context, - AsyncSnapshot _avatar) { + AsyncSnapshot _avatar) { if (_avatar.connectionState != ConnectionState.done || _avatar.hasError) { @@ -294,11 +293,11 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { ]); } if (_avatar.hasData) { - g1WalletsBox.get(repository[2]).avatar = + g1WalletsBox.get(repository[2])?.avatar = _avatar.data; return ClipOval(child: _avatar.data); } else { - g1WalletsBox.get(repository[2]).avatar = + g1WalletsBox.get(repository[2])?.avatar = _cesiumPlusProvider .defaultAvatar(repository[2]); return _cesiumPlusProvider @@ -307,7 +306,8 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { }) : ClipOval( child: Image( - image: g1WalletsBox.get(repository[2]).avatar.image, + image: + g1WalletsBox.get(repository[2])!.avatar!.image, height: _avatarSize, ), ), @@ -406,7 +406,7 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { _historyProvider.snackCopyKey(context); }, child: Text( - _historyProvider.getShortPubkey(pubkey), + _historyProvider.getShortPubkey(pubkey!), style: const TextStyle( fontSize: 30, fontWeight: FontWeight.w800, @@ -424,17 +424,17 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { }, ), builder: (QueryResult result, - {VoidCallback refetch, FetchMore fetchMore}) { + {VoidCallback? refetch, FetchMore? fetchMore}) { if (result.isLoading || result.hasException) { return const Text('...'); - } else if (result.data['idty'] == null || - result.data['idty']['username'] == null) { + } else if (result.data!['idty'] == null || + result.data!['idty']['username'] == null) { return const Text(''); } else { return SizedBox( width: 230, child: Text( - result?.data['idty']['username'] ?? '', + result.data!['idty']['username'] ?? '', style: const TextStyle( fontSize: 27, color: Color(0xff814C00), @@ -448,7 +448,7 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { SizedBox( width: 230, child: Text( - username, + username!, style: const TextStyle( fontSize: 27, color: Color(0xff814C00), @@ -460,7 +460,7 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { FutureBuilder( future: _historyProvider.getBalance(pubkey), builder: - (BuildContext context, AsyncSnapshot _balance) { + (BuildContext context, AsyncSnapshot _balance) { if (_balance.connectionState != ConnectionState.done || _balance.hasError) { return const Text('...'); @@ -480,7 +480,7 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { FutureBuilder( future: _cesiumPlusProvider.getAvatar(pubkey, _avatarSize), builder: - (BuildContext context, AsyncSnapshot _avatar) { + (BuildContext context, AsyncSnapshot _avatar) { if (_avatar.connectionState != ConnectionState.done) { return Stack(children: [ ClipOval( @@ -512,7 +512,7 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { }, child: ClipOval( child: Image( - image: _avatar.data.image, + image: _avatar.data!.image, height: _avatarSize, fit: BoxFit.cover, ), @@ -536,7 +536,7 @@ class HistoryScreen extends StatelessWidget with ChangeNotifier { }, child: ClipOval( child: Image( - image: avatar.image, + image: avatar!.image, height: _avatarSize, fit: BoxFit.cover, ), diff --git a/lib/screens/home.dart b/lib/screens/home.dart index 776da46..23d4759 100644 --- a/lib/screens/home.dart +++ b/lib/screens/home.dart @@ -1,11 +1,10 @@ import 'package:bubble/bubble.dart'; -import 'package:dubp/dubp.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/chest_provider.dart'; -import 'package:gecko/models/wallets_profiles.dart'; +import 'package:gecko/providers/chest_provider.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; import 'package:flutter/material.dart'; -import 'package:gecko/models/home.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/home.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/models/wallet_data.dart'; import 'package:gecko/screens/myWallets/restore_chest.dart'; import 'package:gecko/screens/myWallets/unlocking_wallet.dart'; @@ -16,7 +15,7 @@ import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; class HomeScreen extends StatelessWidget { - const HomeScreen({Key key}) : super(key: key); + const HomeScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -66,13 +65,11 @@ class HomeScreen extends StatelessWidget { ); }, ), - ListTile( - title: const Text('A propos'), - onTap: () { - // Update the state of the app. - // ... - }, - ), + // ListTile( + // title: const Text('A propos'), + // onTap: () { + // }, + // ), ])), Align( alignment: FractionalOffset.bottomCenter, @@ -85,8 +82,7 @@ class HomeScreen extends StatelessWidget { body: Builder( builder: (ctx) => StatefulWrapper( onInit: () { - WidgetsBinding.instance.addPostFrameCallback((_) { - DubpRust.setup(); + WidgetsBinding.instance!.addPostFrameCallback((_) { if (isWalletsExists) homeClass.snackNode(ctx); }); }, @@ -256,7 +252,7 @@ Widget geckHome(context) { image: AssetImage('assets/home/wallet.png'), height: 75)), onTap: () { - WalletData defaultWallet = + WalletData? defaultWallet = _myWalletProvider.getDefaultWallet( configBox.get('currentChest')); Navigator.push( @@ -413,19 +409,21 @@ Widget welcomeHome(context) { ]), ), Expanded( - flex: 1, - child: Container( - decoration: BoxDecoration( - gradient: LinearGradient( - begin: Alignment.topCenter, - end: Alignment.bottomCenter, - colors: [ - Colors.transparent, - Colors.black.withOpacity(0.9), - ], - ), + flex: 1, + child: Container( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Colors.transparent, + Colors.black.withOpacity(0.9), + ], ), - child: Center( + ), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 480), child: Column(children: [ const Spacer(), Row(children: [ @@ -507,7 +505,9 @@ Widget welcomeHome(context) { SizedBox(height: isTall ? 100 : 50) ]), ), - )) + ), + ), + ) ]), ); } @@ -515,7 +515,7 @@ Widget welcomeHome(context) { class StatefulWrapper extends StatefulWidget { final Function onInit; final Widget child; - const StatefulWrapper({Key key, @required this.onInit, @required this.child}) + const StatefulWrapper({Key? key, required this.onInit, required this.child}) : super(key: key); @override _StatefulWrapperState createState() => _StatefulWrapperState(); @@ -524,9 +524,7 @@ class StatefulWrapper extends StatefulWidget { class _StatefulWrapperState extends State { @override void initState() { - if (widget.onInit != null) { - widget.onInit(); - } + widget.onInit(); super.initState(); } @@ -536,7 +534,7 @@ class _StatefulWrapperState extends State { } } -Widget bubbleSpeak(String text, {double long, Key textKey}) { +Widget bubbleSpeak(String text, {double? long, Key? textKey}) { return Bubble( padding: long == null ? const BubbleEdges.all(20) diff --git a/lib/screens/myWallets/cesium_wallet_options.dart b/lib/screens/myWallets/cesium_wallet_options.dart index b5ea61a..473bd98 100644 --- a/lib/screens/myWallets/cesium_wallet_options.dart +++ b/lib/screens/myWallets/cesium_wallet_options.dart @@ -1,25 +1,26 @@ +import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; import 'package:gecko/models/chest_data.dart'; -import 'package:gecko/models/chest_provider.dart'; -import 'package:gecko/models/wallets_profiles.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/chest_provider.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/models/queries.dart'; -import 'package:gecko/models/wallet_options.dart'; +import 'package:gecko/providers/wallet_options.dart'; import 'package:gecko/screens/history.dart'; import 'package:gecko/screens/myWallets/change_pin.dart'; import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:provider/provider.dart'; import 'package:flutter/services.dart'; +import 'package:qr_flutter/qr_flutter.dart'; -int _nbrLinesName = 1; bool _isNewNameValid = false; class CesiumWalletOptions extends StatelessWidget { const CesiumWalletOptions( - {Key key, Key keyMyWallets, @required this.cesiumWallet}) + {Key? key, Key? keyMyWallets, required this.cesiumWallet}) : super(key: key); final ChestData cesiumWallet; @@ -39,20 +40,12 @@ class CesiumWalletOptions extends StatelessWidget { final String shortPubkey = _walletOptions.getShortPubkey(_walletOptions.pubkey.text); - if (_walletOptions.nameController.text == null || - _isNewNameValid == false) { - _walletOptions.nameController.text = cesiumWallet.name; + if (_isNewNameValid == false) { + _walletOptions.nameController.text = cesiumWallet.name!; } else { cesiumWallet.name = _walletOptions.nameController.text; } - _walletOptions.nameController.text.length >= 15 - ? _nbrLinesName = 2 - : _nbrLinesName = 1; - if (_walletOptions.nameController.text.length >= 26 && isTall) { - _nbrLinesName = 3; - } - return WillPopScope( onWillPop: () { _walletOptions.isEditing = false; @@ -101,40 +94,40 @@ class CesiumWalletOptions extends StatelessWidget { const Color(0xfffafafa), ], )), - child: Row(children: [ - const SizedBox(width: 25), - InkWell( - onTap: () async { - File newAvatar = await _walletOptions.changeAvatar(); - if (newAvatar != null) { - cesiumWallet.imageFile = newAvatar; - } - _walletOptions.reloadBuild(); - }, - child: cesiumWallet.imageFile == null - ? Image.asset( - 'assets/chests/${cesiumWallet.imageName}', - width: 110, - ) - : Image.file(cesiumWallet.imageFile, width: 110), - ), - InkWell( - onTap: () async { - File newAvatar = await _walletOptions.changeAvatar(); - if (newAvatar != null) { + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + const Spacer(flex: 1), + InkWell( + onTap: () async { + File newAvatar = + await (_walletOptions.changeAvatar()); cesiumWallet.imageFile = newAvatar; - } - _walletOptions.reloadBuild(); - }, - child: Column(children: [ - Image.asset( - 'assets/walletOptions/camera.png', - height: 40, - ), - const SizedBox(height: 80) - ])), - Column(children: [ - Row(children: [ + _walletOptions.reloadBuild(); + }, + child: cesiumWallet.imageFile == null + ? Image.asset( + 'assets/chests/${cesiumWallet.imageName}', + width: 110, + ) + : Image.file(cesiumWallet.imageFile!, width: 110), + ), + InkWell( + onTap: () async { + File newAvatar = + await (_walletOptions.changeAvatar()); + cesiumWallet.imageFile = newAvatar; + _walletOptions.reloadBuild(); + }, + child: Column(children: [ + Image.asset( + 'assets/walletOptions/camera.png', + height: 40, + ), + const SizedBox(height: 80) + ])), + const Spacer(flex: 1), Column(children: [ SizedBox( width: 260, @@ -144,7 +137,8 @@ class CesiumWalletOptions extends StatelessWidget { focusNode: _walletOptions.walletNameFocus, enabled: _walletOptions.isEditing, controller: _walletOptions.nameController, - maxLines: _nbrLinesName, + minLines: 1, + maxLines: 3, textAlign: TextAlign.center, decoration: const InputDecoration( border: InputBorder.none, @@ -154,10 +148,10 @@ class CesiumWalletOptions extends StatelessWidget { contentPadding: EdgeInsets.all(15.0), ), style: TextStyle( - fontSize: isTall ? 27 : 23, - color: Colors.black, - fontWeight: FontWeight.w400, - fontFamily: 'Monospace')), + fontSize: isTall ? 27 : 23, + color: Colors.black, + fontWeight: FontWeight.w400, + )), ), SizedBox(height: isTall ? 5 : 0), Query( @@ -169,7 +163,7 @@ class CesiumWalletOptions extends StatelessWidget { // pollInterval: Duration(seconds: 1), ), builder: (QueryResult result, - {VoidCallback refetch, FetchMore fetchMore}) { + {VoidCallback? refetch, FetchMore? fetchMore}) { if (result.hasException) { return Text(result.exception.toString()); } @@ -180,13 +174,13 @@ class CesiumWalletOptions extends StatelessWidget { // List repositories = result.data['viewer']['repositories']['nodes']; String wBalanceUD; - if (result.data['balance'] == null) { + if (result.data!['balance'] == null) { wBalanceUD = '0.0'; } else { int wBalanceG1 = - result.data['balance']['amount']; + result.data!['balance']['amount']; int currentUD = - result.data['currentUd']['amount']; + result.data!['currentUd']['amount']; double wBalanceUDBrut = wBalanceG1 / currentUD; // .toString(); wBalanceUD = double.parse( @@ -196,10 +190,12 @@ class CesiumWalletOptions extends StatelessWidget { return Row(children: [ ImageFiltered( imageFilter: ImageFilter.blur( - sigmaX: - _walletOptions.isBalanceBlur ? 6 : 0, - sigmaY: - _walletOptions.isBalanceBlur ? 5 : 0), + sigmaX: _walletOptions.isBalanceBlur + ? 6 + : 0.001, + sigmaY: _walletOptions.isBalanceBlur + ? 5 + : 0.001), child: Text(wBalanceUD, style: TextStyle( fontSize: isTall ? 20 : 18, @@ -232,7 +228,6 @@ class CesiumWalletOptions extends StatelessWidget { ), ), ]), - const SizedBox(width: 0), Column(children: [ InkWell( key: const Key('renameWallet'), @@ -255,22 +250,17 @@ class CesiumWalletOptions extends StatelessWidget { const SizedBox( height: 60, ) - ]) + ]), + const Spacer(flex: 3), ]), - ]), - ]), ); }), SizedBox(height: 4 * ratio), - FutureBuilder( - future: - _walletOptions.generateQRcode(_walletOptions.pubkey.text), - builder: (context, snapshot) { - return snapshot.data != null - ? Image.memory(snapshot.data, - height: isTall ? 300 : 270) - : const Text('-', style: TextStyle(fontSize: 20)); - }), + QrImage( + data: _walletOptions.pubkey.text, + version: QrVersions.auto, + size: isTall ? 300 : 270, + ), SizedBox(height: 15 * ratio), GestureDetector( key: const Key('copyPubkey'), @@ -358,7 +348,7 @@ class CesiumWalletOptions extends StatelessWidget { key: const Key('changePin'), onTap: () async { // await _chestProvider.changePin(context, cesiumWallet); - String newPin = await Navigator.push( + String? newPin = await Navigator.push( context, MaterialPageRoute( builder: (context) { diff --git a/lib/screens/myWallets/change_pin.dart b/lib/screens/myWallets/change_pin.dart index b429efb..1366e67 100644 --- a/lib/screens/myWallets/change_pin.dart +++ b/lib/screens/myWallets/change_pin.dart @@ -1,23 +1,22 @@ import 'package:flutter/material.dart'; -import 'package:dubp/dubp.dart'; +import 'package:durt/durt.dart'; import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/change_pin.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/change_pin.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'dart:io'; import 'package:provider/provider.dart'; // ignore: must_be_immutable class ChangePinScreen extends StatelessWidget with ChangeNotifier { ChangePinScreen( - {Key keyMyWallets, - @required this.walletName, - @required this.walletProvider}) + {Key? keyMyWallets, + required this.walletName, + required this.walletProvider}) : super(key: keyMyWallets); - final String walletName; + final String? walletName; final MyWalletsProvider walletProvider; - Directory appPath; - NewWallet _newWalletFile; + Directory? appPath; @override Widget build(BuildContext context) { @@ -42,16 +41,15 @@ class ChangePinScreen extends StatelessWidget with ChangeNotifier { }), title: SizedBox( height: 22, - child: Text(walletName), + child: Text(walletName!), ), ), body: Center( child: SafeArea( child: Column(children: [ StatefulWrapper( - onInit: () async { - _newWalletFile = - await _changePin.changePin(walletProvider.pinCode); + onInit: () { + _changePin.newPin.text = randomSecretCode(pinLength); }, child: Container(), ), @@ -82,8 +80,7 @@ class ChangePinScreen extends StatelessWidget with ChangeNotifier { icon: const Icon(Icons.replay), color: orangeC, onPressed: () async { - _newWalletFile = - await _changePin.changePin(walletProvider.pinCode); + _changePin.newPin.text = randomSecretCode(pinLength); }, ), ], @@ -98,13 +95,14 @@ class ChangePinScreen extends StatelessWidget with ChangeNotifier { primary: Colors.green[400], //smoothYellow, // background onPrimary: Colors.black, // foreground ), - onPressed: _changePin.newPin.text != '' - ? () { - _changePin.newPin.text = ''; - _changePin.storeNewPinChest(context, _newWalletFile); - walletProvider.pinCode = _changePin.newPin.text; - } - : null, + onPressed: () async { + NewWallet? _newWalletFile = await _changePin.changePin( + walletProvider.pinCode, + newCustomPin: _changePin.newPin.text); + _changePin.newPin.text = ''; + _changePin.storeNewPinChest(context, _newWalletFile!); + walletProvider.pinCode = _changePin.newPin.text; + }, child: const Text( 'Confirmer', style: TextStyle(fontSize: 28), @@ -122,7 +120,7 @@ class ChangePinScreen extends StatelessWidget with ChangeNotifier { class StatefulWrapper extends StatefulWidget { final Function onInit; final Widget child; - const StatefulWrapper({Key key, @required this.onInit, @required this.child}) + const StatefulWrapper({Key? key, required this.onInit, required this.child}) : super(key: key); @override _StatefulWrapperState createState() => _StatefulWrapperState(); @@ -131,9 +129,7 @@ class StatefulWrapper extends StatefulWidget { class _StatefulWrapperState extends State { @override void initState() { - if (widget.onInit != null) { - widget.onInit(); - } + widget.onInit(); super.initState(); } diff --git a/lib/screens/myWallets/chest_options.dart b/lib/screens/myWallets/chest_options.dart index d9acdd5..5b6e524 100644 --- a/lib/screens/myWallets/chest_options.dart +++ b/lib/screens/myWallets/chest_options.dart @@ -2,13 +2,13 @@ import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; import 'package:gecko/models/chest_data.dart'; import 'package:flutter/services.dart'; -import 'package:gecko/models/chest_provider.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/chest_provider.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/screens/myWallets/change_pin.dart'; import 'package:provider/provider.dart'; class ChestOptions extends StatelessWidget { - const ChestOptions({Key keyMyWallets, @required this.walletProvider}) + const ChestOptions({Key? keyMyWallets, required this.walletProvider}) : super(key: keyMyWallets); final MyWalletsProvider walletProvider; @@ -18,7 +18,7 @@ class ChestOptions extends StatelessWidget { ChestProvider _chestProvider = Provider.of(context, listen: false); - ChestData currentChest = chestBox.get(configBox.get('currentChest')); + ChestData currentChest = chestBox.get(configBox.get('currentChest'))!; return Scaffold( resizeToAvoidBottomInset: false, @@ -34,7 +34,7 @@ class ChestOptions extends StatelessWidget { }), title: SizedBox( height: 22, - child: Text(currentChest.name), + child: Text(currentChest.name!), )), body: Builder( builder: (ctx) => SafeArea( @@ -44,7 +44,7 @@ class ChestOptions extends StatelessWidget { key: const Key('changePin'), onTap: () async { // await _chestProvider.changePin(context, cesiumWallet); - String pinResult = await Navigator.push( + String? pinResult = await Navigator.push( context, MaterialPageRoute( builder: (context) { @@ -69,8 +69,10 @@ class ChestOptions extends StatelessWidget { height: 25, ), const SizedBox(width: 18), - const Text('Changer mon code secret', - style: TextStyle(fontSize: 20, color: Colors.black)), + const Text( + 'Changer mon code secret', + style: TextStyle(fontSize: 20, color: Colors.black), + ), ])), ), SizedBox(height: 10 * ratio), diff --git a/lib/screens/myWallets/choose_chest.dart b/lib/screens/myWallets/choose_chest.dart index 7179903..c9b7aad 100644 --- a/lib/screens/myWallets/choose_chest.dart +++ b/lib/screens/myWallets/choose_chest.dart @@ -1,6 +1,6 @@ import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/models/wallet_data.dart'; import 'package:flutter/material.dart'; import 'package:gecko/screens/myWallets/generate_wallets.dart'; @@ -9,8 +9,8 @@ import 'package:carousel_slider/carousel_slider.dart'; import 'package:provider/provider.dart'; class ChooseChest extends StatefulWidget { - const ChooseChest({this.action, Key key}) : super(key: key); - final String action; + const ChooseChest({this.action, Key? key}) : super(key: key); + final String? action; @override State createState() { @@ -22,7 +22,7 @@ class ChooseChest extends StatefulWidget { class _ChooseChestState extends State { TextEditingController tplController = TextEditingController(); CarouselController buttonCarouselController = CarouselController(); - int currentChest = configBox.get('currentChest'); + int? currentChest = configBox.get('currentChest'); @override Widget build(BuildContext context) { @@ -51,9 +51,9 @@ class _ChooseChestState extends State { setState(() {}); }, enableInfiniteScroll: false, - initialPage: currentChest, + initialPage: currentChest!, enlargeCenterPage: true, - viewportFraction: 0.6, + viewportFraction: 0.5, ), items: chestBox.toMap().entries.map((i) { return Builder( @@ -65,12 +65,12 @@ class _ChooseChestState extends State { height: 150, ) : Image.file( - i.value.imageFile, + i.value.imageFile!, height: 150, ), const SizedBox(height: 30), Text( - i.value.name, + i.value.name!, style: const TextStyle(fontSize: 21), ), ]); @@ -113,7 +113,7 @@ class _ChooseChestState extends State { ), onPressed: () { configBox.put('currentChest', currentChest); - WalletData defaultWallet = + WalletData? defaultWallet = _myWalletProvider.getDefaultWallet(currentChest); _myWalletProvider.rebuildWidget(); Navigator.pushAndRemoveUntil( diff --git a/lib/screens/myWallets/choose_wallet.dart b/lib/screens/myWallets/choose_wallet.dart new file mode 100644 index 0000000..fc97230 --- /dev/null +++ b/lib/screens/myWallets/choose_wallet.dart @@ -0,0 +1,222 @@ +import 'package:flutter/services.dart'; +import 'package:gecko/globals.dart'; +import 'package:flutter/material.dart'; +import 'package:gecko/models/wallet_data.dart'; +import 'package:gecko/providers/my_wallets.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; +import 'package:gecko/screens/myWallets/wallets_home.dart'; +import 'package:provider/provider.dart'; +// import 'package:gecko/models/home.dart'; +// import 'package:provider/provider.dart'; + +// ignore: must_be_immutable +class ChooseWalletScreen extends StatelessWidget { + ChooseWalletScreen({Key? key}) : super(key: key); + int? _derivation; + List? _selectedId; + + @override + Widget build(BuildContext context) { + SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + // HomeProvider _homeProvider = Provider.of(context); + WalletsProfilesProvider _walletsProfilesProvider = + Provider.of(context); + + return Scaffold( + appBar: AppBar( + toolbarHeight: 60 * ratio, + title: const SizedBox( + height: 22, + child: Text('Choix du portefeuille source'), + )), + body: SafeArea( + child: Stack(children: [ + myWalletsTiles(context), + Positioned.fill( + bottom: 60, + child: Align( + alignment: Alignment.bottomCenter, + child: SizedBox( + width: 470, + height: 70, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + elevation: 4, + primary: orangeC, // background + onPrimary: Colors.white, // foreground + ), + onPressed: () async { + final resultPay = await _walletsProfilesProvider + .pay(context, derivation: _derivation); + await paymentsResult(context, resultPay); + }, + child: const Text( + 'Valider le paiement', + style: + TextStyle(fontSize: 24, fontWeight: FontWeight.w600), + ), + ), + ), + ), + ), + // const SizedBox(height: 160), + ]), + )); + } + + Widget myWalletsTiles(BuildContext context) { + MyWalletsProvider _myWalletProvider = + Provider.of(context); + final bool isWalletsExists = _myWalletProvider.checkIfWalletExist(); + + WalletData? defaultWallet = + _myWalletProvider.getDefaultWallet(configBox.get('currentChest')); + _selectedId ??= defaultWallet!.id(); + _derivation ??= defaultWallet!.derivation!; + + _myWalletProvider.readAllWallets(configBox.get('currentChest')); + + if (!isWalletsExists) { + return const Text(''); + } + + if (_myWalletProvider.listWallets.isEmpty) { + return Column(children: const [ + Center( + child: Text( + 'Veuillez générer votre premier portefeuille', + style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500), + )), + ]); + } + + List _listWallets = _myWalletProvider.listWallets; + final double screenWidth = MediaQuery.of(context).size.width; + int nTule = 2; + + if (screenWidth >= 900) { + nTule = 4; + } else if (screenWidth >= 650) { + nTule = 3; + } + + return CustomScrollView(slivers: [ + const SliverToBoxAdapter(child: SizedBox(height: 20)), + SliverGrid.count( + key: const Key('listWallets'), + crossAxisCount: nTule, + childAspectRatio: 1, + crossAxisSpacing: 0, + mainAxisSpacing: 0, + children: [ + for (WalletData _repository in _listWallets as Iterable) + Padding( + padding: const EdgeInsets.all(16), + child: GestureDetector( + onTap: () { + _derivation = _repository.derivation!; + _selectedId = _repository.id(); + _myWalletProvider.rebuildWidget(); + }, + child: ClipOvalShadow( + shadow: const Shadow( + color: Colors.transparent, + offset: Offset(0, 0), + blurRadius: 5, + ), + clipper: CustomClipperOval(), + child: ClipRRect( + borderRadius: + const BorderRadius.all(Radius.circular(12)), + child: Column(children: [ + Expanded( + child: Container( + width: double.infinity, + height: double.infinity, + decoration: BoxDecoration( + gradient: RadialGradient( + radius: 0.6, + colors: [ + Colors.green[400]!, + const Color(0xFFE7E7A6), + ], + )), + child: _repository.imageFile == null + ? Image.asset( + 'assets/avatars/${_repository.imageName}', + alignment: Alignment.bottomCenter, + scale: 0.5, + ) + : Image.file( + _repository.imageFile!, + alignment: Alignment.bottomCenter, + scale: 0.5, + ), + )), + ListTile( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical( + bottom: Radius.circular(12), + ), + ), + tileColor: _repository.id()[1] == _selectedId![1] + ? orangeC + : const Color(0xffFFD58D), + title: Center( + child: Padding( + padding: + const EdgeInsets.symmetric(horizontal: 5), + child: Text( + _repository.name!, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 17.0, + color: + _repository.id()[1] == _selectedId![1] + ? const Color(0xffF9F9F1) + : Colors.black, + fontStyle: FontStyle.italic), + ), + ), + ), + onTap: () { + _derivation = _repository.derivation!; + _selectedId = _repository.id(); + _myWalletProvider.rebuildWidget(); + }, + ) + ]), + ), + ), + )), + ]), + ]); + } +} + +Future paymentsResult(context, String resultPay) { + if (resultPay != "success") log.e(resultPay); + return showDialog( + context: context, + barrierDismissible: true, // user must tap button! + builder: (BuildContext context) { + return AlertDialog( + title: Text(resultPay == "success" + ? 'Paiement effecuté avec succès !' + : "Une erreur s'est produite lors du paiement:\n$resultPay"), + content: const SingleChildScrollView(child: Text('')), + actions: [ + TextButton( + child: const Text("OK"), + onPressed: () { + Navigator.popUntil( + context, + ModalRoute.withName('/'), + ); + }, + ), + ], + ); + }, + ); +} diff --git a/lib/screens/myWallets/confirm_wallet_storage.dart b/lib/screens/myWallets/confirm_wallet_storage.dart index fe7dc15..3dab6ad 100644 --- a/lib/screens/myWallets/confirm_wallet_storage.dart +++ b/lib/screens/myWallets/confirm_wallet_storage.dart @@ -1,24 +1,23 @@ import 'dart:async'; - -import 'package:dubp/dubp.dart'; +import 'package:durt/durt.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/generate_wallets.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/generate_wallets.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/screens/myWallets/unlocking_wallet.dart'; import 'package:provider/provider.dart'; // ignore: must_be_immutable class ConfirmStoreWallet extends StatelessWidget with ChangeNotifier { ConfirmStoreWallet({ - Key validationKey, - @required this.generatedMnemonic, - @required this.generatedWallet, + Key? validationKey, + required this.generatedMnemonic, + required this.generatedWallet, }) : super(key: validationKey); - String generatedMnemonic; - NewWallet generatedWallet; + String? generatedMnemonic; + NewWallet? generatedWallet; final TextEditingController _mnemonicController = TextEditingController(); final TextEditingController _inputRestoreWord = TextEditingController(); @@ -32,9 +31,9 @@ class ConfirmStoreWallet extends StatelessWidget with ChangeNotifier { Provider.of(context); MyWalletsProvider _myWalletProvider = Provider.of(context); - final int _currentChest = _myWalletProvider.getCurrentChest(); + final int? _currentChest = _myWalletProvider.getCurrentChest(); - _mnemonicController.text = generatedMnemonic; + _mnemonicController.text = generatedMnemonic!; return WillPopScope( onWillPop: () { _generateWalletProvider.isAskedWordValid = false; @@ -136,7 +135,7 @@ class ConfirmStoreWallet extends StatelessWidget with ChangeNotifier { walletName.text != '') ? () async { _generateWalletProvider.storeHDWChest( - generatedWallet, + generatedWallet!, walletName.text, context); _generateWalletProvider.isAskedWordValid = @@ -149,6 +148,9 @@ class ConfirmStoreWallet extends StatelessWidget with ChangeNotifier { await Future.delayed( const Duration(milliseconds: 50)); _myWalletProvider.rebuildWidget(); + _generateWalletProvider.pin.text = ''; + _generateWalletProvider + .mnemonicController.text = ''; Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) { return UnlockingWallet( diff --git a/lib/screens/myWallets/generate_wallets.dart b/lib/screens/myWallets/generate_wallets.dart index 0adf9d5..8851268 100644 --- a/lib/screens/myWallets/generate_wallets.dart +++ b/lib/screens/myWallets/generate_wallets.dart @@ -1,6 +1,7 @@ +import 'package:durt/durt.dart'; import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/generate_wallets.dart'; +import 'package:gecko/providers/generate_wallets.dart'; import 'package:gecko/screens/myWallets/confirm_wallet_storage.dart'; import 'package:flutter/material.dart'; import 'package:printing/printing.dart'; @@ -9,7 +10,7 @@ import 'package:super_tooltip/super_tooltip.dart'; // ignore: must_be_immutable class GenerateFastChestScreen extends StatelessWidget { - SuperTooltip tooltip; + SuperTooltip? tooltip; bool hasError = false; String validPin = 'NO PIN'; String currentText = ""; @@ -18,18 +19,37 @@ class GenerateFastChestScreen extends StatelessWidget { final GlobalKey _toolTipSentence = GlobalKey(); final GlobalKey _toolTipSecret = GlobalKey(); - GenerateFastChestScreen({Key key}) : super(key: key); + GenerateFastChestScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); GenerateWalletsProvider _generateWalletProvider = Provider.of(context); - _generateWalletProvider.generateMnemonic(); - return Scaffold( + if (_generateWalletProvider.mnemonicController.text == '') { + _generateWalletProvider.generateWordList(); + _generateWalletProvider.mnemonicController.text = + _generateWalletProvider.generatedMnemonic!; + _generateWalletProvider.pin.text = randomSecretCode(pinLength); + } + + return WillPopScope( + onWillPop: () { + _generateWalletProvider.pin.text = ''; + _generateWalletProvider.mnemonicController.text = ''; + return Future.value(true); + }, + child: Scaffold( appBar: AppBar( toolbarHeight: 60 * ratio, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.black), + onPressed: () { + _generateWalletProvider.pin.text = ''; + _generateWalletProvider.mnemonicController.text = ''; + Navigator.of(context).pop(); + }), title: const SizedBox( height: 22, child: Text('Générer un trousseau'), @@ -40,7 +60,11 @@ class GenerateFastChestScreen extends StatelessWidget { child: FittedBox( child: FloatingActionButton( heroTag: "buttonGenerateWallet", - onPressed: () => _generateWalletProvider.generateMnemonic(), + onPressed: () { + _generateWalletProvider.generateWordList(); + _generateWalletProvider.mnemonicController.text = + _generateWalletProvider.generatedMnemonic!; + }, child: SizedBox( height: 40.0, width: 40.0, @@ -50,103 +74,96 @@ class GenerateFastChestScreen extends StatelessWidget { floattingYellow, //smoothYellow, //Color.fromARGB(500, 204, 255, 255), ))), body: Builder( - builder: (ctx) => SafeArea( - child: Column(children: [ - const SizedBox(height: 20), - toolTips(_toolTipSentence, 'Phrase de restauration:', - "Notez et gardez cette phrase précieusement sur un papier, elle vous servira à restaurer votre portefeuille sur un autre appareil"), - TextField( - enabled: false, - controller: _generateWalletProvider.mnemonicController, - maxLines: 3, - textAlign: TextAlign.center, - decoration: const InputDecoration( - contentPadding: EdgeInsets.all(15.0), - ), - style: const TextStyle( - fontSize: 22.0, - color: Colors.black, - fontWeight: FontWeight.w400)), - const SizedBox(height: 8), - toolTips(_toolTipSecret, 'Code secret:', - "Retenez bien votre code secret, il vous sera demandé à chaque paiement, ainsi que pour configurer votre portefeuille"), - Stack( - alignment: Alignment.centerRight, - children: [ - TextField( - key: const Key('generatedPin'), - enabled: false, - controller: _generateWalletProvider.pin, - maxLines: 1, - textAlign: TextAlign.center, - decoration: const InputDecoration(), - style: const TextStyle( - fontSize: 30.0, - color: Colors.black, - fontWeight: FontWeight.bold)), - IconButton( - icon: const Icon(Icons.replay), - color: orangeC, - onPressed: () { - _generateWalletProvider.changePinCode( - reload: false); - }, - ), - ], - ), - const SizedBox(height: 20), - ElevatedButton( - key: const Key('storeKeychain'), - style: ElevatedButton.styleFrom( - primary: yellowC, // background - onPrimary: Colors.black, // foreground - ), - onPressed: _generateWalletProvider.walletIsGenerated - ? () async { - _generateWalletProvider.nbrWord = - _generateWalletProvider.getRandomInt(); - await Navigator.push( - context, - MaterialPageRoute(builder: (context) { - return ConfirmStoreWallet( - generatedMnemonic: - _generateWalletProvider - .generatedMnemonic, - generatedWallet: _generateWalletProvider - .actualWallet); - }), - ); - await Future.delayed( - const Duration(milliseconds: 20)); - // if (_generateWalletProvider.hasBeenStored) { - // _generateWalletProvider.hasBeenStored = false; - // await Navigator.pushAndRemoveUntil(context, - // MaterialPageRoute(builder: (context) { - // return UnlockingWallet( - // wallet: _myWalletClass.getDefaultWallet( - // configBox.get('currentChest')), - // action: "mywallets", - // ); - // }), ModalRoute.withName('/')); - // } - } - : null, - child: const Text('Enregistrer ce trousseau', - style: TextStyle(fontSize: 20))), - const SizedBox(height: 20), - GestureDetector( - onTap: () { - Navigator.push( + builder: (ctx) => SafeArea( + child: Column(children: [ + const SizedBox(height: 20), + toolTips(_toolTipSentence, 'Phrase de restauration:', + "Notez et gardez cette phrase précieusement sur un papier, elle vous servira à restaurer votre portefeuille sur un autre appareil"), + TextField( + enabled: false, + controller: _generateWalletProvider.mnemonicController, + maxLines: 3, + textAlign: TextAlign.center, + decoration: const InputDecoration( + contentPadding: EdgeInsets.all(15.0), + ), + style: const TextStyle( + fontSize: 22.0, + color: Colors.black, + fontWeight: FontWeight.w400)), + const SizedBox(height: 8), + toolTips(_toolTipSecret, 'Code secret:', + "Retenez bien votre code secret, il vous sera demandé à chaque paiement, ainsi que pour configurer votre portefeuille"), + Stack( + alignment: Alignment.centerRight, + children: [ + TextField( + key: const Key('generatedPin'), + enabled: false, + controller: _generateWalletProvider.pin, + maxLines: 1, + textAlign: TextAlign.center, + decoration: const InputDecoration(), + style: const TextStyle( + fontSize: 30.0, + color: Colors.black, + fontWeight: FontWeight.bold)), + IconButton( + icon: const Icon(Icons.replay), + color: orangeC, + onPressed: () { + _generateWalletProvider.changePinCode(reload: true); + }, + ), + ], + ), + const SizedBox(height: 20), + ElevatedButton( + key: const Key('storeKeychain'), + style: ElevatedButton.styleFrom( + primary: yellowC, // background + onPrimary: Colors.black, // foreground + ), + onPressed: _generateWalletProvider.walletIsGenerated + ? () async { + _generateWalletProvider.nbrWord = + _generateWalletProvider.getRandomInt(); + _generateWalletProvider.actualWallet = await Dewif() + .generateDewif( + _generateWalletProvider.generatedMnemonic!, + _generateWalletProvider.pin.text, + lang: appLang); + await Navigator.push( context, MaterialPageRoute(builder: (context) { - return PrintWallet( - _generateWalletProvider.generatedMnemonic); + return ConfirmStoreWallet( + generatedMnemonic: + _generateWalletProvider.generatedMnemonic, + generatedWallet: + _generateWalletProvider.actualWallet); }), ); - }, - child: const Icon(Icons.print)) - ]), - ))); + } + : null, + child: const Text('Enregistrer ce trousseau', + style: TextStyle(fontSize: 20))), + const SizedBox(height: 20), + GestureDetector( + onTap: () { + Navigator.push( + context, + MaterialPageRoute(builder: (context) { + return PrintWallet( + _generateWalletProvider.generatedMnemonic); + }), + ); + }, + child: const Icon(Icons.print)) + ]), + ), + ), + ), + ); } Widget toolTips(_key, _text, _message) { @@ -186,9 +203,9 @@ class GenerateFastChestScreen extends StatelessWidget { // ignore: must_be_immutable class PrintWallet extends StatelessWidget { - const PrintWallet(this.sentence, {Key key}) : super(key: key); + const PrintWallet(this.sentence, {Key? key}) : super(key: key); - final String sentence; + final String? sentence; @override Widget build(BuildContext context) { @@ -197,6 +214,11 @@ class PrintWallet extends StatelessWidget { return MaterialApp( home: Scaffold( appBar: AppBar( + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () { + Navigator.pop(context); + }), toolbarHeight: 60 * ratio, title: const Text('Imprimer ce trousseau')), body: PdfPreview( diff --git a/lib/screens/myWallets/import_cesium_wallet.dart b/lib/screens/myWallets/import_cesium_wallet.dart index 84e2fea..bbac4cc 100644 --- a/lib/screens/myWallets/import_cesium_wallet.dart +++ b/lib/screens/myWallets/import_cesium_wallet.dart @@ -1,189 +1,211 @@ import 'dart:async'; +import 'package:durt/durt.dart'; import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/generate_wallets.dart'; +import 'package:gecko/providers/generate_wallets.dart'; import 'package:flutter/material.dart'; -import 'package:gecko/models/my_wallets.dart'; -import 'package:gecko/models/wallet_options.dart'; +import 'package:gecko/providers/my_wallets.dart'; +import 'package:gecko/models/wallet_data.dart'; +import 'package:gecko/providers/wallet_options.dart'; +import 'package:gecko/screens/myWallets/unlocking_wallet.dart'; import 'package:provider/provider.dart'; class ImportWalletScreen extends StatelessWidget { - const ImportWalletScreen({Key key}) : super(key: key); + const ImportWalletScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); GlobalKey _toolTipSecret = GlobalKey(); - Timer _debounce; + Timer? _debounce; GenerateWalletsProvider _generateWalletProvider = - Provider.of(context); - MyWalletsProvider _myWalletProvider = - Provider.of(context); + Provider.of(context, listen: false); WalletOptionsProvider _walletOptions = - Provider.of(context); + Provider.of(context, listen: false); + MyWalletsProvider _myWalletProvider = + Provider.of(context, listen: false); + _generateWalletProvider.pin.text = randomSecretCode(pinLength); return WillPopScope( - onWillPop: () { - _generateWalletProvider.resetCesiumImportView(); - return Future.value(true); - }, - child: Scaffold( - appBar: AppBar( - toolbarHeight: 60 * ratio, - leading: IconButton( - icon: const Icon(Icons.arrow_back, color: Colors.black), + onWillPop: () { + _generateWalletProvider.resetCesiumImportView(); + return Future.value(true); + }, + child: Scaffold( + appBar: AppBar( + toolbarHeight: 60 * ratio, + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.black), + onPressed: () { + _generateWalletProvider.resetCesiumImportView(); + Navigator.of(context).pop(); + }), + title: const SizedBox( + height: 22, + child: Text('Importer un portefeuille'), + )), + body: Builder( + builder: (ctx) => SafeArea( + child: Column(children: [ + const SizedBox(height: 20), + Consumer( + builder: (context, walletProvider, _) { + return TextFormField( + autofocus: true, + onChanged: (text) { + if (_debounce?.isActive ?? false) { + _debounce!.cancel(); + } + _debounce = Timer(const Duration(milliseconds: 600), () { + walletProvider + .generateCesiumWalletPubkey( + text, walletProvider.cesiumPWD.text) + .then((value) { + walletProvider.canImport = true; + walletProvider.reloadBuild(); + }); + }); + }, + keyboardType: TextInputType.text, + controller: walletProvider.cesiumID, + obscureText: !walletProvider + .isCesiumIDVisible, //This will obscure text dynamically + decoration: InputDecoration( + hintText: 'Entrez votre identifiant Cesium', + suffixIcon: IconButton( + icon: Icon( + walletProvider.isCesiumIDVisible + ? Icons.visibility + : Icons.visibility_off, + color: Colors.black, + ), + onPressed: () { + walletProvider.cesiumIDisVisible(); + }, + ), + ), + ); + }), + const SizedBox(height: 15), + Consumer( + builder: (context, walletProvider, _) { + return TextFormField( + onChanged: (text) { + if (_debounce?.isActive ?? false) { + _debounce!.cancel(); + } + _debounce = Timer(const Duration(milliseconds: 600), () { + walletProvider + .generateCesiumWalletPubkey( + walletProvider.cesiumID.text, text) + .then((value) { + walletProvider.canImport = true; + walletProvider.reloadBuild(); + }); + }); + }, + keyboardType: TextInputType.text, + controller: walletProvider.cesiumPWD, + obscureText: !walletProvider + .isCesiumPWDVisible, //This will obscure text dynamically + decoration: InputDecoration( + hintText: 'Entrez votre mot de passe Cesium', + suffixIcon: IconButton( + icon: Icon( + walletProvider.isCesiumPWDVisible + ? Icons.visibility + : Icons.visibility_off, + color: Colors.black, + ), + onPressed: () { + walletProvider.cesiumPWDisVisible(); + }, + ), + ), + ); + }), + const SizedBox(height: 15), + GestureDetector( + onTap: () { + Clipboard.setData(ClipboardData( + text: _generateWalletProvider.cesiumPubkey.text)); + _walletOptions.snackCopyKey(ctx); + }, + child: Consumer( + builder: (context, walletProvider, _) { + return Text( + _generateWalletProvider.cesiumPubkey.text, + style: const TextStyle( + fontSize: 14.0, + color: Colors.black, + fontWeight: FontWeight.bold, + fontFamily: 'Monospace'), + ); + }), + ), + const SizedBox(height: 20), + toolTips(_toolTipSecret, 'Code secret:', + "Retenez bien votre code secret, il vous sera demandé à chaque paiement, ainsi que pour configurer votre portefeuille"), + Stack( + alignment: Alignment.centerRight, + children: [ + TextField( + enabled: false, + controller: _generateWalletProvider.pin, + maxLines: 1, + textAlign: TextAlign.center, + decoration: const InputDecoration(), + style: const TextStyle( + fontSize: 30.0, + color: Colors.black, + fontWeight: FontWeight.bold)), + IconButton( + icon: const Icon(Icons.replay), + color: orangeC, onPressed: () { - _generateWalletProvider.resetCesiumImportView(); - Navigator.of(context).pop(); - }), - title: const SizedBox( - height: 22, - child: Text('Importer un portefeuille'), - )), - body: Builder( - builder: (ctx) => SafeArea( - child: Column(children: [ - const SizedBox(height: 20), - TextFormField( - onChanged: (text) { - if (_debounce?.isActive ?? false) { - _debounce.cancel(); - } - _debounce = - Timer(const Duration(milliseconds: 200), () { - _generateWalletProvider - .generateCesiumWalletPubkey(text, - _generateWalletProvider.cesiumPWD.text) - .then((value) { - _generateWalletProvider.canImport = true; - _generateWalletProvider.reloadBuild(); - }); - }); - }, - keyboardType: TextInputType.text, - controller: _generateWalletProvider.cesiumID, - obscureText: !_generateWalletProvider - .isCesiumIDVisible, //This will obscure text dynamically - decoration: InputDecoration( - hintText: 'Entrez votre identifiant Cesium', - suffixIcon: IconButton( - icon: Icon( - _generateWalletProvider.isCesiumIDVisible - ? Icons.visibility - : Icons.visibility_off, - color: Colors.black, - ), - onPressed: () { - _generateWalletProvider.cesiumIDisVisible(); - }, - ), - ), - ), - const SizedBox(height: 15), - TextFormField( - onChanged: (text) { - if (_debounce?.isActive ?? false) { - _debounce.cancel(); - } - _debounce = - Timer(const Duration(milliseconds: 200), () { - _generateWalletProvider - .generateCesiumWalletPubkey( - _generateWalletProvider.cesiumID.text, - text) - .then((value) { - _generateWalletProvider.canImport = true; - _generateWalletProvider.reloadBuild(); - }); - }); - }, - keyboardType: TextInputType.text, - controller: _generateWalletProvider.cesiumPWD, - obscureText: !_generateWalletProvider - .isCesiumPWDVisible, //This will obscure text dynamically - decoration: InputDecoration( - hintText: 'Entrez votre mot de passe Cesium', - suffixIcon: IconButton( - icon: Icon( - _generateWalletProvider.isCesiumPWDVisible - ? Icons.visibility - : Icons.visibility_off, - color: Colors.black, - ), - onPressed: () { - _generateWalletProvider.cesiumPWDisVisible(); - }, - ), - ), - ), - const SizedBox(height: 15), - GestureDetector( - onTap: () { - Clipboard.setData(ClipboardData( - text: _generateWalletProvider - .cesiumPubkey.text)); - _walletOptions.snackCopyKey(ctx); - }, - child: Text( - _generateWalletProvider.cesiumPubkey.text, - style: const TextStyle( - fontSize: 14.0, - color: Colors.black, - fontWeight: FontWeight.bold, - fontFamily: 'Monospace'), - )), - const SizedBox(height: 20), - toolTips(_toolTipSecret, 'Code secret:', - "Retenez bien votre code secret, il vous sera demandé à chaque paiement, ainsi que pour configurer votre portefeuille"), - Stack( - alignment: Alignment.centerRight, - children: [ - TextField( - enabled: false, - controller: _generateWalletProvider.pin, - maxLines: 1, - textAlign: TextAlign.center, - decoration: const InputDecoration(), - style: const TextStyle( - fontSize: 30.0, - color: Colors.black, - fontWeight: FontWeight.bold)), - IconButton( - icon: const Icon(Icons.replay), - color: orangeC, - onPressed: () { - _generateWalletProvider.changePinCode( - reload: true); - }, - ), - ], - ), - const SizedBox(height: 30), - ElevatedButton( - style: ElevatedButton.styleFrom( - primary: yellowC, // background - onPrimary: Colors.black, // foreground - ), - onPressed: _generateWalletProvider.canImport && - _generateWalletProvider.isPinChanged - ? () { - _generateWalletProvider - .importCesiumWallet() - .then((value) { - _myWalletProvider.rebuildWidget(); - _generateWalletProvider - .resetCesiumImportView(); - Navigator.popUntil( - context, - ModalRoute.withName('/'), - ); - }); - } - : null, - child: const Text('Importer ce portefeuille Cesium', - style: TextStyle(fontSize: 20))), - ]), - )))); + _generateWalletProvider.changePinCode(reload: true); + }, + ), + ], + ), + const SizedBox(height: 30), + Consumer( + builder: (context, walletProvider, _) { + return ElevatedButton( + style: ElevatedButton.styleFrom( + primary: yellowC, // background + onPrimary: Colors.black, // foreground + ), + onPressed: walletProvider.canImport + ? () async { + final chestKey = + await walletProvider.importCesiumWallet(); + _myWalletProvider.rebuildWidget(); + + await Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (context) { + return UnlockingWallet( + wallet: WalletData(chest: chestKey), + action: "mywallets", + ); + }), + ModalRoute.withName('/'), + ); + _generateWalletProvider.resetCesiumImportView(); + } + : null, + child: const Text( + 'Importer ce portefeuille Cesium', + style: TextStyle(fontSize: 20), + ), + ); + }), + ]), + ), + ), + ), + ); } Widget toolTips(_key, _text, _message) { diff --git a/lib/screens/myWallets/restore_chest.dart b/lib/screens/myWallets/restore_chest.dart index 9f8b1eb..79c798e 100644 --- a/lib/screens/myWallets/restore_chest.dart +++ b/lib/screens/myWallets/restore_chest.dart @@ -2,7 +2,7 @@ import 'package:bubble/bubble.dart'; import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; import 'package:flutter/material.dart'; -import 'package:gecko/models/generate_wallets.dart'; +import 'package:gecko/providers/generate_wallets.dart'; import 'package:gecko/screens/common_elements.dart'; import 'package:gecko/screens/onBoarding/11.dart'; import 'package:provider/provider.dart'; @@ -10,7 +10,7 @@ import 'package:provider/provider.dart'; // import 'package:provider/provider.dart'; class RestoreChest extends StatelessWidget { - const RestoreChest({Key key}) : super(key: key); + const RestoreChest({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -92,7 +92,7 @@ class RestoreChest extends StatelessWidget { await Navigator.push( context, FaderTransition( - page: OnboardingStepThirteen(), isFast: true), + page: const OnboardingStepThirteen(), isFast: true), ); } else { await badMnemonicPopup(context); @@ -160,7 +160,7 @@ class RestoreChest extends StatelessWidget { ); } - Future badMnemonicPopup(BuildContext context) async { + Future badMnemonicPopup(BuildContext context) async { return showDialog( context: context, barrierDismissible: true, // user must tap button! diff --git a/lib/screens/myWallets/transaction_comment.dart b/lib/screens/myWallets/transaction_comment.dart new file mode 100644 index 0000000..7356e1e --- /dev/null +++ b/lib/screens/myWallets/transaction_comment.dart @@ -0,0 +1,44 @@ +import 'package:flutter/services.dart'; +import 'package:gecko/globals.dart'; +import 'package:flutter/material.dart'; +// import 'package:gecko/models/home.dart'; +// import 'package:provider/provider.dart'; + +// ignore: must_be_immutable +class TransactionCommentScreen extends StatelessWidget { + TextEditingController tplController = TextEditingController(); + + TransactionCommentScreen({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + // HomeProvider _homeProvider = Provider.of(context); + return Scaffold( + appBar: AppBar( + toolbarHeight: 60 * ratio, + title: const SizedBox( + height: 22, + child: Text('Confirmer le paiement'), + ), + ), + body: SafeArea( + child: Column(children: [ + const SizedBox(height: 20), + TextField( + enabled: true, + controller: tplController, + maxLines: 1, + textAlign: TextAlign.center, + decoration: const InputDecoration( + contentPadding: EdgeInsets.all(15.0), + ), + style: const TextStyle( + fontSize: 22.0, + color: Colors.black, + fontWeight: FontWeight.w400)), + const SizedBox(height: 20), + ]), + )); + } +} diff --git a/lib/screens/myWallets/unlocking_wallet.dart b/lib/screens/myWallets/unlocking_wallet.dart index 77701af..d3ed360 100644 --- a/lib/screens/myWallets/unlocking_wallet.dart +++ b/lib/screens/myWallets/unlocking_wallet.dart @@ -1,14 +1,16 @@ import 'dart:async'; -import 'package:dubp/dubp.dart'; +import 'package:durt/durt.dart'; import 'package:flutter/services.dart'; import 'package:gecko/models/chest_data.dart'; -import 'package:gecko/models/wallets_profiles.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/models/wallet_data.dart'; -import 'package:gecko/models/wallet_options.dart'; +import 'package:gecko/providers/wallet_options.dart'; import 'package:flutter/material.dart'; import 'package:gecko/screens/myWallets/cesium_wallet_options.dart'; import 'package:gecko/screens/myWallets/choose_chest.dart'; +import 'package:gecko/screens/myWallets/choose_wallet.dart'; +import 'package:gecko/screens/myWallets/wallets_home.dart'; import 'package:pin_code_fields/pin_code_fields.dart'; import 'package:provider/provider.dart'; import 'package:gecko/globals.dart'; @@ -16,105 +18,122 @@ import 'package:gecko/globals.dart'; // ignore: must_be_immutable class UnlockingWallet extends StatelessWidget { UnlockingWallet( - {Key keyUnlockWallet, @required this.wallet, @required this.action}) + {Key? keyUnlockWallet, required this.wallet, required this.action}) : super(key: keyUnlockWallet); - WalletData wallet; + WalletData? wallet; String action; // ignore: close_sinks - StreamController errorController; + StreamController? errorController; final formKey = GlobalKey(); - var pinColor = const Color(0xffF9F9F1); + Color? pinColor = const Color(0xffF9F9F1); var walletPin = ''; - String resultPay; - - Future get badWallet => null; @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); WalletOptionsProvider _walletOptions = Provider.of(context); + final double statusBarHeight = MediaQuery.of(context).padding.top; int _pinLenght; - ChestData currentChest = chestBox.get(configBox.get('currentChest')); + ChestData currentChest = chestBox.get(configBox.get('currentChest'))!; - if (currentChest.isCesium) { + if (currentChest.isCesium!) { _pinLenght = _walletOptions.getPinLenght(currentChest.dewif); wallet = WalletData(derivation: -1, chest: currentChest.key); } else { - _pinLenght = _walletOptions.getPinLenght(wallet.number); + _pinLenght = _walletOptions.getPinLenght(wallet!.number); } errorController = StreamController(); return Scaffold( // backgroundColor: Colors.brown[600], body: SafeArea( - child: Column(children: [ - Expanded( - child: Column(children: [ - SizedBox(height: isTall ? 100 : 20), - Row(mainAxisAlignment: MainAxisAlignment.center, children: [ - currentChest.imageFile == null - ? Image.asset( - 'assets/chests/${currentChest.imageName}', - width: isTall ? 130 : 100, - ) - : Image.file( - currentChest.imageFile, - width: isTall ? 130 : 100, - ), - const SizedBox(width: 5), - SizedBox( - width: 250, - child: Text( - currentChest.name, - textAlign: TextAlign.center, - style: const TextStyle( - fontSize: 25, - color: Colors.black, - fontWeight: FontWeight.w700), - )), - ]), - SizedBox(height: 30 * ratio), - const SizedBox( - width: 400, - child: Text( - 'Pour déverrouiller votre coffre, composez votre code secret à l’abri des lézards indiscrets :', - style: TextStyle( - fontSize: 19, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Stack(children: [ + Positioned( + top: statusBarHeight + 10, + left: 15, + child: Builder( + builder: (context) => IconButton( + key: const Key('popButton'), + icon: const Icon( + Icons.arrow_back, color: Colors.black, - fontWeight: FontWeight.w400), - )), - SizedBox(height: 40 * ratio), - pinForm(context, _pinLenght, currentChest), - SizedBox(height: 3 * ratio), - InkWell( - key: const Key('chooseChest'), - onTap: () { - Navigator.push( - context, - MaterialPageRoute(builder: (context) { - return ChooseChest(action: action); - }), - ); - }, - child: SizedBox( - width: 400, - height: 70, - child: Center( - child: Text( - 'Changer de coffre', - style: TextStyle( - fontSize: 22, - color: orangeC, - fontWeight: FontWeight.w600), + size: 25, ), + onPressed: () => Navigator.pop(context), ), - )), + ), + ), + Column(children: [ + SizedBox(height: isTall ? 100 : 20), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + currentChest.imageFile == null + ? Image.asset( + 'assets/chests/${currentChest.imageName}', + width: isTall ? 130 : 100, + ) + : Image.file( + currentChest.imageFile!, + width: isTall ? 130 : 100, + ), + const SizedBox(width: 5), + SizedBox( + width: 250, + child: Text( + currentChest.name!, + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 25, + color: Colors.black, + fontWeight: FontWeight.w700), + )), + ]), + SizedBox(height: 30 * ratio), + const SizedBox( + width: 400, + child: Text( + 'Pour déverrouiller votre coffre, composez votre code secret à l’abri des lézards indiscrets :', + style: TextStyle( + fontSize: 19, + color: Colors.black, + fontWeight: FontWeight.w400), + )), + SizedBox(height: 40 * ratio), + pinForm(context, _pinLenght, currentChest), + SizedBox(height: 3 * ratio), + InkWell( + key: const Key('chooseChest'), + onTap: () { + Navigator.push( + context, + MaterialPageRoute(builder: (context) { + return ChooseChest(action: action); + }), + ); + }, + child: SizedBox( + width: 400, + height: 70, + child: Center( + child: Text( + 'Changer de coffre', + style: TextStyle( + fontSize: 22, + color: orangeC, + fontWeight: FontWeight.w600), + ), + ), + )), + ]), + ]), ]), - ), - ]), )); } @@ -150,7 +169,7 @@ class UnlockingWallet extends StatelessWidget { obscuringCharacter: '*', animationType: AnimationType.fade, validator: (v) { - if (v.length < _pinLenght) { + if (v!.length < _pinLenght) { return "Votre code PIN fait $_pinLenght caractères"; } else { return null; @@ -183,35 +202,65 @@ class UnlockingWallet extends StatelessWidget { onCompleted: (_pin) async { log.d("Completed"); _myWalletProvider.pinCode = _pin; - final String resultWallet = await _walletOptions.readLocalWallet( - context, wallet, _pin.toUpperCase(), _pinLenght); + + if (currentChest.isCesium!) { + try { + String _localDewif = chestBox.get(wallet!.chest)!.dewif!; + final cesiumWallet = + CesiumWallet.fromDewif(_localDewif, _pin.toUpperCase()); + _walletOptions.pubkey.text = cesiumWallet.pubkey; + _myWalletProvider.cesiumSeed = cesiumWallet.seed; + _myWalletProvider.mnemonic = 'cesium'; + } catch (e) { + log.e(e); + _myWalletProvider.mnemonic = 'bad'; + } + } else { + _myWalletProvider.mnemonic = _myWalletProvider.dewifToMnemonic( + context, wallet!, _pin.toUpperCase()); + } + // final String? resultWallet = _walletOptions.readLocalWallet( + // context, wallet!, _pin.toUpperCase(), _pinLenght); // _myWalletProvider.pinCode = _pin.toUpperCase(); _myWalletProvider.pinLenght = _pinLenght; - if (resultWallet == 'bad') { + if (_myWalletProvider.mnemonic == 'bad') { + await Future.delayed(const Duration(milliseconds: 50)); errorController.add(ErrorAnimationType .shake); // Triggering error shake animation pinColor = Colors.red[600]; + _myWalletProvider.pinCode = _myWalletProvider.mnemonic = ''; _walletOptions.reloadBuild(); pinFocus.requestFocus(); } else { pinColor = Colors.green[400]; - // await Future.delayed(Duration(milliseconds: 50)); if (action == "mywallets") { - currentChest.isCesium + currentChest.isCesium! ? Navigator.push( context, MaterialPageRoute(builder: (context) { return CesiumWalletOptions( cesiumWallet: currentChest); }), - ) - : Navigator.pushNamed( - formKey.currentContext, '/mywallets'); + ).then((value) => _myWalletProvider.mnemonic = '') + : Navigator.push( + context, + MaterialPageRoute(builder: (context) { + return const WalletsHome(); + }), + ).then((value) => _myWalletProvider.cesiumSeed.clear()); } else if (action == "pay") { - resultPay = - await _historyProvider.pay(context, _pin.toUpperCase()); - await _paymentsResult(context); + if (currentChest.isCesium!) { + final resultPay = await _historyProvider.pay(context); + await paymentsResult(context, resultPay); + } else { + Navigator.push( + context, + MaterialPageRoute(builder: (context) { + return ChooseWalletScreen(); + }), + ); + } } } }, @@ -223,31 +272,4 @@ class UnlockingWallet extends StatelessWidget { )), ); } - - Future _paymentsResult(context) { - if (resultPay != "Success") log.i(resultPay); - return showDialog( - context: context, - barrierDismissible: true, // user must tap button! - builder: (BuildContext context) { - return AlertDialog( - title: Text(resultPay == "Success" - ? 'Paiement effecuté avec succès !' - : "Une erreur s'est produite lors du paiement"), - content: const SingleChildScrollView(child: Text('')), - actions: [ - TextButton( - child: const Text("OK"), - onPressed: () { - Navigator.popUntil( - context, - ModalRoute.withName('/'), - ); - }, - ), - ], - ); - }, - ); - } } diff --git a/lib/screens/myWallets/wallet_options.dart b/lib/screens/myWallets/wallet_options.dart index 77fdd3d..f7f7215 100644 --- a/lib/screens/myWallets/wallet_options.dart +++ b/lib/screens/myWallets/wallet_options.dart @@ -1,24 +1,21 @@ +import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/my_wallets.dart'; -import 'package:gecko/models/queries.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/models/wallet_data.dart'; -import 'package:gecko/models/wallet_options.dart'; -import 'package:gecko/models/wallets_profiles.dart'; +import 'package:gecko/providers/wallet_options.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; import 'package:gecko/screens/history.dart'; -import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:provider/provider.dart'; import 'package:flutter/services.dart'; +import 'package:qr_flutter/qr_flutter.dart'; -// ignore: must_be_immutable class WalletOptions extends StatelessWidget { - WalletOptions({Key keyMyWallets, @required this.wallet}) + const WalletOptions({Key? keyMyWallets, required this.wallet}) : super(key: keyMyWallets); - WalletData wallet; - int _nbrLinesName = 1; - bool _isNewNameValid = false; + final WalletData wallet; @override Widget build(BuildContext context) { @@ -27,45 +24,20 @@ class WalletOptions extends StatelessWidget { Provider.of(context, listen: false); WalletsProfilesProvider _historyProvider = Provider.of(context, listen: false); - MyWalletsProvider _myWalletProvider = Provider.of(context); - final int _currentChest = _myWalletProvider.getCurrentChest(); - final String shortPubkey = - _walletOptions.getShortPubkey(_walletOptions.pubkey.text); + log.d(_walletOptions.pubkey.text); - if (_walletOptions.nameController.text == null || - _isNewNameValid == false) { - _walletOptions.nameController.text = wallet.name; - } else { - wallet.name = _walletOptions.nameController.text; - } + final int _currentChest = _myWalletProvider.getCurrentChest()!; - _walletOptions.nameController.text.length >= 15 - ? _nbrLinesName = 2 - : _nbrLinesName = 1; - if (_walletOptions.nameController.text.length >= 26 && isTall) { - _nbrLinesName = 3; - } - - WalletData defaultWallet = - _myWalletProvider.getDefaultWallet(_currentChest); - - _walletOptions.isDefaultWallet = (defaultWallet.number == wallet.id()[1]); - - int currentChest = _myWalletProvider.getCurrentChest(); - - log.d("Wallet options: $currentChest:${wallet.number}"); + log.d("Wallet options: $_currentChest:${wallet.number}"); return WillPopScope( onWillPop: () { _walletOptions.isEditing = false; _walletOptions.isBalanceBlur = true; - Navigator.popUntil( - context, - ModalRoute.withName('/mywallets'), - ); + Navigator.pop(context); return Future.value(true); }, child: Scaffold( @@ -78,10 +50,7 @@ class WalletOptions extends StatelessWidget { onPressed: () { _walletOptions.isEditing = false; _walletOptions.isBalanceBlur = true; - Navigator.popUntil( - context, - ModalRoute.withName('/mywallets'), - ); + Navigator.pop(context); }), title: SizedBox( height: 22, @@ -110,350 +79,42 @@ class WalletOptions extends StatelessWidget { const Color(0xfffafafa), ], )), - child: Row(children: [ - const SizedBox(width: 25), - InkWell( - onTap: () async { - File newAvatar = await walletProvider.changeAvatar(); - if (newAvatar != null) { - wallet.imageFile = newAvatar; - } - walletProvider.reloadBuild(); - }, - child: wallet.imageFile == null - ? Image.asset( - 'assets/avatars/${wallet.imageName}', - width: 110, - ) - : Image.file( - wallet.imageFile, - width: 110, - ), - ), - InkWell( - onTap: () async { - File newAvatar = await walletProvider.changeAvatar(); - if (newAvatar != null) { - wallet.imageFile = newAvatar; - } - walletProvider.reloadBuild(); - }, - child: Column(children: [ - Image.asset( - 'assets/walletOptions/camera.png', - height: 40, - ), - const SizedBox(height: 80) - ])), - Column(children: [ - Row(children: [ + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + const Spacer(flex: 1), + avatar(walletProvider), + const Spacer(flex: 1), Column(children: [ - SizedBox( - width: 260, - child: TextField( - key: const Key('walletName'), - autofocus: false, - focusNode: walletProvider.walletNameFocus, - enabled: walletProvider.isEditing, - controller: walletProvider.nameController, - maxLines: _nbrLinesName, - textAlign: TextAlign.center, - decoration: const InputDecoration( - border: InputBorder.none, - focusedBorder: InputBorder.none, - enabledBorder: InputBorder.none, - disabledBorder: InputBorder.none, - contentPadding: EdgeInsets.all(15.0), - ), - style: TextStyle( - fontSize: isTall ? 27 : 23, - color: Colors.black, - fontWeight: FontWeight.w400, - fontFamily: 'Monospace')), - ), + walletName(walletProvider, _walletOptions), SizedBox(height: isTall ? 5 : 0), - Query( - options: QueryOptions( - document: gql(getBalance), - variables: { - 'pubkey': walletProvider.pubkey.text, - }, - // pollInterval: Duration(seconds: 1), - ), - builder: (QueryResult result, - {VoidCallback refetch, FetchMore fetchMore}) { - if (result.hasException) { - return Text(result.exception.toString()); - } - - if (result.isLoading) { - return const Text('Loading'); - } - - // List repositories = result.data['viewer']['repositories']['nodes']; - String wBalanceUD; - if (result.data['balance'] == null) { - wBalanceUD = '0.0'; - } else if (result.hasException) { - wBalanceUD = '?'; - } else { - int wBalanceG1 = - result.data['balance']['amount']; - int currentUD = - result.data['currentUd']['amount']; - double wBalanceUDBrut = - wBalanceG1 / currentUD; // .toString(); - wBalanceUD = double.parse( - (wBalanceUDBrut).toStringAsFixed(2)) - .toString(); - } - return Row(children: [ - ImageFiltered( - imageFilter: ImageFilter.blur( - sigmaX: - walletProvider.isBalanceBlur ? 6 : 0, - sigmaY: - walletProvider.isBalanceBlur ? 5 : 0), - child: Text( - wBalanceUD, - style: TextStyle( - fontSize: isTall ? 20 : 18, - color: Colors.black), - ), - ), - Text(' DU', - style: TextStyle( - fontSize: isTall ? 20 : 18, - color: Colors.black)) - ]); - - // Text( - // '$wBalanceUD DU', - // style: TextStyle( - // fontSize: 20, color: Colors.black), - // ); - }, - ), - const SizedBox(height: 5), - InkWell( - key: const Key('displayBalance'), - onTap: () { - walletProvider.bluringBalance(); - }, - child: Image.asset( - walletProvider.isBalanceBlur - ? 'assets/walletOptions/icon_oeuil.png' - : 'assets/walletOptions/icon_oeuil_close.png', - height: 35, - ), - ), + balance(walletProvider), ]), - const SizedBox(width: 0), - Column(children: [ - InkWell( - key: const Key('renameWallet'), - onTap: () async { - _isNewNameValid = walletProvider.editWalletName( - wallet.id(), - isCesium: false); - await Future.delayed( - const Duration(milliseconds: 30)); - walletProvider.walletNameFocus.requestFocus(); - }, - child: ClipRRect( - child: Image.asset( - walletProvider.isEditing - ? 'assets/walletOptions/android-checkmark.png' - : 'assets/walletOptions/edit.png', - width: 20, - height: 20), - )), - const SizedBox( - height: 60, - ) - ]) + const Spacer(flex: 3), ]), - ]), - ]), ); }), SizedBox(height: 4 * ratio), - FutureBuilder( - future: - _walletOptions.generateQRcode(_walletOptions.pubkey.text), - builder: (context, snapshot) { - return snapshot.data != null - ? Image.memory(snapshot.data, height: isTall ? 300 : 270) - : const Text('-', style: TextStyle(fontSize: 20)); - }, + QrImage( + data: _walletOptions.pubkey.text, + version: QrVersions.auto, + size: isTall ? 300 : 270, ), SizedBox(height: 15 * ratio), Consumer( builder: (context, walletProvider, _) { return Column(children: [ - GestureDetector( - key: const Key('copyPubkey'), - onTap: () { - Clipboard.setData( - ClipboardData(text: walletProvider.pubkey.text)); - walletProvider.snackCopyKey(ctx); - }, - child: SizedBox( - height: 50, - child: Row(children: [ - const SizedBox(width: 30), - Image.asset( - 'assets/walletOptions/key.png', - height: 45, - ), - const SizedBox(width: 20), - Text("${shortPubkey.split(':')[0]}:", - style: const TextStyle( - fontSize: 22, - fontWeight: FontWeight.w800, - fontFamily: 'Monospace', - color: Colors.black)), - Text(shortPubkey.split(':')[1], - style: const TextStyle( - fontSize: 22, - fontWeight: FontWeight.w800, - fontFamily: 'Monospace')), - const SizedBox(width: 15), - SizedBox( - height: 40, - child: ElevatedButton( - style: ElevatedButton.styleFrom( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - elevation: 1, - primary: orangeC, // background - onPrimary: Colors.black, // foreground - ), - onPressed: () { - Clipboard.setData(ClipboardData( - text: walletProvider.pubkey.text)); - walletProvider.snackCopyKey(ctx); - }, - child: Row(children: [ - Image.asset( - 'assets/walletOptions/copy-white.png', - height: 25, - ), - const SizedBox(width: 7), - Text( - 'Copier', - style: TextStyle( - fontSize: 15, color: Colors.grey[50]), - ) - ]), - ), - ), - ]), - ), - ), + pubkeyWidget(walletProvider, ctx), SizedBox(height: 10 * ratio), - InkWell( - key: const Key('displayHistory'), - onTap: () { - _historyProvider.nPage = 1; - Navigator.push( - context, - MaterialPageRoute(builder: (context) { - return HistoryScreen( - pubkey: walletProvider.pubkey.text, - avatar: wallet.imageFile == null - ? Image.asset( - 'assets/avatars/${wallet.imageName}', - width: 110, - ) - : Image.file( - wallet.imageFile, - width: 110, - )); - }), - ); - }, - child: SizedBox( - height: 50, - child: Row(children: [ - const SizedBox(width: 30), - Image.asset( - 'assets/walletOptions/clock.png', - height: 45, - ), - const SizedBox(width: 22), - const Text('Historique des transactions', - style: - TextStyle(fontSize: 20, color: Colors.black)), - ]), - ), - ), + historyWidget(context, _historyProvider, walletProvider), SizedBox(height: 12 * ratio), - InkWell( - key: const Key('setDefaultWallet'), - onTap: !walletProvider.isDefaultWallet - ? () { - defaultWallet = wallet; - chestBox.get(currentChest).defaultWallet = - wallet.number; - _myWalletProvider.readAllWallets(_currentChest); - _myWalletProvider.rebuildWidget(); - } - : null, - child: SizedBox( - height: 50, - child: Row(children: [ - const SizedBox(width: 31), - CircleAvatar( - backgroundColor: Colors - .grey[walletProvider.isDefaultWallet ? 300 : 500], - child: Image.asset( - 'assets/walletOptions/android-checkmark.png', - height: 25, - ), - ), - const SizedBox(width: 22), - Text( - walletProvider.isDefaultWallet - ? 'Ce portefeuille est celui par defaut' - : 'Définir comme portefeuille par défaut', - style: TextStyle( - fontSize: 20, - color: walletProvider.isDefaultWallet - ? Colors.grey[500] - : Colors.black)), - ]), - ), - ), + setDefaultWallet(walletProvider, _myWalletProvider, + _walletOptions, _currentChest), SizedBox(height: 17 * ratio), if (!walletProvider.isDefaultWallet) - InkWell( - key: const Key('deleteWallet'), - onTap: !walletProvider.isDefaultWallet - ? () async { - await walletProvider.deleteWallet( - context, wallet); - WidgetsBinding.instance.addPostFrameCallback((_) { - _myWalletProvider.listWallets = - _myWalletProvider - .readAllWallets(_currentChest); - _myWalletProvider.rebuildWidget(); - }); - } - : null, - child: Row(children: [ - const SizedBox(width: 30), - Image.asset( - 'assets/walletOptions/trash.png', - height: 45, - ), - const SizedBox(width: 19), - const Text('Supprimer ce portefeuille', - style: TextStyle( - fontSize: 20, color: Color(0xffD80000))), - ]), - ), + deleteWallet(context, walletProvider, _myWalletProvider, + _currentChest) ]); }), ]), @@ -462,4 +123,322 @@ class WalletOptions extends StatelessWidget { ), ); } + + Widget avatar(WalletOptionsProvider walletProvider) { + return Stack( + children: [ + InkWell( + onTap: () async { + File newAvatar = await (walletProvider.changeAvatar()); + wallet.imageFile = newAvatar; + walletProvider.reloadBuild(); + }, + child: wallet.imageFile == null + ? Image.asset( + 'assets/avatars/${wallet.imageName}', + width: 110, + ) + : Image.file( + wallet.imageFile!, + width: 110, + ), + ), + Positioned( + right: 0, + top: 0, + child: InkWell( + onTap: () async { + File newAvatar = await (walletProvider.changeAvatar()); + wallet.imageFile = newAvatar; + walletProvider.reloadBuild(); + }, + child: Image.asset( + 'assets/walletOptions/camera.png', + height: 40, + ), + ), + ), + ], + ); + } + + Widget walletName(WalletOptionsProvider walletProvider, + WalletOptionsProvider _walletOptions) { + bool _isNewNameValid = false; + if (_isNewNameValid == false) { + _walletOptions.nameController.text = wallet.name!; + } else { + wallet.name = _walletOptions.nameController.text; + } + + return SizedBox( + width: 260, + child: Stack(children: [ + TextField( + key: const Key('walletName'), + autofocus: false, + focusNode: walletProvider.walletNameFocus, + enabled: walletProvider.isEditing, + controller: walletProvider.nameController, + minLines: 1, + maxLines: 3, + textAlign: TextAlign.center, + decoration: const InputDecoration( + border: InputBorder.none, + focusedBorder: InputBorder.none, + enabledBorder: InputBorder.none, + disabledBorder: InputBorder.none, + contentPadding: EdgeInsets.all(15.0), + ), + style: TextStyle( + fontSize: isTall ? 27 : 23, + color: Colors.black, + fontWeight: FontWeight.w400, + ), + ), + Positioned( + right: 0, + child: InkWell( + key: const Key('renameWallet'), + onTap: () async { + _isNewNameValid = + walletProvider.editWalletName(wallet.id(), isCesium: false); + await Future.delayed(const Duration(milliseconds: 30)); + walletProvider.walletNameFocus.requestFocus(); + }, + child: ClipRRect( + child: Image.asset( + walletProvider.isEditing + ? 'assets/walletOptions/android-checkmark.png' + : 'assets/walletOptions/edit.png', + width: 20, + height: 20), + ), + ), + ), + ]), + ); + } + + Widget balance(WalletOptionsProvider walletProvider) { + return Column(children: [ + FutureBuilder( + future: walletProvider.getBalance(walletProvider.pubkey.text), + builder: (BuildContext context, AsyncSnapshot _balance) { + if (_balance.connectionState != ConnectionState.done || + _balance.hasError) { + return Text('', + style: TextStyle( + fontSize: isTall ? 20 : 18, + )); + } + return ImageFiltered( + imageFilter: ImageFilter.blur( + sigmaX: walletProvider.isBalanceBlur ? 6 : 0, + sigmaY: walletProvider.isBalanceBlur ? 5 : 0), + child: Text( + _balance.data.toString() + ' Ğ1', + style: TextStyle( + fontSize: isTall ? 20 : 18, + ), + ), + ); + }), + const SizedBox(height: 5), + InkWell( + key: const Key('displayBalance'), + onTap: () { + walletProvider.bluringBalance(); + }, + child: Image.asset( + walletProvider.isBalanceBlur + ? 'assets/walletOptions/icon_oeuil.png' + : 'assets/walletOptions/icon_oeuil_close.png', + height: 35, + ), + ), + ]); + } + + Widget pubkeyWidget(WalletOptionsProvider walletProvider, BuildContext ctx) { + final String shortPubkey = + walletProvider.getShortPubkey(walletProvider.pubkey.text); + return GestureDetector( + key: const Key('copyPubkey'), + onTap: () { + Clipboard.setData(ClipboardData(text: walletProvider.pubkey.text)); + walletProvider.snackCopyKey(ctx); + }, + child: SizedBox( + height: 50, + child: Row(children: [ + const SizedBox(width: 30), + Image.asset( + 'assets/walletOptions/key.png', + height: 45, + ), + const SizedBox(width: 20), + Text("${shortPubkey.split(':')[0]}:", + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.w800, + fontFamily: 'Monospace', + color: Colors.black)), + Text(shortPubkey.split(':')[1], + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.w800, + fontFamily: 'Monospace')), + const SizedBox(width: 15), + SizedBox( + height: 40, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + elevation: 1, + primary: orangeC, // background + onPrimary: Colors.black, // foreground + ), + onPressed: () { + Clipboard.setData( + ClipboardData(text: walletProvider.pubkey.text)); + walletProvider.snackCopyKey(ctx); + }, + child: Row(children: [ + Image.asset( + 'assets/walletOptions/copy-white.png', + height: 25, + ), + const SizedBox(width: 7), + Text( + 'Copier', + style: TextStyle(fontSize: 15, color: Colors.grey[50]), + ) + ]), + ), + ), + ]), + ), + ); + } + + Widget historyWidget( + BuildContext context, + WalletsProfilesProvider _historyProvider, + WalletOptionsProvider walletProvider) { + return InkWell( + key: const Key('displayHistory'), + onTap: () { + _historyProvider.nPage = 1; + Navigator.push( + context, + MaterialPageRoute(builder: (context) { + return HistoryScreen( + pubkey: walletProvider.pubkey.text, + avatar: wallet.imageFile == null + ? Image.asset( + 'assets/avatars/${wallet.imageName}', + width: 110, + ) + : Image.file( + wallet.imageFile!, + width: 110, + )); + }), + ); + }, + child: SizedBox( + height: 50, + child: Row(children: [ + const SizedBox(width: 30), + Image.asset( + 'assets/walletOptions/clock.png', + height: 45, + ), + const SizedBox(width: 22), + const Text('Historique des transactions', + style: TextStyle(fontSize: 20, color: Colors.black)), + ]), + ), + ); + } + + Widget setDefaultWallet( + WalletOptionsProvider walletProvider, + MyWalletsProvider _myWalletProvider, + WalletOptionsProvider _walletOptions, + int _currentChest) { + WalletData defaultWallet = + _myWalletProvider.getDefaultWallet(_currentChest)!; + + _walletOptions.isDefaultWallet = (defaultWallet.number == wallet.id()[1]); + + return InkWell( + key: const Key('setDefaultWallet'), + onTap: !walletProvider.isDefaultWallet + ? () { + defaultWallet = wallet; + chestBox.get(_currentChest)!.defaultWallet = wallet.number; + _myWalletProvider.readAllWallets(_currentChest); + _myWalletProvider.rebuildWidget(); + } + : null, + child: SizedBox( + height: 50, + child: Row(children: [ + const SizedBox(width: 31), + CircleAvatar( + backgroundColor: + Colors.grey[walletProvider.isDefaultWallet ? 300 : 500], + child: Image.asset( + 'assets/walletOptions/android-checkmark.png', + height: 25, + ), + ), + const SizedBox(width: 22), + Text( + walletProvider.isDefaultWallet + ? 'Ce portefeuille est celui par defaut' + : 'Définir comme portefeuille par défaut', + style: TextStyle( + fontSize: 20, + color: walletProvider.isDefaultWallet + ? Colors.grey[500] + : Colors.black)), + ]), + ), + ); + } + + Widget deleteWallet( + BuildContext context, + WalletOptionsProvider walletProvider, + MyWalletsProvider _myWalletProvider, + int _currentChest) { + return InkWell( + key: const Key('deleteWallet'), + onTap: !walletProvider.isDefaultWallet + ? () async { + await walletProvider.deleteWallet(context, wallet); + WidgetsBinding.instance!.addPostFrameCallback((_) { + _myWalletProvider.listWallets = + _myWalletProvider.readAllWallets(_currentChest); + _myWalletProvider.rebuildWidget(); + }); + } + : null, + child: Row(children: [ + const SizedBox(width: 30), + Image.asset( + 'assets/walletOptions/trash.png', + height: 45, + ), + const SizedBox(width: 19), + const Text('Supprimer ce portefeuille', + style: TextStyle(fontSize: 20, color: Color(0xffD80000))), + ]), + ); + } } diff --git a/lib/screens/myWallets/wallets_home.dart b/lib/screens/myWallets/wallets_home.dart index 4d18027..c751e2d 100644 --- a/lib/screens/myWallets/wallets_home.dart +++ b/lib/screens/myWallets/wallets_home.dart @@ -1,11 +1,12 @@ +import 'package:durt/durt.dart'; import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; import 'package:gecko/models/chest_data.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/models/queries.dart'; import 'package:gecko/models/wallet_data.dart'; -import 'package:gecko/models/wallet_options.dart'; import 'package:flutter/material.dart'; +import 'package:gecko/providers/wallet_options.dart'; import 'package:gecko/screens/common_elements.dart'; import 'package:gecko/screens/myWallets/chest_options.dart'; import 'package:gecko/screens/myWallets/choose_chest.dart'; @@ -14,9 +15,7 @@ import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:provider/provider.dart'; class WalletsHome extends StatelessWidget { - final _derivationKey = GlobalKey(); - - WalletsHome({Key key}) : super(key: key); + const WalletsHome({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -24,13 +23,14 @@ class WalletsHome extends StatelessWidget { MyWalletsProvider myWalletProvider = Provider.of(context); - final int _currentChestNumber = myWalletProvider.getCurrentChest(); - final ChestData _currentChest = chestBox.get(_currentChestNumber); + final int? _currentChestNumber = myWalletProvider.getCurrentChest(); + final ChestData _currentChest = chestBox.get(_currentChestNumber)!; myWalletProvider.listWallets = myWalletProvider.readAllWallets(_currentChestNumber); return WillPopScope( onWillPop: () { + myWalletProvider.pinCode = myWalletProvider.mnemonic = ''; Navigator.popUntil( context, ModalRoute.withName('/'), @@ -43,12 +43,13 @@ class WalletsHome extends StatelessWidget { leading: IconButton( icon: const Icon(Icons.arrow_back, color: Colors.black), onPressed: () { + myWalletProvider.pinCode = myWalletProvider.mnemonic = ''; Navigator.popUntil( context, ModalRoute.withName('/'), ); }), - title: Text(_currentChest.name, + title: Text(_currentChest.name!, key: const Key('myWallets'), style: TextStyle(color: Colors.grey[850])), backgroundColor: const Color(0xffFFD58D), @@ -71,11 +72,12 @@ class WalletsHome extends StatelessWidget { return Column(children: [ const SizedBox(height: 50), SizedBox( - height: 120, - width: 445, + height: 90, + width: 420, child: ElevatedButton.icon( icon: Image.asset( 'assets/chests/config.png', + height: 60, ), style: ElevatedButton.styleFrom( elevation: 2, @@ -89,9 +91,9 @@ class WalletsHome extends StatelessWidget { }), ), label: const Text( - " Paramétrer ce coffre", + " Paramétrer ce coffre", style: TextStyle( - fontSize: 25, + fontSize: 22, fontWeight: FontWeight.w700, color: Color(0xff8a3c0f), ), @@ -99,10 +101,13 @@ class WalletsHome extends StatelessWidget { )), const SizedBox(height: 30), SizedBox( - height: 120, - width: 445, + height: 90, + width: 420, child: ElevatedButton.icon( - icon: Image.asset('assets/chests/miniChests.png'), + icon: Image.asset( + 'assets/chests/miniChests.png', + height: 70, + ), style: ElevatedButton.styleFrom( elevation: 2, primary: floattingYellow, // background @@ -115,9 +120,9 @@ class WalletsHome extends StatelessWidget { }), ), label: const Text( - " Changer de coffre", + " Changer de coffre", style: TextStyle( - fontSize: 25, + fontSize: 22, fontWeight: FontWeight.w700, color: Color(0xff8a3c0f), ), @@ -131,8 +136,7 @@ class WalletsHome extends StatelessWidget { MyWalletsProvider _myWalletProvider = Provider.of(context); WalletOptionsProvider _walletOptions = - Provider.of(context); - + Provider.of(context, listen: false); final bool isWalletsExists = _myWalletProvider.checkIfWalletExist(); if (!isWalletsExists) { @@ -151,34 +155,44 @@ class WalletsHome extends StatelessWidget { } List _listWallets = _myWalletProvider.listWallets; - WalletData defaultWallet = + WalletData? defaultWallet = _myWalletProvider.getDefaultWallet(configBox.get('currentChest')); + final double screenWidth = MediaQuery.of(context).size.width; + int nTule = 2; + + if (screenWidth >= 900) { + nTule = 4; + } else if (screenWidth >= 650) { + nTule = 3; + } return CustomScrollView(slivers: [ const SliverToBoxAdapter(child: SizedBox(height: 20)), SliverGrid.count( key: const Key('listWallets'), - crossAxisCount: 2, + crossAxisCount: nTule, childAspectRatio: 1, crossAxisSpacing: 0, mainAxisSpacing: 0, children: [ - for (WalletData _repository in _listWallets) + for (WalletData _repository in _listWallets as Iterable) Padding( padding: const EdgeInsets.all(16), child: GestureDetector( - onTap: () async { - await _walletOptions.readLocalWallet( - context, - _repository, - _myWalletProvider.pinCode, - _myWalletProvider.pinLenght); + onTap: () { + // _walletOptions.readLocalWallet(context, _repository, + // _myWalletProvider.pinCode, pinLength); + _walletOptions.pubkey.text = + HdWallet.fromMnemonic(_myWalletProvider.mnemonic) + .getPubkey(_repository.derivation!); Navigator.push( - context, - SmoothTransition( - page: WalletOptions( + context, + SmoothTransition( + page: WalletOptions( wallet: _repository, - ))); + ), + ), + ); // Navigator.push(context, // MaterialPageRoute(builder: (context) { @@ -204,7 +218,7 @@ class WalletsHome extends StatelessWidget { gradient: RadialGradient( radius: 0.6, colors: [ - Colors.green[400], + Colors.green[400]!, const Color(0xFFE7E7A6), ], )), @@ -218,7 +232,7 @@ class WalletsHome extends StatelessWidget { scale: 0.5, ) : Image.file( - _repository.imageFile, + _repository.imageFile!, alignment: Alignment.bottomCenter, scale: 0.5, ), @@ -230,7 +244,7 @@ class WalletsHome extends StatelessWidget { bottom: Radius.circular(12))), // contentPadding: const EdgeInsets.only(left: 7.0), tileColor: - _repository.id()[1] == defaultWallet.id()[1] + _repository.id()[1] == defaultWallet!.id()[1] ? orangeC : const Color(0xffFFD58D), // leading: Text('IMAGE'), @@ -242,7 +256,7 @@ class WalletsHome extends StatelessWidget { padding: const EdgeInsets.symmetric(horizontal: 5), child: Text( - _repository.name, + _repository.name!, textAlign: TextAlign.center, style: TextStyle( fontSize: 17.0, @@ -256,6 +270,15 @@ class WalletsHome extends StatelessWidget { ), // dense: true, onTap: () { + // _walletOptions.readLocalWallet( + // context, + // _repository, + // _myWalletProvider.pinCode, + // pinLength); + _walletOptions.pubkey.text = + HdWallet.fromMnemonic( + _myWalletProvider.mnemonic) + .getPubkey(_repository.derivation!); Navigator.push( context, SmoothTransition( @@ -295,7 +318,7 @@ class WalletsHome extends StatelessWidget { // pollInterval: Duration(seconds: 1), ), builder: (QueryResult result, - {VoidCallback refetch, FetchMore fetchMore}) { + {VoidCallback? refetch, FetchMore? fetchMore}) { if (result.hasException) { return Text(result.exception.toString()); } @@ -304,11 +327,11 @@ class WalletsHome extends StatelessWidget { return const Text('Loading'); } String wBalanceUD; - if (result.data['balance'] == null) { + if (result.data!['balance'] == null) { wBalanceUD = '0.0'; } else { - int wBalanceG1 = result.data['balance']['amount']; - int currentUD = result.data['currentUd']['amount']; + int wBalanceG1 = result.data!['balance']['amount']; + int currentUD = result.data!['currentUd']['amount']; double wBalanceUDBrut = wBalanceG1 / currentUD; // .toString(); wBalanceUD = double.parse((wBalanceUDBrut).toStringAsFixed(2)).toString(); @@ -322,7 +345,7 @@ class WalletsHome extends StatelessWidget { Provider.of(context); String _newDerivationName = - 'Portefeuille ${_myWalletProvider.listWallets.last.number + 2}'; + 'Portefeuille ${_myWalletProvider.listWallets.last.number! + 2}'; return Padding( padding: const EdgeInsets.all(16), child: ClipRRect( @@ -351,56 +374,6 @@ class WalletsHome extends StatelessWidget { ), ]))); } - - Widget addNewDerivationPopup(context) { - final TextEditingController _newDerivationName = TextEditingController(); - MyWalletsProvider _myWalletProvider = - Provider.of(context); - - return AlertDialog( - content: Stack( - clipBehavior: Clip.hardEdge, - children: [ - Form( - key: _derivationKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Text('Nom du portefeuille:'), - Padding( - padding: const EdgeInsets.all(8.0), - child: TextFormField( - key: const Key('DerivationNameKey'), - controller: _newDerivationName, - textAlign: TextAlign.center, - autofocus: true, - ), - ), - const SizedBox(height: 20), - Padding( - padding: const EdgeInsets.all(8.0), - child: ElevatedButton( - key: const Key('validDerivation'), - style: ElevatedButton.styleFrom( - elevation: 1, - primary: yellowC, // background - onPrimary: Colors.black, // foreground - ), - onPressed: () async { - await _myWalletProvider - .generateNewDerivation( - context, _newDerivationName.text) - .then((_) => _newDerivationName.text == ''); - }, - child: const Text("Créer")), - ) - ], - ), - ), - ], - ), - ); - } } // extension Range on num { @@ -429,10 +402,10 @@ class ClipOvalShadow extends StatelessWidget { final Widget child; const ClipOvalShadow({ - Key key, - @required this.shadow, - @required this.clipper, - @required this.child, + Key? key, + required this.shadow, + required this.clipper, + required this.child, }) : super(key: key); @override @@ -451,7 +424,7 @@ class _ClipOvalShadowPainter extends CustomPainter { final Shadow shadow; final CustomClipper clipper; - _ClipOvalShadowPainter({@required this.shadow, @required this.clipper}); + _ClipOvalShadowPainter({required this.shadow, required this.clipper}); @override void paint(Canvas canvas, Size size) { diff --git a/lib/screens/old_history_pay.dart b/lib/screens/old_history_pay.dart deleted file mode 100644 index 6ab424c..0000000 --- a/lib/screens/old_history_pay.dart +++ /dev/null @@ -1,483 +0,0 @@ -import 'package:flutter/services.dart'; -import 'package:gecko/globals.dart'; -import 'package:gecko/models/cesium_plus.dart'; -import 'package:gecko/models/home.dart'; -import 'package:gecko/models/my_wallets.dart'; -import 'package:gecko/models/queries.dart'; -import 'package:gecko/models/wallets_profiles.dart'; -import 'package:flutter/material.dart'; -import 'package:gecko/models/wallet_data.dart'; -import 'package:gecko/screens/myWallets/unlocking_wallet.dart'; -import 'package:gecko/screens/wallet_view.dart'; -import 'package:graphql_flutter/graphql_flutter.dart'; -import 'package:provider/provider.dart'; -import 'package:flutter_svg/flutter_svg.dart'; - -// ignore: must_be_immutable -class OldHistoryScreen extends StatelessWidget with ChangeNotifier { - final TextEditingController _outputPubkey = TextEditingController(); - ScrollController scrollController = ScrollController(); - final nRepositories = 20; - // HistoryProvider _historyProvider; - final _formKey = GlobalKey(); - final FocusNode _pubkeyFocus = FocusNode(); - final double avatarsSize = 80; - - FetchMore fetchMore; - FetchMoreOptions opts; - final GlobalKey _scaffoldKey = GlobalKey(); - - OldHistoryScreen({Key key}) : super(key: key); - - @override - Widget build(BuildContext context) { - SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); - WalletsProfilesProvider _historyProvider = - Provider.of(context); - HomeProvider _homeProvider = Provider.of(context); - _outputPubkey.text = _historyProvider.pubkey; - log.i('Build pubkey : ' + _historyProvider.pubkey); - WidgetsBinding.instance.addPostFrameCallback((_) {}); - - return Scaffold( - key: _scaffoldKey, - appBar: AppBar( - toolbarHeight: 60 * ratio, - title: _homeProvider.appBarExplorer, - actions: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: IconButton( - icon: _homeProvider.searchIcon, - color: Colors.grey[850], - onPressed: () { - if (_homeProvider.searchIcon.icon == Icons.search) { - _homeProvider.searchIcon = Icon( - Icons.close, - color: Colors.grey[850], - ); - _homeProvider.appBarExplorer = TextField( - autofocus: true, - controller: _homeProvider.searchQuery, - onChanged: (text) { - log.d("Clé tappé: $text"); - if (_historyProvider.isPubkey(text)) { - _homeProvider.currentIndex = 0; - Navigator.push( - context, - MaterialPageRoute(builder: (context) { - return WalletViewScreen(pubkey: text); - }), - ); - } - }, - style: TextStyle( - color: Colors.grey[850], - ), - decoration: InputDecoration( - prefixIcon: - Icon(Icons.search, color: Colors.grey[850]), - hintText: "Rechercher ...", - hintStyle: TextStyle(color: Colors.grey[850])), - ); - _homeProvider.handleSearchStart(); - } else { - _homeProvider.handleSearchEnd(); - } - })) - ], - backgroundColor: const Color(0xffFFD58D), - ), - floatingActionButton: SizedBox( - height: 80.0, - width: 80.0, - child: FittedBox( - child: FloatingActionButton( - heroTag: "buttonScan", - onPressed: () async { - await _historyProvider.scan(context); - }, - child: SizedBox( - height: 40.0, - width: 40.0, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 3), - child: Image.asset('assets/qrcode-scan.png'))), - backgroundColor: - floattingYellow, //smoothYellow, //Color.fromARGB(500, 204, 255, 255), - ), - ), - ), - body: Column(children: [ - const SizedBox(height: 0), - if (_historyProvider.pubkey != '') - historyQuery(context, _historyProvider), - ])); - } - - Widget historyQuery(context, WalletsProfilesProvider _historyProvider) { - _pubkeyFocus.unfocus(); - // HistoryProvider _historyProvider = Provider.of(context); - CesiumPlusProvider _cesiumPlusProvider = - Provider.of(context); - bool _isFirstExec = true; - return Expanded( - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.max, - children: [ - Query( - options: QueryOptions( - document: gql(getHistory), - variables: { - 'pubkey': _historyProvider.pubkey, - 'number': nRepositories, - 'cursor': null - }, - ), - builder: (QueryResult result, {fetchMore, refetch}) { - if (result.isLoading && result.data == null) { - return const Center( - child: CircularProgressIndicator(), - ); - } - - if (result.hasException) { - log.e('Error GVA: ' + result.exception.toString()); - return Column(children: const [ - SizedBox(height: 50), - Text( - "Aucun noeud GVA valide n'a pu être trouvé.\nVeuillez réessayer ultérieurement.", - style: TextStyle(fontSize: 17.0), - ) - ]); - } - - if (result.data == null && result.exception.toString() == null) { - return const Text('Aucune donnée à afficher.'); - } - - num balance; - - if (result.data['balance'] == null) { - balance = 0.0; - } else { - balance = _historyProvider - .removeDecimalZero(result.data['balance']['amount'] / 100); - } - - opts = _historyProvider.checkQueryResult( - result, opts, _outputPubkey.text); - - // _historyProvider.transBC = null; - - // Build history list - return NotificationListener( - child: Builder( - builder: (context) => Expanded( - child: ListView( - key: const Key('listTransactions'), - controller: scrollController, - children: [ - const SizedBox(height: 20), - if (_historyProvider.pubkey != '') - Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - if (_isFirstExec) - Container( - padding: const EdgeInsets.fromLTRB( - 20, 0, 30, 0), - child: FutureBuilder( - future: - _cesiumPlusProvider.getAvatar( - _historyProvider.pubkey, - 55), - builder: (BuildContext context, - AsyncSnapshot _avatar) { - if (_avatar.connectionState != - ConnectionState.done || - _avatar.hasError) { - return Stack(children: [ - _cesiumPlusProvider - .defaultAvatar(55), - Positioned( - top: 8, - right: 0, - width: 12, - height: 12, - child: - CircularProgressIndicator( - strokeWidth: 1, - color: orangeC, - ), - ), - ]); - } - if (_avatar.hasData) { - return ClipOval( - child: _avatar.data, - ); - } - return _cesiumPlusProvider - .defaultAvatar(55); - }), - ), - GestureDetector( - key: const Key('copyPubkey'), - onTap: () { - Clipboard.setData(ClipboardData( - text: _historyProvider.pubkey)); - _historyProvider.snackCopyKey(context); - }, - child: Text( - _historyProvider.getShortPubkey( - _historyProvider.pubkey), - style: const TextStyle( - fontSize: 22, - fontWeight: FontWeight.w800, - fontFamily: 'Monospace')), - ), - Container( - padding: const EdgeInsets.fromLTRB( - 30, 0, 5, 0), // .only(right: 15), - child: Card( - child: Column( - children: [ - SvgPicture.string( - _historyProvider - .generateIdenticon( - _historyProvider - .pubkey), - fit: BoxFit.contain, - height: 64, - width: 64, - ), - ], - ), - )), - const SizedBox(width: 0) - ]), - if (_isFirstExec) - Row( - mainAxisAlignment: - MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Container( - padding: - const EdgeInsets.fromLTRB(0, 0, 0, 0), - // padding: const EdgeInsets., - child: FutureBuilder( - future: _cesiumPlusProvider - .getName(_historyProvider.pubkey), - initialData: '...', - builder: (context, snapshot) { - return Text(snapshot.data ?? '-', - style: const TextStyle( - fontSize: 20)); - }), - ) - ]), - const SizedBox(height: 18), - if (_isFirstExec) - Container( - padding: - const EdgeInsets.fromLTRB(0, 0, 0, 0), - child: Text(balance.toString() + ' Ğ1', - textAlign: TextAlign.center, - style: const TextStyle(fontSize: 18.0))), - const SizedBox(height: 20), - ElevatedButton( - key: const Key('switchPayHistory'), - style: ElevatedButton.styleFrom( - elevation: 1, - primary: Colors.grey[50], // background - onPrimary: Colors.black, // foreground - ), - onPressed: () { - _historyProvider.switchProfileView(); - }, - child: Text( - _historyProvider.historySwitchButtun, - style: TextStyle( - fontSize: 15, color: orangeC))), - // const Divider( - // color: Colors.grey, - // height: 5, - // thickness: 0.5, - // indent: 0, - // endIndent: 0, - // ), - _historyProvider.isHistoryScreen - ? historyView(context, result) - : payView(context, _historyProvider), - ], - ))), - onNotification: (t) { - if (t is ScrollEndNotification && - scrollController.position.pixels >= - scrollController.position.maxScrollExtent * 0.7) { - fetchMore(opts); - } - return true; - }); - }, - ), - ], - )); - } - - Widget payView(context, WalletsProfilesProvider _historyProvider) { - MyWalletsProvider _myWalletProvider = MyWalletsProvider(); - WalletData defaultWallet = - _myWalletProvider.getDefaultWallet(configBox.get('currentChest')); - - return Stack( - clipBehavior: Clip.hardEdge, - children: [ - Form( - key: _formKey, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const SizedBox(height: 20), - const Text('Commentaire:', style: TextStyle(fontSize: 20.0)), - Padding( - padding: const EdgeInsets.all(8.0), - child: TextField( - controller: _historyProvider.payComment, - maxLines: 2, - textAlign: TextAlign.center, - decoration: const InputDecoration(), - style: const TextStyle( - fontSize: 22, - color: Colors.black, - fontWeight: FontWeight.bold))), - const SizedBox(height: 20), - const Text('Montant (DU/Ğ1):', style: TextStyle(fontSize: 20.0)), - Padding( - padding: const EdgeInsets.all(8.0), - child: TextFormField( - style: const TextStyle(fontSize: 22), - controller: _historyProvider.payAmount, - textAlign: TextAlign.center, - maxLines: 1, - keyboardType: TextInputType.number, - decoration: InputDecoration( - contentPadding: const EdgeInsets.symmetric( - vertical: 25.0, horizontal: 10.0), - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(10.0)), - ), - inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp(r'(^\d*\.?\d*)')) - ], - ), - ), - Padding( - padding: const EdgeInsets.only(top: 15), - child: OutlinedButton( - style: OutlinedButton.styleFrom( - side: BorderSide(width: 2, color: orangeC)), - onPressed: () { - // if (_formKey.currentState.validate()) { - // _formKey.currentState.save(); - // } - // _historyProvider.pay(payAmount.text, payComment.text); - Navigator.push( - context, - MaterialPageRoute(builder: (context) { - return UnlockingWallet( - wallet: defaultWallet, action: "pay"); - }), - ); - }, - child: Padding( - padding: const EdgeInsets.all(12), - child: Text( - "PAYER", - style: TextStyle(fontSize: 25, color: Colors.grey[850]), - ), - ), - ), - ) - ], - ), - ), - ], - ); - } - - Widget historyView(context, result) { - WalletsProfilesProvider _historyProvider = - Provider.of(context); - HomeProvider _homeProvider = - Provider.of(context, listen: false); - int keyID = 0; - - return _historyProvider.transBC == null - ? const Text('Aucune transaction à afficher.') - : Column(children: [ - for (var repository in _historyProvider.transBC) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 5.0), - child: ListTile( - key: Key('transaction${keyID++}'), - contentPadding: const EdgeInsets.all(5.0), - leading: Text(repository[1].toString(), - style: TextStyle( - fontSize: 12, - color: Colors.grey[800], - fontWeight: FontWeight.w700), - textAlign: TextAlign.center), - title: Text(repository[3], - style: const TextStyle( - fontSize: 15.0, fontFamily: 'Monospace'), - textAlign: TextAlign.center), - subtitle: Text(repository[6] != '' ? repository[6] : '-', - style: const TextStyle(fontSize: 12.0), - textAlign: TextAlign.center), - trailing: Text("${repository[4]} Ğ1", - style: const TextStyle(fontSize: 14.0), - textAlign: TextAlign.justify), - dense: true, - isThreeLine: false, - onTap: () { - if (_historyProvider.isPubkey(repository[2])) { - _homeProvider.currentIndex = 0; - Navigator.push( - context, - MaterialPageRoute(builder: (context) { - return WalletViewScreen(pubkey: repository[2]); - }), - ); - } - Navigator.pop(context); - }), - ), - if (result.isLoading && - _historyProvider.pageInfo['hasPreviousPage']) - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: const [ - CircularProgressIndicator(), - ], - ), - // if (_historyProvider.isTheEnd) // What I did before ... - if (!_historyProvider.pageInfo['hasPreviousPage']) - Column( - children: const [ - SizedBox(height: 15), - Text("Début de l'historique.", - textAlign: TextAlign.center, - style: TextStyle(fontSize: 20)), - SizedBox(height: 15) - ], - ) - ]); - } -} diff --git a/lib/screens/onBoarding/0_no_keychain_found.dart b/lib/screens/onBoarding/0_no_keychain_found.dart index 685bc27..12fe699 100644 --- a/lib/screens/onBoarding/0_no_keychain_found.dart +++ b/lib/screens/onBoarding/0_no_keychain_found.dart @@ -8,7 +8,7 @@ import 'package:gecko/screens/myWallets/import_cesium_wallet.dart'; import 'package:gecko/screens/onBoarding/1.dart'; class NoKeyChainScreen extends StatelessWidget { - const NoKeyChainScreen({Key key}) : super(key: key); + const NoKeyChainScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/screens/onBoarding/1.dart b/lib/screens/onBoarding/1.dart index 6cbd97c..9bd7cc5 100644 --- a/lib/screens/onBoarding/1.dart +++ b/lib/screens/onBoarding/1.dart @@ -13,7 +13,7 @@ class OnboardingStepOne extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 1; - OnboardingStepOne({Key key}) : super(key: key); + OnboardingStepOne({Key? key}) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/screens/onBoarding/10.dart b/lib/screens/onBoarding/10.dart index 8a92869..4f4aff0 100644 --- a/lib/screens/onBoarding/10.dart +++ b/lib/screens/onBoarding/10.dart @@ -11,7 +11,7 @@ class OnboardingStepTwelve extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 9; - OnboardingStepTwelve({Key key}) : super(key: key); + OnboardingStepTwelve({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -31,7 +31,7 @@ class OnboardingStepTwelve extends StatelessWidget { const SizedBox(height: 10), Image.asset( 'assets/onBoarding/plusieurs-codes-secrets-un-trousseau.png', - height: 410 * ratio, + height: isTall ? 410 : 380, ), Expanded( child: Align( @@ -50,13 +50,14 @@ class OnboardingStepTwelve extends StatelessWidget { Navigator.push( context, FaderTransition( - page: OnboardingStepThirteen(), isFast: true), + page: const OnboardingStepThirteen(), + isFast: true), ); }, child: const Text("Générer le code secret", style: TextStyle(fontSize: 20))), ))), - SizedBox(height: isTall ? 80 : 40), + const SizedBox(height: 80), ]), )); } diff --git a/lib/screens/onBoarding/11.dart b/lib/screens/onBoarding/11.dart index 58e6878..0c88222 100644 --- a/lib/screens/onBoarding/11.dart +++ b/lib/screens/onBoarding/11.dart @@ -1,20 +1,17 @@ // ignore_for_file: file_names - -import 'package:dubp/dubp.dart'; import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/generate_wallets.dart'; +import 'package:gecko/providers/generate_wallets.dart'; import 'package:gecko/screens/common_elements.dart'; import 'package:gecko/screens/onBoarding/12.dart'; import 'package:provider/provider.dart'; // ignore: must_be_immutable class OnboardingStepThirteen extends StatelessWidget { - NewWallet generatedWallet; final int progress = 10; - OnboardingStepThirteen({Key key}) : super(key: key); + const OnboardingStepThirteen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -24,19 +21,13 @@ class OnboardingStepThirteen extends StatelessWidget { // MyWalletsProvider myWalletProvider = // Provider.of(context); CommonElements common = CommonElements(); - _generateWalletProvider.pin.text = ''; + _generateWalletProvider.pin.text = + _generateWalletProvider.changePinCode(reload: false); return Scaffold( extendBodyBehindAppBar: true, body: SafeArea( child: Column(children: [ - FutureBuilder( - future: _generateWalletProvider.changePinCode(reload: false), - // initialData: '...', - builder: (context, snapshot) { - generatedWallet = snapshot.data; - return const Visibility(visible: false, child: Text('')); - }), common.onboardingProgressBar( context, 'Ma phrase de restauration', progress), common.bubbleSpeakRich( @@ -72,9 +63,8 @@ class OnboardingStepThirteen extends StatelessWidget { IconButton( icon: const Icon(Icons.replay), color: orangeC, - onPressed: () async { - generatedWallet = await _generateWalletProvider - .changePinCode(reload: false); + onPressed: () { + _generateWalletProvider.changePinCode(reload: true); }, ), ], @@ -92,9 +82,8 @@ class OnboardingStepThirteen extends StatelessWidget { primary: const Color(0xffFFD58D), onPrimary: Colors.black, // foreground ), - onPressed: () async { - generatedWallet = await _generateWalletProvider - .changePinCode(reload: false); + onPressed: () { + _generateWalletProvider.changePinCode(reload: true); }, child: const Text("Choisir un autre code secret", style: TextStyle(fontSize: 20))), @@ -116,9 +105,7 @@ class OnboardingStepThirteen extends StatelessWidget { Navigator.push( context, FaderTransition( - page: OnboardingStepFourteen( - generatedWallet: generatedWallet), - isFast: true), + page: OnboardingStepFourteen(), isFast: true), ); }, child: const Text("J'ai noté mon code secret", diff --git a/lib/screens/onBoarding/12.dart b/lib/screens/onBoarding/12.dart index ecbc27f..3832702 100644 --- a/lib/screens/onBoarding/12.dart +++ b/lib/screens/onBoarding/12.dart @@ -1,13 +1,13 @@ // ignore_for_file: file_names import 'dart:async'; -import 'package:dubp/dubp.dart'; +import 'package:durt/durt.dart'; import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/generate_wallets.dart'; -import 'package:gecko/models/my_wallets.dart'; -import 'package:gecko/models/wallet_options.dart'; +import 'package:gecko/providers/generate_wallets.dart'; +import 'package:gecko/providers/my_wallets.dart'; +import 'package:gecko/providers/wallet_options.dart'; import 'package:gecko/screens/common_elements.dart'; import 'package:gecko/screens/onBoarding/13_congratulations.dart'; import 'package:pin_code_fields/pin_code_fields.dart'; @@ -16,25 +16,23 @@ import 'package:provider/provider.dart'; // ignore: must_be_immutable class OnboardingStepFourteen extends StatelessWidget { OnboardingStepFourteen({ - Key validationKey, - @required this.generatedWallet, + Key? validationKey, }) : super(key: validationKey); - NewWallet generatedWallet; final int progress = 11; final formKey = GlobalKey(); - var pinColor = const Color(0xFFA4B600); + Color? pinColor = const Color(0xFFA4B600); bool hasError = false; @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); - // GenerateWalletsProvider _generateWalletProvider = - // Provider.of(context); + GenerateWalletsProvider _generateWalletProvider = + Provider.of(context); WalletOptionsProvider _walletOptions = Provider.of(context); CommonElements common = CommonElements(); - final int _pinLenght = _walletOptions.getPinLenght(generatedWallet.dewif); + final int _pinLenght = _generateWalletProvider.pin.text.length; return Scaffold( extendBodyBehindAppBar: true, @@ -64,7 +62,7 @@ class OnboardingStepFourteen extends StatelessWidget { GenerateWalletsProvider _generateWalletProvider = Provider.of(context); - final int _currentChest = _myWalletProvider.getCurrentChest(); + final int? _currentChest = _myWalletProvider.getCurrentChest(); return Form( key: formKey, @@ -83,7 +81,7 @@ class OnboardingStepFourteen extends StatelessWidget { obscuringCharacter: '*', animationType: AnimationType.fade, validator: (v) { - if (v.length < _pinLenght) { + if (v!.length < _pinLenght) { return "Votre code PIN fait $_pinLenght caractères"; } else { return null; @@ -114,19 +112,23 @@ class OnboardingStepFourteen extends StatelessWidget { ) ], onCompleted: (_pin) async { - _myWalletProvider.pinCode = _pin; + _myWalletProvider.pinCode = _pin.toUpperCase(); _myWalletProvider.pinLenght = _pinLenght; - final bool resultWallet = await _walletOptions.checkPinOK( - generatedWallet.dewif, _pin.toUpperCase(), _pinLenght); - if (resultWallet) { + log.d(_pin + ' || ' + _generateWalletProvider.pin.text); + if (_pin.toUpperCase() == _generateWalletProvider.pin.text) { pinColor = Colors.green[500]; - _generateWalletProvider.storeHDWChest( + NewWallet generatedWallet = await Dewif().generateDewif( + _generateWalletProvider.generatedMnemonic!, + _generateWalletProvider.pin.text, + lang: appLang); + await _generateWalletProvider.storeHDWChest( generatedWallet, 'Mon portefeuille courant', context); _myWalletProvider.readAllWallets(_currentChest); - scheduleMicrotask(() { - _walletOptions.reloadBuild(); - _myWalletProvider.rebuildWidget(); - }); + // scheduleMicrotask(() { + // _walletOptions.reloadBuild(); + _myWalletProvider.rebuildWidget(); + // }); + _generateWalletProvider.generatedMnemonic = ''; Navigator.push( context, FaderTransition( diff --git a/lib/screens/onBoarding/13_congratulations.dart b/lib/screens/onBoarding/13_congratulations.dart index ae2ec6f..f7189c7 100644 --- a/lib/screens/onBoarding/13_congratulations.dart +++ b/lib/screens/onBoarding/13_congratulations.dart @@ -4,13 +4,14 @@ import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; import 'package:gecko/screens/common_elements.dart'; +import 'package:gecko/screens/myWallets/wallets_home.dart'; // ignore: must_be_immutable class OnboardingStepFiveteen extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 12; - OnboardingStepFiveteen({Key key}) : super(key: key); + OnboardingStepFiveteen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -33,28 +34,32 @@ class OnboardingStepFiveteen extends StatelessWidget { height: isTall ? 400 : 300, ), Expanded( - child: Align( - alignment: Alignment.bottomCenter, - child: SizedBox( - width: 400, - height: 62, - child: ElevatedButton( - key: const Key('goWalletHome'), - style: ElevatedButton.styleFrom( - elevation: 5, - primary: orangeC, - onPrimary: Colors.white, // foreground - ), - onPressed: () { - Navigator.pushNamedAndRemoveUntil( - context, - '/mywallets', - ModalRoute.withName('/'), - ); - }, - child: const Text("Accéder à mes portefeuilles", - style: TextStyle(fontSize: 20))), - ))), + child: Align( + alignment: Alignment.bottomCenter, + child: SizedBox( + width: 400, + height: 62, + child: ElevatedButton( + key: const Key('goWalletHome'), + style: ElevatedButton.styleFrom( + elevation: 5, + primary: orangeC, + onPrimary: Colors.white, // foreground + ), + onPressed: () { + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (context) { + return const WalletsHome(); + }), + ModalRoute.withName('/'), + ); + }, + child: const Text("Accéder à mes portefeuilles", + style: TextStyle(fontSize: 20))), + ), + ), + ), const SizedBox(height: 80), ]), )); diff --git a/lib/screens/onBoarding/2.dart b/lib/screens/onBoarding/2.dart index 19e2cbf..04c3495 100644 --- a/lib/screens/onBoarding/2.dart +++ b/lib/screens/onBoarding/2.dart @@ -14,7 +14,7 @@ class OnboardingStepTwo extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 2; - OnboardingStepTwo({Key key}) : super(key: key); + OnboardingStepTwo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/screens/onBoarding/3.dart b/lib/screens/onBoarding/3.dart index 815741b..41b9ec3 100644 --- a/lib/screens/onBoarding/3.dart +++ b/lib/screens/onBoarding/3.dart @@ -11,7 +11,7 @@ class OnboardingStepFor extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 3; - OnboardingStepFor({Key key}) : super(key: key); + OnboardingStepFor({Key? key}) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/screens/onBoarding/4.dart b/lib/screens/onBoarding/4.dart index bd0317b..a064231 100644 --- a/lib/screens/onBoarding/4.dart +++ b/lib/screens/onBoarding/4.dart @@ -11,7 +11,7 @@ class OnboardingStepFive extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 4; - OnboardingStepFive({Key key}) : super(key: key); + OnboardingStepFive({Key? key}) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/screens/onBoarding/5.dart b/lib/screens/onBoarding/5.dart index dbe5ee7..af8c3ad 100644 --- a/lib/screens/onBoarding/5.dart +++ b/lib/screens/onBoarding/5.dart @@ -11,7 +11,7 @@ class OnboardingStepSeven extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 5; - OnboardingStepSeven({Key key}) : super(key: key); + OnboardingStepSeven({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -43,8 +43,8 @@ class OnboardingStepSeven extends StatelessWidget { Container( padding: const EdgeInsets.only(bottom: 90), child: common.bubbleSpeak( - "Moi, j’ai déjà essayé de\nmémoriser une phrase de\nrestauration, mais je n’ai\npas une mémoire\nd’éléphant.", - ), + "Moi, j’ai déjà essayé de\nmémoriser une phrase de\nrestauration, mais je n’ai\npas une mémoire\nd’éléphant.", + isMaxWidth: false), ), Image.asset( 'assets/onBoarding/chopp-gecko.png', diff --git a/lib/screens/onBoarding/6.dart b/lib/screens/onBoarding/6.dart index 741947d..dc2b119 100644 --- a/lib/screens/onBoarding/6.dart +++ b/lib/screens/onBoarding/6.dart @@ -12,7 +12,7 @@ class OnboardingStepEight extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 6; - OnboardingStepEight({Key key}) : super(key: key); + OnboardingStepEight({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -29,7 +29,7 @@ class OnboardingStepEight extends StatelessWidget { "J’ai généré votre phrase de restauration !\nTâchez de la garder bien secrète, car elle permet à quiconque la connaît d’accéder à tous vos portefeuilles.", textKey: const Key('step6'), ), - SizedBox(height: isTall ? 61 : 31), + SizedBox(height: isTall ? 70 : 40), // SizedBox(height: 30), sentanceArray(context), // ), @@ -63,9 +63,10 @@ class OnboardingStepEight extends StatelessWidget { } Widget sentanceArray(BuildContext context) { - return Container( + return Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Container( + constraints: const BoxConstraints(maxWidth: 450), decoration: BoxDecoration( border: Border.all(color: Colors.black), color: Colors.grey[300], @@ -116,7 +117,7 @@ Widget arrayCell(dataWord) { ImageFiltered( imageFilter: ImageFilter.blur(sigmaX: 4, sigmaY: 4), child: Text(dataWord.split(':')[1], - style: const TextStyle(fontSize: 20, color: Colors.black)), + style: const TextStyle(fontSize: 19, color: Colors.black)), ) ], )); diff --git a/lib/screens/onBoarding/7.dart b/lib/screens/onBoarding/7.dart index 6604b5b..7d7d39f 100644 --- a/lib/screens/onBoarding/7.dart +++ b/lib/screens/onBoarding/7.dart @@ -3,7 +3,7 @@ import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/generate_wallets.dart'; +import 'package:gecko/providers/generate_wallets.dart'; import 'package:gecko/screens/common_elements.dart'; import 'package:gecko/screens/onBoarding/8.dart'; import 'package:printing/printing.dart'; @@ -14,7 +14,7 @@ class OnboardingStepNine extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 6; - OnboardingStepNine({Key key}) : super(key: key); + OnboardingStepNine({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -96,9 +96,7 @@ class OnboardingStepNine extends StatelessWidget { FaderTransition( page: OnboardingStepTen( generatedMnemonic: - _generateWalletProvider.generatedMnemonic, - generatedWallet: - _generateWalletProvider.actualWallet), + _generateWalletProvider.generatedMnemonic), isFast: true), ); }, @@ -115,64 +113,48 @@ Widget sentanceArray(BuildContext context) { GenerateWalletsProvider _generateWalletProvider = Provider.of(context); - return FutureBuilder( - future: _generateWalletProvider.generateWordList(), - initialData: const [ - '1:...', - '2:...', - '3:...', - '4:...', - '5:...', - '6:...', - '7:...', - '8:...', - '9:...', - '10:...', - '11:...', - '12:...', - ], - builder: (context, formatedArray) { - // print(formatedArray.data); - return Container( - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Container( - decoration: BoxDecoration( - border: Border.all(color: Colors.black), - color: Colors.grey[300], - borderRadius: const BorderRadius.all( - Radius.circular(10), - )), - // color: Colors.grey[300], - padding: const EdgeInsets.all(20), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.max, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Row(children: [ - arrayCell(formatedArray.data[0]), - arrayCell(formatedArray.data[1]), - arrayCell(formatedArray.data[2]), - arrayCell(formatedArray.data[3]), - ]), - const SizedBox(height: 15), - Row(children: [ - arrayCell(formatedArray.data[4]), - arrayCell(formatedArray.data[5]), - arrayCell(formatedArray.data[6]), - arrayCell(formatedArray.data[7]), - ]), - const SizedBox(height: 15), - Row(children: [ - arrayCell(formatedArray.data[8]), - arrayCell(formatedArray.data[9]), - arrayCell(formatedArray.data[10]), - arrayCell(formatedArray.data[11]), - ]), - ]), - ), - ); - }); + List formatedArray = _generateWalletProvider.generateWordList(); + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Container( + constraints: const BoxConstraints(maxWidth: 450), + decoration: BoxDecoration( + border: Border.all(color: Colors.black), + color: Colors.grey[300], + borderRadius: const BorderRadius.all( + Radius.circular(10), + )), + // color: Colors.grey[300], + padding: const EdgeInsets.all(20), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.max, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Row(children: [ + arrayCell(formatedArray[0]), + arrayCell(formatedArray[1]), + arrayCell(formatedArray[2]), + arrayCell(formatedArray[3]), + ]), + const SizedBox(height: 15), + Row(children: [ + arrayCell(formatedArray[4]), + arrayCell(formatedArray[5]), + arrayCell(formatedArray[6]), + arrayCell(formatedArray[7]), + ]), + const SizedBox(height: 15), + Row(children: [ + arrayCell(formatedArray[8]), + arrayCell(formatedArray[9]), + arrayCell(formatedArray[10]), + arrayCell(formatedArray[11]), + ]), + ]), + ), + ); } Widget arrayCell(dataWord) { @@ -195,9 +177,9 @@ Widget arrayCell(dataWord) { // ignore: must_be_immutable class PrintWallet extends StatelessWidget { - const PrintWallet(this.sentence, {Key key}) : super(key: key); + const PrintWallet(this.sentence, {Key? key}) : super(key: key); - final String sentence; + final String? sentence; @override Widget build(BuildContext context) { @@ -206,6 +188,11 @@ class PrintWallet extends StatelessWidget { return MaterialApp( home: Scaffold( appBar: AppBar( + leading: IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () { + Navigator.pop(context); + }), toolbarHeight: 60 * ratio, title: const Text('Imprimer ce trousseau')), body: PdfPreview( diff --git a/lib/screens/onBoarding/8.dart b/lib/screens/onBoarding/8.dart index 3426035..c9ec4ca 100644 --- a/lib/screens/onBoarding/8.dart +++ b/lib/screens/onBoarding/8.dart @@ -1,10 +1,8 @@ // ignore_for_file: file_names - -import 'package:dubp/dubp.dart'; import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:gecko/globals.dart'; -import 'package:gecko/models/generate_wallets.dart'; +import 'package:gecko/providers/generate_wallets.dart'; import 'package:gecko/screens/common_elements.dart'; import 'package:gecko/screens/onBoarding/9.dart'; import 'package:provider/provider.dart'; @@ -12,14 +10,11 @@ import 'package:provider/provider.dart'; // ignore: must_be_immutable class OnboardingStepTen extends StatelessWidget { OnboardingStepTen({ - Key validationKey, - @required this.generatedMnemonic, - @required this.generatedWallet, + Key? validationKey, + required this.generatedMnemonic, }) : super(key: validationKey); - String generatedMnemonic; - NewWallet generatedWallet; - + String? generatedMnemonic; TextEditingController tplController = TextEditingController(); TextEditingController wordController = TextEditingController(); final TextEditingController _mnemonicController = TextEditingController(); @@ -32,7 +27,7 @@ class OnboardingStepTen extends StatelessWidget { GenerateWalletsProvider _generateWalletProvider = Provider.of(context); CommonElements common = CommonElements(); - _mnemonicController.text = generatedMnemonic; + _mnemonicController.text = generatedMnemonic!; return WillPopScope( onWillPop: () { @@ -75,7 +70,7 @@ class OnboardingStepTen extends StatelessWidget { decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), border: Border.all( - color: Colors.grey[600], + color: Colors.grey[600]!, width: 3, )), width: 430, diff --git a/lib/screens/onBoarding/9.dart b/lib/screens/onBoarding/9.dart index 35b285e..bf0d938 100644 --- a/lib/screens/onBoarding/9.dart +++ b/lib/screens/onBoarding/9.dart @@ -11,7 +11,7 @@ class OnboardingStepEleven extends StatelessWidget { TextEditingController tplController = TextEditingController(); final int progress = 8; - OnboardingStepEleven({Key key}) : super(key: key); + OnboardingStepEleven({Key? key}) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/screens/search.dart b/lib/screens/search.dart index 39e4337..d98b98a 100644 --- a/lib/screens/search.dart +++ b/lib/screens/search.dart @@ -1,19 +1,20 @@ import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; import 'package:flutter/material.dart'; -import 'package:gecko/models/search.dart'; +import 'package:gecko/providers/search.dart'; import 'package:gecko/screens/search_result.dart'; import 'package:provider/provider.dart'; // import 'package:gecko/models/home.dart'; // import 'package:provider/provider.dart'; class SearchScreen extends StatelessWidget { - const SearchScreen({Key key}) : super(key: key); + const SearchScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); SearchProvider _searchProvider = Provider.of(context); + final double screenHeight = MediaQuery.of(context).size.height; return WillPopScope( onWillPop: () { @@ -59,11 +60,11 @@ class SearchScreen extends StatelessWidget { ), border: OutlineInputBorder( borderSide: - BorderSide(color: Colors.grey[500], width: 2), + BorderSide(color: Colors.grey[500]!, width: 2), borderRadius: BorderRadius.circular(8)), focusedBorder: OutlineInputBorder( borderSide: - BorderSide(color: Colors.grey[500], width: 2.5), + BorderSide(color: Colors.grey[500]!, width: 2.5), borderRadius: BorderRadius.circular(8), ), contentPadding: const EdgeInsets.all(20), @@ -101,7 +102,7 @@ class SearchScreen extends StatelessWidget { ), ), ), - const Spacer(flex: 1), + Spacer(flex: screenHeight <= 800 ? 1 : 2), ]), ), )); diff --git a/lib/screens/search_result.dart b/lib/screens/search_result.dart index bcaa6c0..347aace 100644 --- a/lib/screens/search_result.dart +++ b/lib/screens/search_result.dart @@ -1,15 +1,15 @@ import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; import 'package:flutter/material.dart'; -import 'package:gecko/models/cesium_plus.dart'; +import 'package:gecko/providers/cesium_plus.dart'; import 'package:gecko/models/g1_wallets_list.dart'; -import 'package:gecko/models/wallets_profiles.dart'; -import 'package:gecko/models/search.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; +import 'package:gecko/providers/search.dart'; import 'package:gecko/screens/wallet_view.dart'; import 'package:provider/provider.dart'; class SearchResultScreen extends StatelessWidget { - const SearchResultScreen({Key key}) : super(key: key); + const SearchResultScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -64,11 +64,11 @@ class SearchResultScreen extends StatelessWidget { const SizedBox(height: 20), FutureBuilder( future: _searchProvider.searchBlockchain(), - builder: (context, snapshot) { + builder: (context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done) { return Expanded( child: ListView(children: [ - for (G1WalletsList g1Wallet in snapshot.data) + for (G1WalletsList g1Wallet in snapshot.data ?? []) Padding( padding: const EdgeInsets.symmetric(horizontal: 5), child: ListTile( @@ -81,13 +81,13 @@ class SearchResultScreen extends StatelessWidget { null ? ClipOval( child: g1WalletsBox - .get(g1Wallet.pubkey) + .get(g1Wallet.pubkey)! .avatar) : FutureBuilder( future: _cesiumPlusProvider.getAvatar( g1Wallet.pubkey, _avatarSize), builder: (BuildContext context, - AsyncSnapshot _avatar) { + AsyncSnapshot _avatar) { if (_avatar.connectionState != ConnectionState.done || _avatar.hasError) { @@ -108,12 +108,12 @@ class SearchResultScreen extends StatelessWidget { } if (_avatar.hasData) { g1WalletsBox - .get(g1Wallet.pubkey) + .get(g1Wallet.pubkey)! .avatar = _avatar.data; return ClipOval(child: _avatar.data); } else { g1WalletsBox - .get(g1Wallet.pubkey) + .get(g1Wallet.pubkey)! .avatar = _cesiumPlusProvider .defaultAvatar(_avatarSize); @@ -124,7 +124,7 @@ class SearchResultScreen extends StatelessWidget { title: Row(children: [ Text( _walletsProfilesClass - .getShortPubkey(g1Wallet.pubkey), + .getShortPubkey(g1Wallet.pubkey!), style: const TextStyle( fontSize: 18, fontFamily: 'Monospace', @@ -132,7 +132,7 @@ class SearchResultScreen extends StatelessWidget { textAlign: TextAlign.center), ]), subtitle: Row(children: [ - Text(g1Wallet?.id?.username ?? '', + Text(g1Wallet.id?.username ?? '', style: const TextStyle( fontSize: 18, fontWeight: FontWeight.w500), diff --git a/lib/screens/settings.dart b/lib/screens/settings.dart index 8211062..f9cdce1 100644 --- a/lib/screens/settings.dart +++ b/lib/screens/settings.dart @@ -1,28 +1,29 @@ import 'package:flutter/material.dart'; -import 'package:dubp/dubp.dart'; +import 'package:durt/durt.dart'; import 'package:flutter/services.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/screens/myWallets/generate_wallets.dart'; import 'dart:io'; import 'package:gecko/screens/myWallets/import_cesium_wallet.dart'; import 'package:gecko/globals.dart'; +import 'package:gecko/screens/myWallets/restore_chest.dart'; // ignore: must_be_immutable class SettingsScreen extends StatelessWidget { - String generatedMnemonic; + String? generatedMnemonic; bool walletIsGenerated = false; - NewWallet actualWallet; - String newWalletName; + NewWallet? actualWallet; + String? newWalletName; bool hasError = false; String validPin = 'NO PIN'; String currentText = ""; var pinColor = Colors.grey[300]; - Directory appPath; + Directory? appPath; final MyWalletsProvider _myWallets = MyWalletsProvider(); - SettingsScreen({Key key}) : super(key: key); + SettingsScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -39,43 +40,74 @@ class SettingsScreen extends StatelessWidget { body: Column(children: [ const SizedBox(height: 40), SizedBox( - height: 70, - width: 500, - child: ElevatedButton( - style: ElevatedButton.styleFrom( - elevation: 5, - primary: yellowC, // background - onPrimary: Colors.black, // foreground - ), - onPressed: () => Navigator.push( - context, - MaterialPageRoute(builder: (context) { - return const ImportWalletScreen(); - }), - ).then((value) => { - if (value == true) {Navigator.pop(context)} - }), - child: const Text("Importer un portefeuille Cesium", - style: TextStyle(fontSize: 16)))), + height: 70, + width: 500, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + elevation: 5, + primary: yellowC, // background + onPrimary: Colors.black, // foreground + ), + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (context) { + return const ImportWalletScreen(); + }), + ).then((value) => { + if (value == true) {Navigator.pop(context)} + }), + child: const Text( + "Importer un portefeuille Cesium", + style: TextStyle(fontSize: 16), + ), + ), + ), const SizedBox(height: 30), SizedBox( - height: 70, - width: 500, - child: ElevatedButton( - key: const Key('generateKeychain'), - style: ElevatedButton.styleFrom( - elevation: 5, - primary: yellowC, // background - onPrimary: Colors.black, // foreground - ), - onPressed: () => Navigator.push( - context, - MaterialPageRoute(builder: (context) { - return GenerateFastChestScreen(); - }), - ), - child: const Text("Générer un nouveau trousseau", - style: TextStyle(fontSize: 16)))), + height: 70, + width: 500, + child: ElevatedButton( + key: const Key('generateKeychain'), + style: ElevatedButton.styleFrom( + elevation: 5, + primary: yellowC, // background + onPrimary: Colors.black, // foreground + ), + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (context) { + return GenerateFastChestScreen(); + }), + ), + child: const Text( + "Générer un nouveau trousseau", + style: TextStyle(fontSize: 16), + ), + ), + ), + const SizedBox(height: 30), + SizedBox( + height: 70, + width: 500, + child: ElevatedButton( + key: const Key('generateKeychain'), + style: ElevatedButton.styleFrom( + elevation: 5, + primary: yellowC, // background + onPrimary: Colors.black, // foreground + ), + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (context) { + return const RestoreChest(); + }), + ), + child: const Text( + "Restaurer un coffre", + style: TextStyle(fontSize: 16), + ), + ), + ), Expanded( child: Align( alignment: Alignment.bottomCenter, diff --git a/lib/screens/template_screen.dart b/lib/screens/template_screen.dart index e8858c7..faa92ec 100644 --- a/lib/screens/template_screen.dart +++ b/lib/screens/template_screen.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; class TemplateScreen extends StatelessWidget { TextEditingController tplController = TextEditingController(); - TemplateScreen({Key key}) : super(key: key); + TemplateScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/screens/wallet_view.dart b/lib/screens/wallet_view.dart index e474236..7444fbf 100644 --- a/lib/screens/wallet_view.dart +++ b/lib/screens/wallet_view.dart @@ -1,10 +1,10 @@ import 'package:flutter/services.dart'; import 'package:gecko/globals.dart'; import 'package:flutter/material.dart'; -import 'package:gecko/models/cesium_plus.dart'; -import 'package:gecko/models/my_wallets.dart'; +import 'package:gecko/providers/cesium_plus.dart'; +import 'package:gecko/providers/my_wallets.dart'; import 'package:gecko/models/wallet_data.dart'; -import 'package:gecko/models/wallets_profiles.dart'; +import 'package:gecko/providers/wallets_profiles.dart'; import 'package:gecko/models/queries.dart'; import 'package:gecko/screens/avatar_fullscreen.dart'; import 'package:gecko/screens/common_elements.dart'; @@ -15,11 +15,11 @@ import 'package:provider/provider.dart'; class WalletViewScreen extends StatelessWidget { const WalletViewScreen( - {@required this.pubkey, this.username, this.avatar, Key key}) + {required this.pubkey, this.username, this.avatar, Key? key}) : super(key: key); - final String pubkey; - final String username; - final Image avatar; + final String? pubkey; + final String? username; + final Image? avatar; final double buttonSize = 100; final double buttonFontSize = 18; @@ -31,6 +31,8 @@ class WalletViewScreen extends StatelessWidget { CesiumPlusProvider _cesiumPlusProvider = Provider.of(context, listen: false); + _historyProvider.pubkey = pubkey!; + return Scaffold( resizeToAvoidBottomInset: true, appBar: AppBar( @@ -185,8 +187,9 @@ class WalletViewScreen extends StatelessWidget { // WalletsProfilesProvider _walletViewProvider = // Provider.of(context); const double shapeSize = 20; - MyWalletsProvider _myWalletProvider = MyWalletsProvider(); - WalletData defaultWallet = + MyWalletsProvider _myWalletProvider = + Provider.of(context, listen: false); + WalletData? defaultWallet = _myWalletProvider.getDefaultWallet(configBox.get('currentChest')); showModalBottomSheet( @@ -199,111 +202,120 @@ class WalletViewScreen extends StatelessWidget { isScrollControlled: true, context: context, builder: (BuildContext context) { - return Padding( - padding: EdgeInsets.only( - bottom: MediaQuery.of(context).viewInsets.bottom), - child: Container( - height: 400, - decoration: const ShapeDecoration( - color: Color(0xffffeed1), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.only( - topRight: Radius.circular(shapeSize), - topLeft: Radius.circular(shapeSize), + return StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Padding( + padding: EdgeInsets.only( + bottom: MediaQuery.of(context).viewInsets.bottom), + child: Container( + height: 400, + decoration: const ShapeDecoration( + color: Color(0xffffeed1), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.only( + topRight: Radius.circular(shapeSize), + topLeft: Radius.circular(shapeSize), + ), ), ), + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Effectuer un virement', + style: TextStyle( + fontSize: 26, fontWeight: FontWeight.w700), + ), + const SizedBox(height: 20), + Text( + 'Saisissez dans le champ ci-dessous le montant à virer.', + style: TextStyle( + fontSize: 19, + fontWeight: FontWeight.w500, + color: Colors.grey[600]), + ), + const Spacer(), + Center( + child: Column(children: [ + TextField( + controller: _walletViewProvider.payAmount, + autofocus: true, + maxLines: 1, + textAlign: TextAlign.center, + keyboardType: TextInputType.number, + onChanged: (_) => setState(() {}), + inputFormatters: [ + FilteringTextInputFormatter.allow( + RegExp(r'^\d+\.?\d{0,2}')), + ], + // onChanged: (v) => _searchProvider.rebuildWidget(), + decoration: InputDecoration( + hintText: '0.00', + suffix: const Text('Ğ1'), + filled: true, + fillColor: Colors.transparent, + // border: OutlineInputBorder( + // borderSide: + // BorderSide(color: Colors.grey[500], width: 2), + // borderRadius: BorderRadius.circular(8)), + focusedBorder: OutlineInputBorder( + borderSide: BorderSide( + color: Colors.grey[500]!, width: 2), + borderRadius: BorderRadius.circular(8), + ), + contentPadding: const EdgeInsets.all(20), + ), + style: const TextStyle( + fontSize: 40, + color: Colors.black, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 40), + // const Spacer(), + SizedBox( + width: double.infinity, + height: 60, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + elevation: 4, + primary: orangeC, // background + onPrimary: Colors.white, // foreground + ), + onPressed: + _walletViewProvider.payAmount.text != '' + ? () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) { + return UnlockingWallet( + wallet: defaultWallet, + action: "pay"); + }, + ), + ); + } + : null, + child: const Text( + 'Effectuer le virement', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w600), + ), + ), + ), + const SizedBox(height: 20), + ]), + ), + ]), + ), ), - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Text( - 'Effectuer un virement', - style: TextStyle( - fontSize: 26, fontWeight: FontWeight.w700), - ), - const SizedBox(height: 20), - Text( - 'Saisissez dans le champ ci-dessous le montant à virer de ... vers ...', - style: TextStyle( - fontSize: 19, - fontWeight: FontWeight.w500, - color: Colors.grey[600]), - ), - const Spacer(), - Center( - child: Column(children: [ - TextField( - controller: _walletViewProvider.payAmount, - autofocus: true, - maxLines: 1, - textAlign: TextAlign.center, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.allow( - RegExp(r'^\d+\.?\d{0,2}')), - ], - // onChanged: (v) => _searchProvider.rebuildWidget(), - decoration: InputDecoration( - hintText: '0.00', - suffix: const Text('DU/Ğ1'), - filled: true, - fillColor: Colors.transparent, - // border: OutlineInputBorder( - // borderSide: - // BorderSide(color: Colors.grey[500], width: 2), - // borderRadius: BorderRadius.circular(8)), - focusedBorder: OutlineInputBorder( - borderSide: BorderSide( - color: Colors.grey[500], width: 2), - borderRadius: BorderRadius.circular(8), - ), - contentPadding: const EdgeInsets.all(20), - ), - style: const TextStyle( - fontSize: 40, - color: Colors.black, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 40), - // const Spacer(), - SizedBox( - width: double.infinity, - height: 60, - child: ElevatedButton( - style: ElevatedButton.styleFrom( - elevation: 4, - primary: orangeC, // background - onPrimary: Colors.white, // foreground - ), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) { - return UnlockingWallet( - wallet: defaultWallet, action: "pay"); - }, - ), - ); - }, - child: const Text( - 'Effectuer le virement', - style: TextStyle( - fontSize: 20, fontWeight: FontWeight.w600), - ), - ), - ), - const SizedBox(height: 20), - ]), - ), - ]), - ), - ), - ); + ); + }); }).then((value) => _walletViewProvider.payAmount.text = ''); } @@ -342,7 +354,7 @@ class WalletViewScreen extends StatelessWidget { _historyProvider.snackCopyKey(context); }, child: Text( - _historyProvider.getShortPubkey(pubkey), + _historyProvider.getShortPubkey(pubkey!), style: const TextStyle( fontSize: 30, fontWeight: FontWeight.w800, @@ -361,20 +373,20 @@ class WalletViewScreen extends StatelessWidget { }, ), builder: (QueryResult result, - {VoidCallback refetch, FetchMore fetchMore}) { + {VoidCallback? refetch, FetchMore? fetchMore}) { if (result.isLoading || result.hasException) { return const Text('...'); - } else if (result.data['idty'] == null || - result.data['idty']['username'] == null) { + } else if (result.data!['idty'] == null || + result.data!['idty']['username'] == null) { g1WalletsBox.get(pubkey)?.username = ''; return const Text(''); } else { g1WalletsBox.get(pubkey)?.username = - result?.data['idty']['username'] ?? ''; + result.data!['idty']['username'] ?? ''; return SizedBox( width: 230, child: Text( - result?.data['idty']['username'] ?? '', + result.data!['idty']['username'] ?? '', style: const TextStyle( fontSize: 27, color: Color(0xff814C00), @@ -389,7 +401,7 @@ class WalletViewScreen extends StatelessWidget { SizedBox( width: 230, child: Text( - g1WalletsBox.get(pubkey)?.username, + g1WalletsBox.get(pubkey)?.username ?? '', style: const TextStyle( fontSize: 27, color: Color(0xff814C00), @@ -400,7 +412,7 @@ class WalletViewScreen extends StatelessWidget { SizedBox( width: 230, child: Text( - username, + username!, style: const TextStyle( fontSize: 27, color: Color(0xff814C00), @@ -415,7 +427,7 @@ class WalletViewScreen extends StatelessWidget { return SizedBox( width: 230, child: Text( - snapshot.data ?? '-', + snapshot.data.toString(), style: const TextStyle( fontSize: 18, color: Colors.black), ), @@ -429,7 +441,7 @@ class WalletViewScreen extends StatelessWidget { FutureBuilder( future: _cesiumPlusProvider.getAvatar(pubkey, _avatarSize), builder: - (BuildContext context, AsyncSnapshot _avatar) { + (BuildContext context, AsyncSnapshot _avatar) { if (_avatar.connectionState != ConnectionState.done) { return Stack(children: [ ClipOval( @@ -461,7 +473,7 @@ class WalletViewScreen extends StatelessWidget { }, child: ClipOval( child: Image( - image: _avatar.data.image, + image: _avatar.data!.image, height: _avatarSize, fit: BoxFit.cover, ), @@ -485,7 +497,7 @@ class WalletViewScreen extends StatelessWidget { }, child: ClipOval( child: Image( - image: avatar.image, + image: avatar!.image, height: _avatarSize, fit: BoxFit.cover, ), diff --git a/native/dubp_rs/Cargo.toml b/native/dubp_rs/Cargo.toml deleted file mode 100644 index 4359111..0000000 --- a/native/dubp_rs/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "dubp_rs" -version = "0.1.0" -authors = ["Éloïs SANCHEZ "] -license = "AGPL-3.0" -edition = "2018" - -[lib] -name = "dubp_rs" -crate-type = ["rlib"] - -[dependencies] -allo-isolate = "0.1.6" -dubp-client = { git = "https://git.duniter.org/libs/dubp-rs-client-lib", branch = "master", features = ["blocking"], default-features = false } -#dubp-client= { path = "../dubp-rs-client-lib", features = ["blocking"], default-features = false } -fast-threadpool = { version = "0.3.0", default-features = false } -once_cell = { version = "1.3.1", default-features = false, features = ["std"] } -parking_lot = "0.11.1" -thiserror = "1.0.24" - -[build-dependencies] -cbindgen = "0.14.3" -dart-bindgen = "0.1.7" - -[dev-dependencies] -assert_matches = "1.5.0" -rusty-hook = "^0.11.2" \ No newline at end of file diff --git a/native/dubp_rs/build.rs b/native/dubp_rs/build.rs deleted file mode 100644 index 39fd1b6..0000000 --- a/native/dubp_rs/build.rs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use dart_bindgen::{config::*, Codegen}; - -fn main() { - let crate_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - let config = cbindgen::Config { - language: cbindgen::Language::C, - braces: cbindgen::Braces::SameLine, - cpp_compat: true, - style: cbindgen::Style::Both, - ..Default::default() - }; - cbindgen::Builder::new() - .with_crate(crate_dir) - .with_config(config) - .generate() - .expect("Unable to generate bindings") - .write_to_file("binding.h"); - let config = DynamicLibraryConfig { - ios: DynamicLibraryCreationMode::Executable.into(), - android: DynamicLibraryCreationMode::open("libdubp_rs.so").into(), - linux: DynamicLibraryCreationMode::open("libdubp_rs.so").into(), - ..Default::default() - }; - // load the c header file, with config and lib name - let codegen = Codegen::builder() - .with_src_header("binding.h") - .with_lib_name("libdubp") - .with_config(config) - .with_allo_isolate() - .build() - .unwrap(); - // generate the dart code and get the bindings back - let bindings = codegen.generate().unwrap(); - // write the bindings to your dart package - // and start using it to write your own high level abstraction. - bindings - .write_to_file("../../packages/dubp_rs/lib/ffi.dart") - .unwrap(); -} diff --git a/native/dubp_rs/src/async.rs b/native/dubp_rs/src/async.rs deleted file mode 100644 index b7ce764..0000000 --- a/native/dubp_rs/src/async.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; - -static THREAD_POOL: Lazy> = Lazy::new(|| { - ThreadPool::start(ThreadPoolConfig::low().queue_size(Some(16)), ()).into_sync_handler() -}); - -pub(crate) fn exec_async(port: i64, parse_params: F, async_job: F2) -where - P: 'static + Send + Sync, - F: FnOnce() -> Result, - F2: 'static + Send + Sync + FnOnce(P) -> R, - DartRes: From, -{ - match parse_params() { - Ok(parsed_params) => { - if THREAD_POOL - .launch(move |_| Isolate::new(port).post(DartRes::from(async_job(parsed_params)))) - .is_err() - { - Isolate::new(port).post(DartRes::err("thread pool panicked")); - } - } - Err(e) => { - Isolate::new(port).post(DartRes::err(e)); - } - } -} diff --git a/native/dubp_rs/src/dewif.rs b/native/dubp_rs/src/dewif.rs deleted file mode 100644 index 84f3eee..0000000 --- a/native/dubp_rs/src/dewif.rs +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -pub mod bip32; -pub mod classic; - -use crate::*; - -pub(super) fn change_secret_code( - dewif: &str, - old_secret_code: &str, - member_wallet: bool, - secret_code_type: SecretCodeType, - system_memory: i64, -) -> Result, DubpError> { - let new_log_n = log_n(system_memory); - let new_secret_code = gen_secret_code(member_wallet, secret_code_type, new_log_n)?; - - let new_dewif = dubp_client::crypto::dewif::change_dewif_passphrase( - dewif, - old_secret_code, - &new_secret_code, - ) - .map_err(DubpError::DewifReadError)?; - - Ok(vec![new_dewif, new_secret_code]) -} - -pub(super) fn gen_dewif( - currency: &str, - language: Language, - mnemonic: &str, - member_wallet: bool, - secret_code_type: SecretCodeType, - system_memory: i64, -) -> Result, DubpError> { - let currency = parse_currency(currency)?; - let mnemonic = - Mnemonic::from_phrase(mnemonic, language).map_err(|_| DubpError::WrongLanguage)?; - - let log_n = log_n(system_memory); - let secret_code = gen_secret_code(member_wallet, secret_code_type, log_n)?; - - let dewif = - dubp_client::crypto::dewif::create_dewif_v1(currency, log_n, &mnemonic, &secret_code) - .map_err(|_| DubpError::RandErr)?; - - Ok(vec![dewif, secret_code]) -} - -pub(super) fn get_dewif_meta( - dewif: &str, - member_wallet: bool, - secret_code_type: SecretCodeType, -) -> Result, DubpError> { - let dubp_client::crypto::dewif::DewifMeta { - algo, - currency, - log_n, - version, - } = dubp_client::crypto::dewif::read_dewif_meta(dewif).map_err(DubpError::DewifReadError)?; - - let secret_code_len = - crate::secret_code::compute_secret_code_len(member_wallet, secret_code_type, log_n)?; - - Ok(vec![ - if algo == KeysAlgo::Bip32Ed25519 { - "Bip32Ed25519".to_owned() - } else { - "Ed25519".to_owned() - }, - currency.to_string(), - secret_code_len.to_string(), - version.to_string(), - ]) -} - -pub(super) fn get_pubkey( - account_index_opt: Option, - address_index_opt: Option, - currency: Currency, - dewif: &str, - external_opt: Option, - secret_code: &str, -) -> Result { - if let Some(account_index) = account_index_opt { - dewif::bip32::get_bip32_pubkey( - account_index, - address_index_opt, - currency, - dewif, - external_opt, - secret_code, - ) - } else if address_index_opt.is_none() && external_opt.is_none() { - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - - match payload { - DewifPayload::Ed25519(keypair) => Ok(keypair.public_key().to_base58()), - DewifPayload::Bip32Ed25519(_) => Err(DubpError::GetMasterPubkeyOfHdWallet), - } - } else { - Err(DubpError::GiveExternalBoolOrAddressIndexForLegacyWallet) - } -} - -pub(super) fn get_secret_code_len( - dewif: *const raw::c_char, - member_wallet: u32, - secret_code_type: u32, -) -> Result { - let dewif = char_ptr_to_str(dewif)?; - let member_wallet = member_wallet != 0; - let secret_code_type = SecretCodeType::from(secret_code_type); - - let log_n = dubp_client::crypto::dewif::read_dewif_log_n(ExpectedCurrency::Any, dewif) - .map_err(DubpError::DewifReadError)?; - - crate::secret_code::compute_secret_code_len(member_wallet, secret_code_type, log_n) -} - -pub(crate) fn log_n(system_memory: i64) -> u8 { - if system_memory > 3_000_000_000 { - 15 - } else { - 12 - } -} - -pub(super) fn sign( - account_index_opt: Option, - address_index_opt: Option, - currency: Currency, - dewif: &str, - external_opt: Option, - secret_code: &str, - msg: &str, -) -> Result { - if let Some(account_index) = account_index_opt { - dewif::bip32::sign_bip32( - account_index, - address_index_opt, - currency, - dewif, - external_opt, - secret_code, - msg, - ) - } else { - dewif::classic::sign(currency, dewif, secret_code, msg) - } -} - -pub(super) fn sign_several( - account_index_opt: Option, - address_index_opt: Option, - currency: Currency, - dewif: &str, - external_opt: Option, - secret_code: &str, - msgs: &[&str], -) -> Result, DubpError> { - if let Some(account_index) = account_index_opt { - dewif::bip32::sign_several_bip32( - account_index, - address_index_opt, - currency, - dewif, - external_opt, - secret_code, - msgs, - ) - } else { - dewif::classic::sign_several(currency, dewif, secret_code, msgs) - } -} diff --git a/native/dubp_rs/src/dewif/bip32.rs b/native/dubp_rs/src/dewif/bip32.rs deleted file mode 100644 index a90ede2..0000000 --- a/native/dubp_rs/src/dewif/bip32.rs +++ /dev/null @@ -1,436 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; - -#[derive(Debug)] -struct OpaqueAccount { - address_index: u32, - chain_code: ChainCode, - public_key: PublicKey, -} - -static CHAINING_EXTERNAL_PUBKEYS: Lazy>>> = - Lazy::new(|| Arc::new(Mutex::new(HashMap::new()))); - -pub(crate) fn get_accounts_pubkeys( - currency: Currency, - dewif: &str, - secret_code: &str, - accounts_indexs: Vec, -) -> Result, DubpError> { - if accounts_indexs.contains(&U31::new(0)?) { - verify_member_secret_code(currency, dewif, secret_code)?; - } - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - match payload { - DewifPayload::Bip32Ed25519(mnemonic) => { - let master_keypair = KeyPair::from_mnemonic(&mnemonic); - Ok(accounts_indexs - .into_iter() - .map(|account_index| { - PrivateDerivationPath::transparent(account_index) - .map(|path| master_keypair.derive(path).public_key().to_base58()) - }) - .collect::, InvalidAccountIndex>>()?) - } - _ => Err(DubpError::NotHdWallet), - } -} - -pub(crate) fn get_bip32_keypair( - account_index: u32, - address_index_opt: Option, - currency: Currency, - dewif: &str, - external_opt: Option, - secret_code: &str, -) -> Result { - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - - if account_index == 0 { - verify_member_secret_code(currency, dewif, secret_code)?; - } - - match payload { - DewifPayload::Bip32Ed25519(mnemonic) => { - let master_keypair = KeyPair::from_mnemonic(&mnemonic); - Ok(KeyPairEnum::Bip32Ed25519(master_keypair.derive( - z_get_derivation_path(account_index, address_index_opt, external_opt)?, - ))) - } - _ => Err(DubpError::NotHdWallet), - } -} - -pub(crate) fn get_bip32_pubkey( - account_index: u32, - address_index_opt: Option, - currency: Currency, - dewif: &str, - external_opt: Option, - secret_code: &str, -) -> Result { - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - - if account_index == 0 { - verify_member_secret_code(currency, dewif, secret_code)?; - } - - match payload { - DewifPayload::Bip32Ed25519(mnemonic) => { - let master_keypair = KeyPair::from_mnemonic(&mnemonic); - Ok(master_keypair - .derive(z_get_derivation_path( - account_index, - address_index_opt, - external_opt, - )?) - .public_key() - .to_base58()) - } - _ => Err(DubpError::NotHdWallet), - } -} - -pub(crate) fn get_opaque_account_next_external_address( - account_index: U31, -) -> Result { - let mut guard = CHAINING_EXTERNAL_PUBKEYS.lock(); - if let Some(opaque_account) = guard.get_mut(&account_index.into_u32()) { - let next_address = PublicKeyWithChainCode { - chain_code: opaque_account.chain_code, - public_key: opaque_account.public_key, - } - .derive(U31::new(opaque_account.address_index).expect("unreachable")) - .expect("unreachable") - .public_key; - - opaque_account.address_index += 1; - - Ok(next_address.to_base58()) - } else { - Err(DubpError::OpaqueAccountNotLoaded) - } -} - -pub(crate) fn get_mnemonic( - currency: Currency, - dewif: &str, - secret_code: &str, -) -> Result { - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - - match payload { - DewifPayload::Bip32Ed25519(mnemonic) => Ok(mnemonic.phrase().to_owned()), - _ => Err(DubpError::NotHdWallet), - } -} - -pub(crate) fn load_opaque_bip32_accounts( - accounts_indexs: Vec, - currency: Currency, - dewif: &str, - secret_code: &str, -) -> Result<(), DubpError> { - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - match payload { - DewifPayload::Bip32Ed25519(mnemonic) => { - let master_keypair = KeyPair::from_mnemonic(&mnemonic); - for account_index in accounts_indexs { - let external_path = PrivateDerivationPath::opaque(account_index, true, None)?; - let external_kp = master_keypair.derive(external_path); - let opaque_account = OpaqueAccount { - address_index: 0, - public_key: external_kp.public_key(), - chain_code: external_kp.chain_code(), - }; - - let mut guard = CHAINING_EXTERNAL_PUBKEYS.lock(); - guard.insert(account_index.into_u32(), opaque_account); - } - Ok(()) - } - _ => Err(DubpError::NotHdWallet), - } -} - -pub(crate) fn sign_bip32( - account_index: u32, - address_index_opt: Option, - currency: Currency, - dewif: &str, - external_opt: Option, - secret_code: &str, - msg: &str, -) -> Result { - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - - if account_index == 0 { - verify_member_secret_code(currency, dewif, secret_code)?; - } - - match payload { - DewifPayload::Bip32Ed25519(mnemonic) => { - let master_keypair = KeyPair::from_mnemonic(&mnemonic); - sign_bip32_inner( - account_index, - address_index_opt, - external_opt, - master_keypair, - msg, - ) - } - _ => Err(DubpError::NotHdWallet), - } -} - -pub(crate) fn sign_several_bip32( - account_index: u32, - address_index_opt: Option, - currency: Currency, - dewif: &str, - external_opt: Option, - secret_code: &str, - msgs: &[&str], -) -> Result, DubpError> { - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - - if account_index == 0 { - verify_member_secret_code(currency, dewif, secret_code)?; - } - - match payload { - DewifPayload::Bip32Ed25519(mnemonic) => { - let master_keypair = KeyPair::from_mnemonic(&mnemonic); - sign_several_bip32_inner( - account_index, - address_index_opt, - external_opt, - master_keypair, - msgs, - ) - } - _ => Err(DubpError::NotHdWallet), - } -} - -fn sign_bip32_inner( - account_index: u32, - address_index_opt: Option, - external_opt: Option, - master_keypair: KeyPair, - msg: &str, -) -> Result { - Ok(master_keypair - .derive(z_get_derivation_path( - account_index, - address_index_opt, - external_opt, - )?) - .generate_signator() - .sign(msg.as_bytes()) - .to_base64()) -} - -fn sign_several_bip32_inner( - account_index: u32, - address_index_opt: Option, - external_opt: Option, - master_keypair: KeyPair, - msgs: &[&str], -) -> Result, DubpError> { - let signator = master_keypair - .derive(z_get_derivation_path( - account_index, - address_index_opt, - external_opt, - )?) - .generate_signator(); - - Ok(msgs - .iter() - .map(|msg| signator.sign(msg.as_bytes()).to_base64()) - .collect()) -} - -fn verify_member_secret_code( - currency: Currency, - dewif: &str, - secret_code: &str, -) -> Result<(), DubpError> { - if crate::secret_code::is_ascii_letters(secret_code) { - let log_n = dubp_client::crypto::dewif::read_dewif_log_n( - ExpectedCurrency::Specific(currency), - dewif, - ) - .map_err(DubpError::DewifReadError)?; - let expected_secret_code_len = - crate::secret_code::compute_secret_code_len(true, SecretCodeType::Letters, log_n)?; - - if secret_code.len() < expected_secret_code_len { - Err(DubpError::SecretCodeTooShort) - } else { - Ok(()) - } - } else { - Err(DubpError::InvalidSecretCodeType) - } -} - -fn z_get_derivation_path( - account_index: u32, - address_index_opt: Option, - external_opt: Option, -) -> Result { - let account_index_u31 = U31::new(account_index)?; - match account_index % 3 { - 0 => Ok(PrivateDerivationPath::transparent(account_index_u31)?), - 1 => { - if let Some(external) = external_opt { - if external { - if address_index_opt.is_none() { - Ok(PrivateDerivationPath::semi_opaque_external( - account_index_u31, - )?) - } else { - Err(DubpError::InvalidAccountIndex(InvalidAccountIndex)) - } - } else if address_index_opt.is_some() { - Ok(PrivateDerivationPath::semi_opaque_internal( - account_index_u31, - address_index_opt, - )?) - } else { - Err(DubpError::TryToSignWithInternalChainingAddress) - } - } else { - Err(DubpError::MissingExternalBool) - } - } - 2 => { - if address_index_opt.is_some() { - if let Some(external) = external_opt { - Ok(PrivateDerivationPath::opaque( - account_index_u31, - external, - address_index_opt, - )?) - } else { - Err(DubpError::MissingExternalBool) - } - } else { - Err(DubpError::TryToSignWithChainingAddress) - } - } - _ => unreachable!(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use assert_matches::assert_matches; - - const MNEMONIC: &str = - "tongue cute mail fossil great frozen same social weasel impact brush kind"; - - #[test] - fn test_get_accounts_pubkeys() -> Result<(), DubpError> { - let vec = crate::dewif::gen_dewif( - "g1", - Language::English, - MNEMONIC, - false, - SecretCodeType::Letters, - 1_000, - )?; - let dewif = &vec[0]; - let secret_code = &vec[1]; - //println!("TMP: secret_code={}", secret_code); - - assert_matches!( - get_accounts_pubkeys( - Currency::from(G1_CURRENCY), - dewif, - secret_code, - vec![U31::new(0).expect("unreachable")], - ), - Err(DubpError::SecretCodeTooShort) - ); - - Ok(()) - } - - #[test] - fn test_sign_bip32() { - assert_matches!( - z_get_derivation_path(1, None, None), - Err(DubpError::MissingExternalBool) - ); - assert_matches!( - z_get_derivation_path(2, None, None), - Err(DubpError::TryToSignWithChainingAddress) - ); - assert_matches!(z_get_derivation_path(3, None, None), Ok(_)); - assert_matches!( - z_get_derivation_path(1, None, Some(false)), - Err(DubpError::TryToSignWithInternalChainingAddress) - ); - assert_matches!( - z_get_derivation_path(2, None, Some(true)), - Err(DubpError::TryToSignWithChainingAddress) - ); - assert_matches!( - z_get_derivation_path(1, Some(U31::new(5).expect("unreachable")), Some(true),), - Err(DubpError::InvalidAccountIndex(_)) - ); - } -} diff --git a/native/dubp_rs/src/dewif/classic.rs b/native/dubp_rs/src/dewif/classic.rs deleted file mode 100644 index 19b6f59..0000000 --- a/native/dubp_rs/src/dewif/classic.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; - -pub(crate) fn sign( - currency: Currency, - dewif: &str, - secret_code: &str, - msg: &str, -) -> Result { - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - if let DewifPayload::Ed25519(keypair) = payload { - Ok(keypair.generate_signator().sign(msg.as_bytes()).to_base64()) - } else { - Err(DubpError::DewifReadError(DewifReadError::CorruptedContent)) - } -} - -pub(crate) fn sign_several( - currency: Currency, - dewif: &str, - secret_code: &str, - msgs: &[&str], -) -> Result, DubpError> { - let DewifContent { payload, .. } = dubp_client::crypto::dewif::read_dewif_content( - ExpectedCurrency::Specific(currency), - dewif, - &secret_code.to_ascii_uppercase(), - ) - .map_err(DubpError::DewifReadError)?; - if let DewifPayload::Ed25519(keypair) = payload { - let signator = keypair.generate_signator(); - Ok(msgs - .iter() - .map(|msg| signator.sign(msg.as_bytes()).to_base64()) - .collect()) - } else { - Err(DubpError::DewifReadError(DewifReadError::CorruptedContent)) - } -} diff --git a/native/dubp_rs/src/error.rs b/native/dubp_rs/src/error.rs deleted file mode 100644 index 479b0c2..0000000 --- a/native/dubp_rs/src/error.rs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; - -/// Dubp error -#[allow(clippy::large_enum_variant)] -#[derive(Debug, Error)] -pub(crate) enum DubpError { - #[error("{0}")] - DewifReadError(DewifReadError), - #[error("Digits secret code forbid for member wallet")] - DigitsCodeForbidForMemberWallet, - #[error("It is forbidden to retrieve the master public key of an HD wallet.")] - GetMasterPubkeyOfHdWallet, - #[error("Give external bool or address index for legacy wallet.")] - GiveExternalBoolOrAddressIndexForLegacyWallet, - #[error("{0}")] - GvaClientError(dubp_client::GvaClientError), - #[error("I/O error: {0}")] - IoErr(io::Error), - #[error("{0}")] - InvalidAccountIndex(InvalidAccountIndex), - #[error("{0}")] - InvalidPubkey(PublicKeyFromStrErr), - #[error("{0}")] - InvalidScript(dubp_client::documents_parser::TextParseError), - #[error("{0}")] - InvalidU31(U31Error), - #[error("Invalid secret code type")] - InvalidSecretCodeType, - #[error("Missing external bool")] - MissingExternalBool, - #[error("this wallet is not an HD wallet")] - NotHdWallet, - #[error("A given parameter is null")] - NullParamErr, - #[error("Opaque account not loaded")] - OpaqueAccountNotLoaded, - #[error("Payment error: {0}")] - PaymentError(String), - #[error("Secret code too short: please change your secret code")] - SecretCodeTooShort, - #[error("The chaining address cannot be used to sign with opaque account")] - TryToSignWithChainingAddress, - #[error("The internal chaining address cannot be used to sign with semi-opaque account")] - TryToSignWithInternalChainingAddress, - #[error("fail to generate random bytes")] - RandErr, - #[error("Unknown currency name")] - UnknownCurrencyName, - #[error("Unknown language")] - UnknownLanguage, - //#[error("Unsupported DEWIF version")] - //UnsupportedDewifVersion, - #[error("{0}")] - Utf8Error(std::str::Utf8Error), - #[error("Wrong language")] - WrongLanguage, -} - -impl From for DubpError { - fn from(e: io::Error) -> Self { - Self::IoErr(e) - } -} - -impl From for DubpError { - fn from(e: InvalidAccountIndex) -> Self { - Self::InvalidAccountIndex(e) - } -} - -impl From for DubpError { - fn from(e: U31Error) -> Self { - Self::InvalidU31(e) - } -} - -pub(crate) struct DartRes(allo_isolate::ffi::DartCObject); -impl DartRes { - pub(crate) fn err(e: E) -> allo_isolate::ffi::DartCObject { - vec![format!("DUBP_RS_ERROR: {}", e.to_string())].into_dart() - } -} -impl IntoDart for DartRes { - fn into_dart(self) -> allo_isolate::ffi::DartCObject { - self.0.into_dart() - } -} -impl From> for DartRes -where - E: ToString, -{ - fn from(res: Result<(), E>) -> Self { - match res { - Ok(()) => Self("".into_dart()), - Err(e) => Self(format!("DUBP_RS_ERROR: {}", e.to_string()).into_dart()), - } - } -} -impl From> for DartRes -where - E: ToString, -{ - fn from(res: Result) -> Self { - match res { - Ok(string) => Self(string.into_dart()), - Err(e) => Self(format!("DUBP_RS_ERROR: {}", e.to_string()).into_dart()), - } - } -} -impl From, E>> for DartRes -where - E: ToString, -{ - fn from(res: Result, E>) -> Self { - match res { - Ok(vec_string) => Self(vec_string.into_dart()), - Err(e) => Self(vec![format!("DUBP_RS_ERROR: {}", e.to_string())].into_dart()), - } - } -} diff --git a/native/dubp_rs/src/inputs.rs b/native/dubp_rs/src/inputs.rs deleted file mode 100644 index bd6fcc9..0000000 --- a/native/dubp_rs/src/inputs.rs +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; - -#[derive(Clone, Copy, Debug)] -pub(crate) enum SecretCodeType { - Digits, - Letters, -} -impl From for SecretCodeType { - fn from(i: u32) -> Self { - if i == 0 { - SecretCodeType::Digits - } else { - SecretCodeType::Letters - } - } -} -#[derive(Clone, Copy, Debug)] -pub(crate) enum WalletType { - Ed25519, - Bip32Ed25519, -} -impl From for WalletType { - fn from(i: u32) -> Self { - if i == 1 { - WalletType::Bip32Ed25519 - } else { - WalletType::Ed25519 - } - } -} - -pub(crate) fn char_ptr_to_str<'a>(c_char_ptr: *const raw::c_char) -> Result<&'a str, DubpError> { - if c_char_ptr.is_null() { - Err(DubpError::NullParamErr) - } else { - unsafe { CStr::from_ptr(c_char_ptr).to_str() }.map_err(DubpError::Utf8Error) - } -} - -pub(crate) fn char_ptr_to_opt_string( - c_char_ptr: *const raw::c_char, -) -> Result, DubpError> { - Ok(if c_char_ptr.is_null() { - None - } else { - Some( - unsafe { CStr::from_ptr(c_char_ptr).to_str() } - .map_err(DubpError::Utf8Error)? - .to_owned(), - ) - }) -} - -pub(crate) fn char_ptr_prt_to_vec_u31( - u32_ptr: *const u32, - len: u32, -) -> Result, DubpError> { - u32_ptr_to_vec_u32(u32_ptr, len) - .into_iter() - .map(|ai| U31::new(ai).map_err(DubpError::InvalidU31)) - .collect() -} - -pub(crate) fn char_ptr_prt_to_vec_str<'a>( - char_ptr_ptr: *const *const raw::c_char, - len: u32, -) -> Result, DubpError> { - let len = len as usize; - let char_ptr_slice: &[*const raw::c_char] = - unsafe { std::slice::from_raw_parts(char_ptr_ptr, len) }; - let mut str_vec = Vec::with_capacity(len); - for char_ptr in char_ptr_slice { - str_vec.push(char_ptr_to_str(*char_ptr)?); - } - Ok(str_vec) -} - -pub(crate) fn i32_to_opt_bool(i: i32) -> Option { - match i { - 1 => Some(true), - 0 => Some(false), - _ => None, - } -} - -pub(crate) fn i32_to_opt_u31(i: i32) -> Result, DubpError> { - if i >= 0 { - Ok(Some(U31::new(i as u32)?)) - } else { - Ok(None) - } -} - -pub(crate) fn i32_to_opt_u32(i: i32) -> Option { - if i >= 0 { - Some(i as u32) - } else { - None - } -} - -pub(crate) fn parse_currency(currency: &str) -> Result { - let currency_code = match currency { - "g1" => G1_CURRENCY, - "g1-test" | "gt" => G1_TEST_CURRENCY, - _ => return Err(DubpError::UnknownCurrencyName), - }; - Ok(Currency::from(currency_code)) -} - -pub(crate) fn u32_ptr_to_vec_u32(u32_ptr: *const u32, len: u32) -> Vec { - let len = len as usize; - let u32_slice: &[u32] = unsafe { std::slice::from_raw_parts(u32_ptr, len) }; - let mut vec = Vec::with_capacity(len); - for u32_ in u32_slice { - vec.push(*u32_); - } - vec -} - -pub(crate) fn u32_to_language(i: u32) -> Result { - match i { - 0 => Ok(Language::English), - 1 => Ok(Language::French), - _ => Err(DubpError::UnknownLanguage), - } -} diff --git a/native/dubp_rs/src/legacy.rs b/native/dubp_rs/src/legacy.rs deleted file mode 100644 index 1522aee..0000000 --- a/native/dubp_rs/src/legacy.rs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; -use dubp_client::crypto::keys::ed25519::{KeyPairFromSaltedPasswordGenerator, SaltedPassword}; - -#[allow(deprecated)] -pub(super) fn gen_dewif_from_legacy( - currency: &str, - salt: String, - password: String, - member_wallet: bool, - secret_code_type: SecretCodeType, - system_memory: i64, -) -> Result, DubpError> { - let currency = parse_currency(currency)?; - let keypair = KeyPairFromSaltedPasswordGenerator::with_default_parameters() - .generate(SaltedPassword::new(salt.clone(), password.clone())); - - let log_n = crate::dewif::log_n(system_memory); - let secret_code = gen_secret_code(member_wallet, secret_code_type, log_n)?; - let dewif = dubp_client::crypto::dewif::create_dewif_v1_legacy( - currency, - log_n, - password, - salt, - &secret_code, - ) - .map_err(|_| DubpError::RandErr)?; - let pubkey = keypair.public_key().to_base58(); - Ok(vec![dewif, secret_code, pubkey]) -} - -pub(super) fn get_pubkey(salt: &str, password: &str) -> String { - KeyPairFromSaltedPasswordGenerator::with_default_parameters() - .generate(SaltedPassword::new(salt.to_owned(), password.to_owned())) - .public_key() - .to_base58() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_dewif_legacy() -> Result<(), DubpError> { - let wallet = gen_dewif_from_legacy( - "g1", - "salt".to_owned(), - "pass".to_owned(), - false, - SecretCodeType::Letters, - 1_000_000_000, - )?; - let dewif = &wallet[0]; - let secret_code = &wallet[1]; - let pubkey = &wallet[2]; - - assert_eq!(pubkey, "3YumN7F7D8c2hmkHLHf3ZD8wc3tBHiECEK9zLPkaJtAF"); - - assert_eq!(get_pubkey("salt", "pass"), pubkey.to_owned()); - - assert_eq!( - crate::dewif::get_pubkey( - None, - None, - Currency::from(G1_CURRENCY), - &dewif, - None, - &secret_code - )?, - pubkey.to_owned() - ); - - Ok(()) - } -} diff --git a/native/dubp_rs/src/lib.rs b/native/dubp_rs/src/lib.rs deleted file mode 100644 index 64876fc..0000000 --- a/native/dubp_rs/src/lib.rs +++ /dev/null @@ -1,536 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -#![allow(clippy::missing_safety_doc, clippy::not_unsafe_ptr_arg_deref)] - -mod r#async; -mod dewif; -mod error; -mod inputs; -mod legacy; -mod mnemonic; -mod payment; -mod pubkey; -mod secret_code; - -use crate::error::{DartRes, DubpError}; -use crate::inputs::*; -use crate::r#async::exec_async; -use crate::secret_code::gen_secret_code; -use allo_isolate::{IntoDart, Isolate}; -use dubp_client::crypto::{ - bases::b58::ToBase58, - dewif::{ - Currency, DewifContent, DewifPayload, DewifReadError, ExpectedCurrency, G1_CURRENCY, - G1_TEST_CURRENCY, - }, - keys::{ - ed25519::bip32::{ - ChainCode, InvalidAccountIndex, KeyPair, PrivateDerivationPath, PublicKeyWithChainCode, - }, - ed25519::{KeyPairFromSeed32Generator, PublicKey, PublicKeyFromStrErr}, - KeyPair as _, KeyPairEnum, KeysAlgo, PublicKey as _, Signator as _, Signature as _, - }, - mnemonic::{Language, Mnemonic, MnemonicType}, - utils::{U31Error, U31}, -}; -use fast_threadpool::{ThreadPool, ThreadPoolConfig, ThreadPoolSyncHandler}; -use once_cell::sync::Lazy; -use parking_lot::Mutex; -use std::{collections::HashMap, ffi::CStr, io, os::raw, sync::Arc}; -use thiserror::Error; - -#[no_mangle] -pub extern "C" fn change_dewif_secret_code( - port: i64, - dewif: *const raw::c_char, - old_secret_code: *const raw::c_char, - member_wallet: u32, - secret_code_type: u32, - system_memory: i64, -) { - exec_async( - port, - || { - let dewif = char_ptr_to_str(dewif)?; - let old_secret_code = char_ptr_to_str(old_secret_code)?; - let member_wallet = member_wallet != 0; - let secret_code_type = SecretCodeType::from(secret_code_type); - Ok(( - dewif, - old_secret_code, - member_wallet, - secret_code_type, - system_memory, - )) - }, - |(dewif, old_secret_code, member_wallet, secret_code_type, system_memory)| { - dewif::change_secret_code( - dewif, - old_secret_code, - member_wallet, - secret_code_type, - system_memory, - ) - }, - ) -} - -#[no_mangle] -pub extern "C" fn check_pubkey(port: i64, pubkey: *const raw::c_char) { - exec_async(port, || char_ptr_to_str(pubkey), pubkey::check_pubkey) -} - -#[no_mangle] -pub extern "C" fn compute_checksum(port: i64, pubkey: *const raw::c_char) { - exec_async(port, || char_ptr_to_str(pubkey), pubkey::compute_checksum) -} - -#[no_mangle] -pub extern "C" fn gen_dewif( - port: i64, - currency: *const raw::c_char, - language: u32, - mnemonic: *const raw::c_char, - member_wallet: u32, - secret_code_type: u32, - system_memory: i64, -) { - exec_async( - port, - || { - let currency = char_ptr_to_str(currency)?; - let language = u32_to_language(language)?; - let mnemonic = char_ptr_to_str(mnemonic)?; - let member_wallet = member_wallet != 0; - let secret_code_type = SecretCodeType::from(secret_code_type); - Ok(( - currency, - language, - mnemonic, - member_wallet, - secret_code_type, - system_memory, - )) - }, - |(currency, language, mnemonic, member_wallet, secret_code_type, system_memory)| { - dewif::gen_dewif( - currency, - language, - mnemonic, - member_wallet, - secret_code_type, - system_memory, - ) - }, - ) -} - -#[no_mangle] -pub extern "C" fn gen_dewif_from_legacy( - port: i64, - currency: *const raw::c_char, - salt: *const raw::c_char, - password: *const raw::c_char, - member_wallet: u32, - secret_code_type: u32, - system_memory: i64, -) { - exec_async( - port, - || { - let currency = char_ptr_to_str(currency)?; - let salt = char_ptr_to_str(salt)?.to_owned(); - let password = char_ptr_to_str(password)?.to_owned(); - let member_wallet = member_wallet != 0; - let secret_code_type = SecretCodeType::from(secret_code_type); - Ok(( - currency, - salt, - password, - member_wallet, - secret_code_type, - system_memory, - )) - }, - |(currency, salt, password, member_wallet, secret_code_type, system_memory)| { - legacy::gen_dewif_from_legacy( - currency, - salt, - password, - member_wallet, - secret_code_type, - system_memory, - ) - }, - ) -} - -#[no_mangle] -pub extern "C" fn gen_mnemonic(port: i64, language: u32) { - exec_async(port, || u32_to_language(language), mnemonic::gen_mnemonic) -} - -#[no_mangle] -pub extern "C" fn get_bip32_dewif_accounts_pubkeys( - port: i64, - currency: *const raw::c_char, - dewif: *const raw::c_char, - secret_code: *const raw::c_char, - accounts_indexs_len: u32, - accounts_indexs: *const u32, -) { - exec_async( - port, - || { - let currency = parse_currency(char_ptr_to_str(currency)?)?; - let dewif = char_ptr_to_str(dewif)?; - let secret_code = char_ptr_to_str(secret_code)?; - let accounts_indexs = char_ptr_prt_to_vec_u31(accounts_indexs, accounts_indexs_len)?; - Ok((currency, dewif, secret_code, accounts_indexs)) - }, - |(currency, dewif, secret_code, accounts_indexs)| { - dewif::bip32::get_accounts_pubkeys(currency, dewif, secret_code, accounts_indexs) - }, - ) -} - -#[no_mangle] -pub extern "C" fn get_bip32_dewif_mnemonic( - port: i64, - currency: *const raw::c_char, - dewif: *const raw::c_char, - secret_code: *const raw::c_char, -) { - exec_async( - port, - || { - let currency = parse_currency(char_ptr_to_str(currency)?)?; - let dewif = char_ptr_to_str(dewif)?; - let secret_code = char_ptr_to_str(secret_code)?; - Ok((currency, dewif, secret_code)) - }, - |(currency, dewif, secret_code)| dewif::bip32::get_mnemonic(currency, dewif, secret_code), - ) -} - -#[no_mangle] -pub extern "C" fn get_dewif_meta( - port: i64, - dewif: *const raw::c_char, - member_wallet: u32, - secret_code_type: u32, -) { - exec_async( - port, - || { - let dewif = char_ptr_to_str(dewif)?; - let member_wallet = member_wallet != 0; - let secret_code_type = SecretCodeType::from(secret_code_type); - Ok((dewif, member_wallet, secret_code_type)) - }, - |(dewif, member_wallet, secret_code_type)| { - dewif::get_dewif_meta(dewif, member_wallet, secret_code_type) - }, - ) -} - -#[no_mangle] -pub extern "C" fn get_dewif_secret_code_len( - dewif: *const raw::c_char, - member_wallet: u32, - secret_code_type: u32, -) -> i32 { - if let Ok(secret_code_len) = dewif::get_secret_code_len(dewif, member_wallet, secret_code_type) - { - secret_code_len as i32 - } else { - -1 - } -} - -#[no_mangle] -pub extern "C" fn get_dewif_pubkey( - port: i64, - account_index: i32, - address_index: i32, - currency: *const raw::c_char, - dewif: *const raw::c_char, - external_opt: i32, - pin: *const raw::c_char, -) { - exec_async( - port, - || { - let account_index_opt = i32_to_opt_u32(account_index); - let address_index_opt = i32_to_opt_u31(address_index)?; - let currency = parse_currency(char_ptr_to_str(currency)?)?; - let dewif = char_ptr_to_str(dewif)?; - let external_opt = i32_to_opt_bool(external_opt); - let pin = char_ptr_to_str(pin)?; - Ok(( - account_index_opt, - address_index_opt, - currency, - dewif, - external_opt, - pin, - )) - }, - |(account_index_opt, address_index_opt, currency, dewif, external_opt, pin)| { - dewif::get_pubkey( - account_index_opt, - address_index_opt, - currency, - dewif, - external_opt, - pin, - ) - }, - ) -} - -#[no_mangle] -pub extern "C" fn get_opaque_account_next_external_address(port: i64, account_index: u32) { - exec_async( - port, - || { - let account_index = U31::new(account_index)?; - Ok(account_index) - }, - dewif::bip32::get_opaque_account_next_external_address, - ) -} - -#[no_mangle] -pub extern "C" fn load_opaque_bip32_accounts( - port: i64, - accounts_indexs_len: u32, - accounts_indexs: *const u32, - currency: *const raw::c_char, - dewif: *const raw::c_char, - secret_code: *const raw::c_char, -) { - exec_async( - port, - || { - let accounts_indexs = char_ptr_prt_to_vec_u31(accounts_indexs, accounts_indexs_len)?; - let currency = parse_currency(char_ptr_to_str(currency)?)?; - let dewif = char_ptr_to_str(dewif)?; - let secret_code = char_ptr_to_str(secret_code)?; - Ok((accounts_indexs, currency, dewif, secret_code)) - }, - |(accounts_indexs, currency, dewif, secret_code)| { - dewif::bip32::load_opaque_bip32_accounts(accounts_indexs, currency, dewif, secret_code) - }, - ) -} - -#[no_mangle] -pub extern "C" fn get_legacy_pubkey( - port: i64, - salt: *const raw::c_char, - password: *const raw::c_char, -) { - exec_async( - port, - || { - let salt = char_ptr_to_str(salt)?; - let password = char_ptr_to_str(password)?; - Ok((salt, password)) - }, - |(salt, password)| Ok::<_, DubpError>(legacy::get_pubkey(salt, password)), - ) -} - -#[no_mangle] -pub extern "C" fn mnemonic_to_pubkey( - port: i64, - language: u32, - mnemonic_phrase: *const raw::c_char, -) { - exec_async( - port, - || { - let language = u32_to_language(language)?; - let mnemonic_phrase = char_ptr_to_str(mnemonic_phrase)?; - Ok((language, mnemonic_phrase)) - }, - |(language, mnemonic_phrase)| mnemonic::mnemonic_to_pubkey(language, mnemonic_phrase), - ) -} - -#[no_mangle] -pub extern "C" fn sign( - port: i64, - account_index: i32, - address_index: i32, - currency: *const raw::c_char, - dewif: *const raw::c_char, - external_opt: i32, - secret_code: *const raw::c_char, - msg: *const raw::c_char, -) { - exec_async( - port, - || { - let account_index_opt = i32_to_opt_u32(account_index); - let address_index_opt = i32_to_opt_u31(address_index)?; - let currency = parse_currency(char_ptr_to_str(currency)?)?; - let dewif = char_ptr_to_str(dewif)?; - let external_opt = i32_to_opt_bool(external_opt); - let secret_code = char_ptr_to_str(secret_code)?; - let msg = char_ptr_to_str(msg)?; - Ok(( - account_index_opt, - address_index_opt, - currency, - dewif, - external_opt, - secret_code, - msg, - )) - }, - |( - account_index_opt, - address_index_opt, - currency, - dewif, - external_opt, - secret_code, - msg, - )| { - dewif::sign( - account_index_opt, - address_index_opt, - currency, - dewif, - external_opt, - secret_code, - msg, - ) - }, - ) -} - -#[no_mangle] -pub extern "C" fn sign_several( - port: i64, - account_index: i32, - address_index: i32, - currency: *const raw::c_char, - dewif: *const raw::c_char, - external_opt: i32, - secret_code: *const raw::c_char, - msgs_len: u32, - msgs: *const *const raw::c_char, -) { - exec_async( - port, - || { - let account_index_opt = i32_to_opt_u32(account_index); - let address_index_opt = i32_to_opt_u31(address_index)?; - let currency = parse_currency(char_ptr_to_str(currency)?)?; - let dewif = char_ptr_to_str(dewif)?; - let external_opt = i32_to_opt_bool(external_opt); - let secret_code = char_ptr_to_str(secret_code)?; - let msgs = char_ptr_prt_to_vec_str(msgs, msgs_len)?; - Ok(( - account_index_opt, - address_index_opt, - currency, - dewif, - external_opt, - secret_code, - msgs, - )) - }, - |( - account_index_opt, - address_index_opt, - currency, - dewif, - external_opt, - secret_code, - msgs, - )| { - dewif::sign_several( - account_index_opt, - address_index_opt, - currency, - dewif, - external_opt, - secret_code, - &msgs, - ) - }, - ) -} - -#[no_mangle] -pub extern "C" fn simple_payment_bip32( - port: i64, - account_index: u32, - amount: f64, - currency: *const raw::c_char, - dewif: *const raw::c_char, - gva_endpoint: *const raw::c_char, - recipient: *const raw::c_char, - secret_code: *const raw::c_char, - tx_comment: *const raw::c_char, -) { - exec_async( - port, - || { - let currency = parse_currency(char_ptr_to_str(currency)?)?; - let dewif = char_ptr_to_str(dewif)?; - let gva_endpoint = char_ptr_to_str(gva_endpoint)?; - let recipient = char_ptr_to_str(recipient)?; - let secret_code = char_ptr_to_str(secret_code)?; - let tx_comment = char_ptr_to_opt_string(tx_comment)?; - Ok(( - account_index, - amount, - currency, - dewif, - gva_endpoint, - secret_code, - recipient, - tx_comment, - )) - }, - |( - account_index, - amount, - currency, - dewif, - gva_endpoint, - secret_code, - recipient, - tx_comment, - )| { - payment::simple_payment( - account_index, - amount, - currency, - dewif, - gva_endpoint, - secret_code, - recipient, - tx_comment, - ) - }, - ) -} diff --git a/native/dubp_rs/src/mnemonic.rs b/native/dubp_rs/src/mnemonic.rs deleted file mode 100644 index 0b9849a..0000000 --- a/native/dubp_rs/src/mnemonic.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; - -pub(super) fn gen_mnemonic(language: Language) -> Result { - let mnemonic = - Mnemonic::new(MnemonicType::Words12, language).map_err(|_| DubpError::RandErr)?; - Ok(mnemonic.phrase().to_owned()) -} - -pub(super) fn mnemonic_to_pubkey(language: Language, mnemonic: &str) -> Result { - let mnemonic = - Mnemonic::from_phrase(mnemonic, language).map_err(|_| DubpError::WrongLanguage)?; - let seed = dubp_client::crypto::mnemonic::mnemonic_to_seed(&mnemonic); - let keypair = KeyPairFromSeed32Generator::generate(seed); - Ok(keypair.public_key().to_base58()) -} diff --git a/native/dubp_rs/src/payment.rs b/native/dubp_rs/src/payment.rs deleted file mode 100644 index b4c4a5f..0000000 --- a/native/dubp_rs/src/payment.rs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; -use dubp_client::wallet::prelude::*; -use dubp_client::{GvaClient, NaiveGvaClient}; - -#[allow(clippy::too_many_arguments)] -pub(super) fn simple_payment( - account_index: u32, - amount: f64, - currency: Currency, - dewif: &str, - gva_endpoint: &str, - secret_code: &str, - recipient: &str, - tx_comment: Option, -) -> Result<(), DubpError> { - let keypair = crate::dewif::bip32::get_bip32_keypair( - account_index, - None, - currency, - dewif, - None, - secret_code, - )?; - - let gva_client = NaiveGvaClient::new(gva_endpoint).expect("invalid' endpoint"); - - let amount = dubp_client::Amount::Uds(amount); - - let recipient = if let Ok(pubkey) = PublicKey::from_base58(recipient) { - WalletScriptV10::single_sig(pubkey) - } else { - dubp_client::documents_parser::wallet_script_from_str(recipient) - .map_err(DubpError::InvalidScript)? - }; - - let res = match keypair.generate_signator() { - dubp_client::crypto::keys::SignatorEnum::Ed25519(signator) => gva_client - .simple_payment(amount, &signator, recipient, tx_comment, None) - .map_err(DubpError::GvaClientError)?, - dubp_client::crypto::keys::SignatorEnum::Schnorr() => unreachable!(), - dubp_client::crypto::keys::SignatorEnum::Bip32Ed25519(signator) => gva_client - .simple_payment(amount, &signator, recipient, tx_comment, None) - .map_err(DubpError::GvaClientError)?, - }; - - if let dubp_client::PaymentResult::Errors(errors) = res { - Err(DubpError::PaymentError(format!("{:?}", errors))) - } else { - Ok(()) - } -} diff --git a/native/dubp_rs/src/pubkey.rs b/native/dubp_rs/src/pubkey.rs deleted file mode 100644 index 6c33825..0000000 --- a/native/dubp_rs/src/pubkey.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; - -pub(crate) fn check_pubkey(pubkey: &str) -> Result<(), DubpError> { - PublicKey::from_base58_with_checksum_opt(pubkey).map_err(DubpError::InvalidPubkey)?; - Ok(()) -} - -pub(crate) fn compute_checksum(pubkey: &str) -> Result { - Ok(PublicKey::from_base58(pubkey) - .map_err(|e| DubpError::InvalidPubkey(PublicKeyFromStrErr::BaseConversionError(e)))? - .checksum()) -} diff --git a/native/dubp_rs/src/secret_code.rs b/native/dubp_rs/src/secret_code.rs deleted file mode 100644 index ab6efc1..0000000 --- a/native/dubp_rs/src/secret_code.rs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (C) 2020 Éloïs SANCHEZ. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use crate::*; - -pub(crate) fn compute_secret_code_len( - member_wallet: bool, - secret_code_type: SecretCodeType, - log_n: u8, -) -> Result { - match secret_code_type { - SecretCodeType::Digits => { - if member_wallet { - Err(DubpError::DigitsCodeForbidForMemberWallet) - } else if log_n >= 15 { - Ok(7) - } else { - Ok(8) - } - } - SecretCodeType::Letters => { - if member_wallet { - if log_n >= 15 { - Ok(7) - } else { - Ok(8) - } - } else if log_n >= 15 { - Ok(5) - } else { - Ok(6) - } - } - } -} - -pub(crate) fn gen_secret_code( - member_wallet: bool, - secret_code_type: SecretCodeType, - log_n: u8, -) -> Result { - let secret_code_len = compute_secret_code_len(member_wallet, secret_code_type, log_n)?; - match secret_code_type { - SecretCodeType::Digits => gen_random_digits(secret_code_len), - SecretCodeType::Letters => gen_random_letters(secret_code_len), - } -} - -pub(crate) fn is_ascii_letters(secret_code: &str) -> bool { - secret_code.len() - == secret_code - .chars() - .filter(|char| char.is_ascii_alphabetic()) - .count() -} - -fn gen_random_digits(n: usize) -> Result { - let mut digits_string = dubp_client::crypto::rand::gen_u32() - .map_err(|_| DubpError::RandErr)? - .to_string(); - digits_string.truncate(n); - - if digits_string.len() == n { - Ok(digits_string) - } else { - let missing_digits = n - digits_string.len(); - let mut digits_string_ = String::with_capacity(n); - for _ in 0..missing_digits { - digits_string_.push('0'); - } - digits_string_.push_str(&digits_string); - Ok(digits_string_) - } -} - -fn gen_random_letters(mut n: usize) -> Result { - let mut letters = String::with_capacity(n); - while n >= 6 { - letters.push_str(&gen_random_letters_inner(6)?); - n -= 6; - } - letters.push_str(&gen_random_letters_inner(n)?); - - Ok(letters) -} - -fn gen_random_letters_inner(n: usize) -> Result { - let mut i = dubp_client::crypto::rand::gen_u32().map_err(|_| DubpError::RandErr)?; - let mut letters = String::new(); - - for _ in 0..n { - letters.push(to_char(i)); - i /= 26; - } - - Ok(letters) -} - -fn to_char(i: u32) -> char { - match i % 26 { - 0 => 'A', - 1 => 'B', - 2 => 'C', - 3 => 'D', - 4 => 'E', - 5 => 'F', - 6 => 'G', - 7 => 'H', - 8 => 'I', - 9 => 'J', - 10 => 'K', - 11 => 'L', - 12 => 'M', - 13 => 'N', - 14 => 'O', - 15 => 'P', - 16 => 'Q', - 17 => 'R', - 18 => 'S', - 19 => 'T', - 20 => 'U', - 21 => 'V', - 22 => 'W', - 23 => 'X', - 24 => 'Y', - 25 => 'Z', - _ => unreachable!(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_gen_random_digits() -> Result<(), DubpError> { - assert_eq!(gen_random_digits(8)?.len(), 8); - //println!("TMP: {}", gen_random_digits(8)?); - Ok(()) - } - #[test] - fn test_gen_random_letters() -> Result<(), DubpError> { - assert_eq!(gen_random_letters(6)?.len(), 6); - //println!("TMP: {}", gen_random_letters(6)?); - Ok(()) - } -} diff --git a/packages/dubp_rs/.metadata b/packages/dubp_rs/.metadata deleted file mode 100644 index 4b7663f..0000000 --- a/packages/dubp_rs/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: f7a6a7906be96d2288f5d63a5a54c515a6e987fe - channel: stable - -project_type: plugin diff --git a/packages/dubp_rs/LICENSE b/packages/dubp_rs/LICENSE deleted file mode 100644 index dba13ed..0000000 --- a/packages/dubp_rs/LICENSE +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/packages/dubp_rs/README.md b/packages/dubp_rs/README.md deleted file mode 100644 index 6be3629..0000000 --- a/packages/dubp_rs/README.md +++ /dev/null @@ -1,198 +0,0 @@ -# dubp - -Flutter package that bind [dubp-rs-libs] Rust crates. - -## Setup - -### Prerequisites - -* Android SDK -* Android **N**DK (**Native** Development Kit) -* Rust and cargo -* Cargo plugin cargo-make: `cargo install cargo-make` -* LLVM/Clang (see dedicated section below) - -You must indicate where the SDK and NDK are located via the `ANDROID_SDK_ROOT` and `ANDROID_NDK_HOME` environment variables. -For example: - - export ANDROID_SDK_ROOT="/home/user/dev/android_sdk" - export ANDROID_NDK_HOME="/home/user/dev/android_sdk/ndk/22.0.7026061" - -You will also need to add targets for all Android architectures: - -```sh -rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android i686-linux-android -``` - -If you develop on mac, you can also add targets for iOS: - -```sh -rustup target add aarch64-apple-ios x86_64-apple-ios -``` - -### LLVM/Clang - -The project use [`dart-bindgen`](https://github.com/sunshine-protocol/dart-bindgen) which requires LLVM/Clang. Install LLVM (10+) in the following way: - -#### ubuntu/linux - -1. Install libclangdev - `sudo apt-get install libclang-dev`. - -#### Windows - -1. Install Visual Studio with C++ development support. -2. Install [LLVM](https://releases.llvm.org/download.html) or `winget install -e --id LLVM.LLVM`. - -#### MacOS - -1. Install Xcode. -2. Install LLVM - `brew install llvm`. - -## Compile - -### For development - -**To reduce the compilation time of the Rust code** during your development, you can **compile only for the target corresponding to your android emulator**. Here is how to do it **depending on the architecture of your emulator**: - -* 32bit emulator (`x86`/`i686` architecture) - -```sh -cargo bd -``` - -* 64bit emulator (`x86_64` architecture) - -```sh -cargo make android-dev -``` - -### For release - -In the Root of the project simply run: - -```sh -cargo br -``` - -WARNING: This will take a lot of time because the Rust code will have to be recompiled for each different architecture, 4 times for android and 2 times for iOS! - -## Use - -You must execute this instruction at startup of your application: - -```dart -DubpRust.setup(); -``` - -### Generate a random Mnemonic - -#### Function signature - -```dart -static Future DubpRust.genMnemonic({Language language = Language.english}); -``` - -#### Usage example - -```dart -String mnemonic = await DubpRust.genMnemonic(); -``` - -You can choose a language (english by default): - -```dart -String mnemonic = await DubpRust.genMnemonic(language: Language.french); -``` - -### Generate a wallet - -#### Function signature - -```dart -static Future genWalletFromMnemonic({ - String currency = "g1", - Language language = Language.english, - String mnemonic, - SecretCodeType secretCodeType = SecretCodeType.letters -}); -``` - -If the mnemonic is not in english, you must indicate the language of the mnemonic (necessary for the verification of its validity). -If the wallet to be generated is not dedicated to the Ğ1 currency, you must indicate the currency for which this wallet will be used. - -#### Usage example - -```dart -NewWallet new_wallet = await DubpRust.genWalletFromMnemonic( - language: Language.english, - mnemonic: "tongue cute mail fossil great frozen same social weasel impact brush kind" -); -``` - -You can choose a different secret code type: - -```dart -NewWallet new_wallet = await DubpRust.genWalletFromMnemonic( - language: Language.english, - mnemonic: "tongue cute mail fossil great frozen same social weasel impact brush kind", - secretCodeType: SecretCodeType.digits -); -``` - -### Sign a message - -#### Function signature - -```dart -static Future sign({ - int accountIndex, - int addressIndexOpt, - String currency = "g1", - String dewif, - bool externalOpt, - String secretCode, - String message -}); -``` - -If the wallet is not dedicated to the Ğ1 currency, you must indicate the currency. - -#### Usage example - -```dart -String signature = await DubpRust.sign( - accountIndex: 3, - dewif: "AAAAARAAAAGfFDAs+jVZYkfhBlHZZ2fEQIvBqnG16g5+02cY18wSOjW0cUg2JV3SUTJYN2CrbQeRDwGazWnzSFBphchMmiL0", - pin: "CDJ4UB", - message: "toto" -); -``` - -### Change secret code - -You can change the secret code that encrypts the [DEWIF]. - -#### Function signature - -```dart -static Future changeDewifPin({ - String currency = "g1", - String dewif, - String oldPin, - SecretCodeType secretCodeType = SecretCodeType.letters -}); -``` - -If the wallet is not dedicated to the Ğ1 currency, you must indicate the currency. - -#### Usage example - -```dart -NewWallet new_wallet = await DubpRust.changeDewifPin( - dewif: "AAAAARAAAAGfFDAs+jVZYkfhBlHZZ2fEQIvBqnG16g5+02cY18wSOjW0cUg2JV3SUTJYN2CrbQeRDwGazWnzSFBphchMmiL0", - oldPin: "CDJAUB", -); -``` - -[dubp-rs-libs]: https://git.duniter.org/libs/dubp-rs-libs -[DEWIF]: https://git.duniter.org/documents/rfcs/blob/dewif/rfc/0013_Duniter_Encrypted_Wallet_Import_Format.md diff --git a/packages/dubp_rs/analysis_options.yaml b/packages/dubp_rs/analysis_options.yaml deleted file mode 100644 index 572b2c2..0000000 --- a/packages/dubp_rs/analysis_options.yaml +++ /dev/null @@ -1,12 +0,0 @@ -include: package:effective_dart/analysis_options.yaml - -analyzer: - exclude: - - lib/ffi.dart - strong-mode: - implicit-casts: false - implicit-dynamic: false - -linter: - rules: - omit_local_variable_types: false diff --git a/packages/dubp_rs/android/.gitignore b/packages/dubp_rs/android/.gitignore deleted file mode 100644 index c6cbe56..0000000 --- a/packages/dubp_rs/android/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*.iml -.gradle -/local.properties -/.idea/workspace.xml -/.idea/libraries -.DS_Store -/build -/captures diff --git a/packages/dubp_rs/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java b/packages/dubp_rs/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java deleted file mode 100644 index 9f52030..0000000 --- a/packages/dubp_rs/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.flutter.plugins; - -import io.flutter.plugin.common.PluginRegistry; -import com.example.dubp.DubpPlugin; - -/** - * Generated file. Do not edit. - */ -public final class GeneratedPluginRegistrant { - public static void registerWith(PluginRegistry registry) { - if (alreadyRegisteredWith(registry)) { - return; - } - DubpPlugin.registerWith(registry.registrarFor("com.example.dubp.DubpPlugin")); - } - - private static boolean alreadyRegisteredWith(PluginRegistry registry) { - final String key = GeneratedPluginRegistrant.class.getCanonicalName(); - if (registry.hasPlugin(key)) { - return true; - } - registry.registrarFor(key); - return false; - } -} diff --git a/packages/dubp_rs/android/build.gradle b/packages/dubp_rs/android/build.gradle deleted file mode 100644 index a11bf58..0000000 --- a/packages/dubp_rs/android/build.gradle +++ /dev/null @@ -1,43 +0,0 @@ -group 'com.example.dubp' -version '1.0-SNAPSHOT' - -buildscript { - ext.kotlin_version = '1.3.50' - repositories { - google() - jcenter() - } - - dependencies { - classpath 'com.android.tools.build:gradle:3.5.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -rootProject.allprojects { - repositories { - google() - jcenter() - } -} - -apply plugin: 'com.android.library' -apply plugin: 'kotlin-android' - -android { - compileSdkVersion 28 - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - defaultConfig { - minSdkVersion 16 - } - lintOptions { - disable 'InvalidPackage' - } -} - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" -} diff --git a/packages/dubp_rs/android/gradle.properties b/packages/dubp_rs/android/gradle.properties deleted file mode 100644 index 38c8d45..0000000 --- a/packages/dubp_rs/android/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.gradle.jvmargs=-Xmx1536M -android.enableR8=true -android.useAndroidX=true -android.enableJetifier=true diff --git a/packages/dubp_rs/android/gradle/wrapper/gradle-wrapper.properties b/packages/dubp_rs/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 01a286e..0000000 --- a/packages/dubp_rs/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip diff --git a/packages/dubp_rs/android/settings.gradle b/packages/dubp_rs/android/settings.gradle deleted file mode 100644 index ae6f0f7..0000000 --- a/packages/dubp_rs/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'dubp' diff --git a/packages/dubp_rs/android/src/main/AndroidManifest.xml b/packages/dubp_rs/android/src/main/AndroidManifest.xml deleted file mode 100644 index 6206217..0000000 --- a/packages/dubp_rs/android/src/main/AndroidManifest.xml +++ /dev/null @@ -1,3 +0,0 @@ - - diff --git a/packages/dubp_rs/android/src/main/kotlin/com/example/dubp/DubpPlugin.kt b/packages/dubp_rs/android/src/main/kotlin/com/example/dubp/DubpPlugin.kt deleted file mode 100644 index e0945fc..0000000 --- a/packages/dubp_rs/android/src/main/kotlin/com/example/dubp/DubpPlugin.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.example.dubp - -import androidx.annotation.NonNull; - -import io.flutter.embedding.engine.plugins.FlutterPlugin -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import io.flutter.plugin.common.MethodChannel.MethodCallHandler -import io.flutter.plugin.common.MethodChannel.Result -import io.flutter.plugin.common.PluginRegistry.Registrar - -/** DubpPlugin */ -public class DubpPlugin: FlutterPlugin, MethodCallHandler { - /// The MethodChannel that will the communication between Flutter and native Android - /// - /// This local reference serves to register the plugin with the Flutter Engine and unregister it - /// when the Flutter Engine is detached from the Activity - private lateinit var channel : MethodChannel - - override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { - channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "dubp") - channel.setMethodCallHandler(this); - } - - // This static function is optional and equivalent to onAttachedToEngine. It supports the old - // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting - // plugin registration via this function while apps migrate to use the new Android APIs - // post-flutter-1.12 via https://flutter.dev/go/android-project-migration. - // - // It is encouraged to share logic between onAttachedToEngine and registerWith to keep - // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called - // depending on the user's project. onAttachedToEngine or registerWith must both be defined - // in the same class. - companion object { - @JvmStatic - fun registerWith(registrar: Registrar) { - val channel = MethodChannel(registrar.messenger(), "dubp") - channel.setMethodCallHandler(DubpPlugin()) - } - } - - override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { - if (call.method == "getPlatformVersion") { - result.success("Android ${android.os.Build.VERSION.RELEASE}") - } else { - result.notImplemented() - } - } - - override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { - channel.setMethodCallHandler(null) - } -} diff --git a/packages/dubp_rs/ios/.gitignore b/packages/dubp_rs/ios/.gitignore deleted file mode 100644 index aa479fd..0000000 --- a/packages/dubp_rs/ios/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -.idea/ -.vagrant/ -.sconsign.dblite -.svn/ - -.DS_Store -*.swp -profile - -DerivedData/ -build/ -GeneratedPluginRegistrant.h -GeneratedPluginRegistrant.m - -.generated/ - -*.pbxuser -*.mode1v3 -*.mode2v3 -*.perspectivev3 - -!default.pbxuser -!default.mode1v3 -!default.mode2v3 -!default.perspectivev3 - -xcuserdata - -*.moved-aside - -*.pyc -*sync/ -Icon? -.tags* - -/Flutter/Generated.xcconfig -/Flutter/flutter_export_environment.sh \ No newline at end of file diff --git a/packages/dubp_rs/ios/Assets/.gitkeep b/packages/dubp_rs/ios/Assets/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/dubp_rs/ios/Classes/DubpPlugin.h b/packages/dubp_rs/ios/Classes/DubpPlugin.h deleted file mode 100644 index b0e2d33..0000000 --- a/packages/dubp_rs/ios/Classes/DubpPlugin.h +++ /dev/null @@ -1,4 +0,0 @@ -#import - -@interface DubpPlugin : NSObject -@end diff --git a/packages/dubp_rs/ios/Classes/DubpPlugin.m b/packages/dubp_rs/ios/Classes/DubpPlugin.m deleted file mode 100644 index 4144f90..0000000 --- a/packages/dubp_rs/ios/Classes/DubpPlugin.m +++ /dev/null @@ -1,15 +0,0 @@ -#import "DubpPlugin.h" -#if __has_include() -#import -#else -// Support project import fallback if the generated compatibility header -// is not copied when this plugin is created as a library. -// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816 -#import "dubp-Swift.h" -#endif - -@implementation DubpPlugin -+ (void)registerWithRegistrar:(NSObject*)registrar { - [SwiftDubpPlugin registerWithRegistrar:registrar]; -} -@end diff --git a/packages/dubp_rs/ios/Classes/SwiftDubpPlugin.swift b/packages/dubp_rs/ios/Classes/SwiftDubpPlugin.swift deleted file mode 100644 index 7108aa4..0000000 --- a/packages/dubp_rs/ios/Classes/SwiftDubpPlugin.swift +++ /dev/null @@ -1,18 +0,0 @@ -import Flutter -import UIKit - -public class SwiftDubpPlugin: NSObject, FlutterPlugin { - public static func register(with registrar: FlutterPluginRegistrar) { - let channel = FlutterMethodChannel(name: "dubp", binaryMessenger: registrar.messenger()) - let instance = SwiftDubpPlugin() - registrar.addMethodCallDelegate(instance, channel: channel) - } - - public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - result("iOS " + UIDevice.current.systemVersion) - } - - public static func dummyMethodToEnforceBundling() { - last_error_length() - } -} diff --git a/packages/dubp_rs/ios/Classes/binding.h b/packages/dubp_rs/ios/Classes/binding.h deleted file mode 100644 index cc4acf2..0000000 --- a/packages/dubp_rs/ios/Classes/binding.h +++ /dev/null @@ -1,240 +0,0 @@ -#include -#include -#include -#include - -/** - * A Dart_CObject is used for representing Dart objects as native C - * data outside the Dart heap. These objects are totally detached from - * the Dart heap. Only a subset of the Dart objects have a - * representation as a Dart_CObject. - * - * The string encoding in the 'value.as_string' is UTF-8. - * - * All the different types from dart:typed_data are exposed as type - * kTypedData. The specific type from dart:typed_data is in the type - * field of the as_typed_data structure. The length in the - * as_typed_data structure is always in bytes. - * - * The data for kTypedData is copied on message send and ownership remains with - * the caller. The ownership of data for kExternalTyped is passed to the VM on - * message send and returned when the VM invokes the - * Dart_WeakPersistentHandleFinalizer callback; a non-NULL callback must be - * provided. - */ -typedef struct DartCObject DartCObject; -enum DartCObjectType -#ifdef __cplusplus - : int32_t -#endif // __cplusplus -{ - DartNull = 0, - DartBool = 1, - DartInt32 = 2, - DartInt64 = 3, - DartDouble = 4, - DartString = 5, - DartArray = 6, - DartTypedData = 7, - DartExternalTypedData = 8, - DartSendPort = 9, - DartCapability = 10, - DartUnsupported = 11, - DartNumberOfTypes = 12, -}; -#ifndef __cplusplus -typedef int32_t DartCObjectType; -#endif // __cplusplus - -enum DartTypedDataType -#ifdef __cplusplus - : int32_t -#endif // __cplusplus -{ - kByteData = 0, - kInt8 = 1, - kUint8 = 2, - kUint8Clamped = 3, - kInt16 = 4, - kUint16 = 5, - kInt32 = 6, - kUint32 = 7, - kInt64 = 8, - kUint64 = 9, - kFloat32 = 10, - kFloat64 = 11, - kFloat32x4 = 12, - kInvalid = 13, -}; -#ifndef __cplusplus -typedef int32_t DartTypedDataType; -#endif // __cplusplus - -typedef void *RuntimePtr; - -/** - * A port is used to send or receive inter-isolate messages - */ -typedef int64_t DartPort; - -typedef struct DartNativeSendPort -{ - DartPort id; - DartPort origin_id; -} DartNativeSendPort; - -typedef struct DartNativeCapability -{ - int64_t id; -} DartNativeCapability; - -typedef struct DartNativeArray -{ - intptr_t length; - DartCObject **values; -} DartNativeArray; - -typedef struct DartNativeTypedData -{ - DartTypedDataType type_; - intptr_t length; - uint8_t *values; -} DartNativeTypedData; - -typedef struct _DartWeakPersistentHandle -{ - uint8_t _unused[0]; -} _DartWeakPersistentHandle; - -typedef _DartWeakPersistentHandle *DartWeakPersistentHandle; - -typedef void (*DartWeakPersistentHandleFinalizer)(void *isolate_callback_data, DartWeakPersistentHandle handle, void *peer); - -typedef struct DartNativeExternalTypedData -{ - DartTypedDataType type_; - intptr_t length; - uint8_t *data; - void *peer; - DartWeakPersistentHandleFinalizer callback; -} DartNativeExternalTypedData; - -typedef union DartCObjectValue { - bool as_bool; - int32_t as_int32; - int64_t as_int64; - double as_double; - char *as_string; - DartNativeSendPort as_send_port; - DartNativeCapability as_capability; - DartNativeArray as_array; - DartNativeTypedData as_typed_data; - DartNativeExternalTypedData as_external_typed_data; - uint64_t _bindgen_union_align[5]; -} DartCObjectValue; - -typedef struct DartCObject -{ - DartCObjectType type_; - DartCObjectValue value; -} DartCObject; - -/** - * Posts a message on some port. The message will contain the - * Dart_CObject object graph rooted in 'message'. - * - * While the message is being sent the state of the graph of - * Dart_CObject structures rooted in 'message' should not be accessed, - * as the message generation will make temporary modifications to the - * data. When the message has been sent the graph will be fully - * restored. - * - * port_id The destination port. - * message The message to send. - * - * return true if the message was posted. - */ -typedef bool (*DartPostCObjectFnPtr)(DartPort port_id, DartCObject *message); - -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus - -void change_dewif_secret_code(int64_t port, - const char *dewif, - const char *old_secret_code, - uint32_t member_wallet, - uint32_t secret_code_type, - int64_t system_memory); - -void gen_dewif(int64_t port, - const char *currency, - uint32_t language, - const char *mnemonic, - uint32_t member_wallet, - uint32_t secret_code_type, - int64_t system_memory, - uint32_t wallet_type); - -void gen_dewif_from_legacy(int64_t port, - const char *currency, - const char *salt, - const char *password, - uint32_t member_wallet, - uint32_t secret_code_type, - int64_t system_memory); - -void gen_mnemonic(int64_t port, uint32_t language); - -void get_bip32_dewif_accounts_pubkeys(int64_t port, - const char *currency, - const char *dewif, - const char *secret_code, - uint32_t accounts_indexs_len, - const uint32_t *accounts_indexs); - -void get_dewif_meta(int64_t port, - const char *dewif, - uint32_t member_wallet, - uint32_t secret_code_type); - -void get_dewif_pubkey(int64_t port, const char *currency, const char *dewif, const char *pin); - -int32_t get_dewif_secret_code_len(const char *dewif, - uint32_t member_wallet, - uint32_t secret_code_type); - -void get_legacy_pubkey(int64_t port, const char *salt, const char *password); - -void mnemonic_to_pubkey(int64_t port, uint32_t language, const char *mnemonic_phrase); - -void sign(int64_t port, const char *currency, const char *dewif, const char *pin, const char *msg); - -void sign_bip32_transparent(int64_t port, - uint32_t account_index, - const char *currency, - const char *dewif, - const char *secret_code, - const char *msg); - -void sign_legacy(int64_t port, const char *salt, const char *password, const char *msg); - -void sign_several(int64_t port, - const char *currency, - const char *dewif, - const char *pin, - uint32_t msgs_len, - const char *const *msgs); - -void sign_several_bip32_transparent(int64_t port, - uint32_t account_index, - const char *currency, - const char *dewif, - const char *pin, - uint32_t msgs_len, - const char *const *msgs); - -#ifdef __cplusplus -} // extern "C" -#endif // __cplusplus diff --git a/packages/dubp_rs/ios/dubp.podspec b/packages/dubp_rs/ios/dubp.podspec deleted file mode 100644 index 459e34b..0000000 --- a/packages/dubp_rs/ios/dubp.podspec +++ /dev/null @@ -1,26 +0,0 @@ -# -# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. -# Run `pod lib lint dubp.podspec' to validate before publishing. -# -Pod::Spec.new do |s| - s.name = 'dubp' - s.version = '0.0.1' - s.summary = 'A new flutter plugin project.' - s.description = <<-DESC -A new flutter plugin project. - DESC - s.homepage = 'http://example.com' - s.license = { :file => '../LICENSE' } - s.author = { 'Your Company' => 'email@example.com' } - s.source = { :path => '.' } - s.public_header_files = 'Classes**/*.h' - s.source_files = 'Classes/**/*' - s.static_framework = true - s.vendored_libraries = "**/*.a" - s.dependency 'Flutter' - s.platform = :ios, '8.0' - - # Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported. - s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' } - s.swift_version = '5.0' -end diff --git a/packages/dubp_rs/lib/dubp.dart b/packages/dubp_rs/lib/dubp.dart deleted file mode 100644 index b6d1d30..0000000 --- a/packages/dubp_rs/lib/dubp.dart +++ /dev/null @@ -1,504 +0,0 @@ -import 'dart:async'; -import 'dart:ffi'; -import 'package:ffi/ffi.dart'; -import 'package:isolate/ports.dart'; -import "package:system_info/system_info.dart"; - -import 'ffi.dart' as native; - -/// DEWIF meta data -class DewifMetaData { - /// Currency name - String currency; - - /// Secret code length - int secretCodeLen; - - /// DEWIF version - int version; - - /// Wallet type - WalletType walletType; - - DewifMetaData._(this.currency, this.secretCodeLen, this.version) { - if (version == 4) { - walletType = WalletType.bip32Ed25519; - } else { - walletType = WalletType.ed25519; - } - } -} - -/// Language -enum Language { - /// English - english, - - /// French - french, -} - -/// New wallet -class NewWallet { - /// DEWIF: Encrypted wallet - String dewif; - - /// Secret code - String pin; - - NewWallet._(this.dewif, this.pin); -} - -/// Secret code type -enum SecretCodeType { - /// Digits - digits, - - /// Letters - letters, -} - -/// Wallet type -enum WalletType { - /// Ed25519 - ed25519, - - /// BIP32-Ed25519 - bip32Ed25519, -} - -// ignore: avoid_classes_with_only_static_members -/// DUBP Rust utilities -/// -/// All the functions of this package are static methods of this -/// class `DubpRust`. -class DubpRust { - /// Must be called only once at the start of your application. - static void setup() { - native.store_dart_post_cobject(NativeApi.postCObject); - print("DUBP_RS Setup Done"); - } - - /// Change the secret code that encrypts the `dewif` keypair. - static Future changeDewifPin({ - String dewif, - String oldPin, - SecretCodeType secretCodeType = SecretCodeType.letters, - }) async { - int ram = SysInfo.getTotalPhysicalMemory(); - - final completer = Completer>(); - final sendPort = singleCompletePort, List>(completer, - callback: _handleErrList); - native.change_dewif_secret_code( - sendPort.nativePort, - // utf8.encoder(dewif), - StringUtf8Pointer(dewif).toNativeUtf8(), - StringUtf8Pointer(oldPin).toNativeUtf8(), - 0, - secretCodeType.index, - ram, - ); - List newWallet = await completer.future; - - return Future.value(NewWallet._(newWallet[0], newWallet[1])); - } - - /// Check validity of a base58 public key with its checksum - static Future checkPublicKey({String pubkey}) { - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErrVoid); - native.check_pubkey( - sendPort.nativePort, - StringUtf8Pointer(pubkey).toNativeUtf8(), - ); - return completer.future; - } - - /// Compute public key checksum - static Future computeChecksum({String pubkey}) { - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErr); - native.compute_checksum( - sendPort.nativePort, - StringUtf8Pointer(pubkey).toNativeUtf8(), - ); - return completer.future; - } - - /// Generate a random mnemonic - static Future genMnemonic({Language language = Language.english}) { - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErr); - native.gen_mnemonic( - sendPort.nativePort, - language.index, - ); - return completer.future; - } - - /// Generate a wallet from a deprecated salt + password couple. - /// - /// This deprecated method must be used only for compatibility purpose ! - static Future genWalletFromDeprecatedSaltPassword({ - String currency = "g1", - String salt, - String password, - SecretCodeType secretCodeType = SecretCodeType.letters, - bool isMember = false, - }) async { - int ram = SysInfo.getTotalPhysicalMemory(); - print('ram=$ram'); - - final completer = Completer>(); - final sendPort = singleCompletePort, List>(completer, - callback: _handleErrList); - native.gen_dewif_from_legacy( - sendPort.nativePort, - StringUtf8Pointer(currency).toNativeUtf8(), - StringUtf8Pointer(salt).toNativeUtf8(), - StringUtf8Pointer(password).toNativeUtf8(), - isMember ? 1 : 0, - secretCodeType.index, - ram, - ); - List newWallet = await completer.future; - - return Future.value(NewWallet._(newWallet[0], newWallet[1])); - } - - /// Generate a wallet from a mnemonic phrase. - /// - /// If the mnemonic is not in English, you must indicate the language of - /// the mnemonic (necessary for the verification of its validity). - /// - /// If the wallet to be generated is not dedicated to the Ğ1 currency, you - /// must indicate the currency for which this wallet will be used. - static Future genWalletFromMnemonic({ - String currency = "g1", - Language language = Language.english, - String mnemonic, - SecretCodeType secretCodeType = SecretCodeType.letters, - }) async { - int ram = SysInfo.getTotalPhysicalMemory(); - print('ram=$ram'); - - final completer = Completer>(); - final sendPort = singleCompletePort, List>(completer, - callback: _handleErrList); - native.gen_dewif( - sendPort.nativePort, - StringUtf8Pointer(currency).toNativeUtf8(), - language.index, - StringUtf8Pointer(mnemonic).toNativeUtf8(), - 0, - secretCodeType.index, - ram, - ); - List newWallet = await completer.future; - - return Future.value(NewWallet._(newWallet[0], newWallet[1])); - } - - /// Get next external public key of a specific opaque account - static Future getOpaqueAccountNextExternalPublicKey( - {int accountIndex}) async { - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErr); - native.get_opaque_account_next_external_address( - sendPort.nativePort, accountIndex.toUnsigned(31)); - return completer.future; - } - - /// Get BIP32 accounts public keys (in base 58) of `dewif` master keypair. - static Future> getBip32DewifAccountsPublicKeys( - {String currency = "g1", - String dewif, - String secretCode, - List accountsIndex}) async { - final completer = Completer>(); - final sendPort = singleCompletePort, List>(completer, - callback: _handleErrList); - native.get_bip32_dewif_accounts_pubkeys( - sendPort.nativePort, - StringUtf8Pointer(currency).toNativeUtf8(), - StringUtf8Pointer(dewif).toNativeUtf8(), - StringUtf8Pointer(secretCode).toNativeUtf8(), - accountsIndex.length, - _listIntToPtrUint32(accountsIndex)); - return completer.future; - } - - /// Get mnemonic phrase of `dewif` (algo Bip32-Ed25519 only). - static Future getBip32DewifMnemonic( - {String currency = "g1", String dewif, String secretCode}) async { - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErr); - native.get_bip32_dewif_mnemonic( - sendPort.nativePort, - StringUtf8Pointer(currency).toNativeUtf8(), - StringUtf8Pointer(dewif).toNativeUtf8(), - StringUtf8Pointer(secretCode).toNativeUtf8(), - ); - return completer.future; - } - - /// Get `dewif` keypair meta data. - static Future getDewifMetaData( - {String dewif, - SecretCodeType secretCodeType = SecretCodeType.letters}) async { - final completer = Completer>(); - final sendPort = singleCompletePort, List>(completer, - callback: _handleErrList); - native.get_dewif_meta(sendPort.nativePort, - StringUtf8Pointer(dewif).toNativeUtf8(), 0, secretCodeType.index); - List dewifMetaData = await completer.future; - - return Future.value(DewifMetaData._(dewifMetaData[0], - int.parse(dewifMetaData[1]), int.parse(dewifMetaData[2]))); - } - - /// Get public key (in base 58) of `dewif` keypair. - static Future getDewifPublicKey( - {int accountIndexOpt, - int addressIndexOpt, - String currency = "g1", - String dewif, - bool externalOpt, - String pin}) async { - var externalOptInt = -1; - if (externalOpt != null) { - externalOptInt = externalOpt ? 1 : 0; - } - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErr); - native.get_dewif_pubkey( - sendPort.nativePort, - accountIndexOpt ?? -1, - addressIndexOpt ?? -1, - StringUtf8Pointer(currency).toNativeUtf8(), - StringUtf8Pointer(dewif).toNativeUtf8(), - externalOptInt, - StringUtf8Pointer(pin).toNativeUtf8(), - ); - return completer.future; - } - - /// Get secret code length of `dewif` keypair. - static int getDewifSecretCodeLen( - {String currency = "g1", - String dewif, - SecretCodeType secretCodeType = SecretCodeType.letters}) { - int res = native.get_dewif_secret_code_len( - StringUtf8Pointer(dewif).toNativeUtf8(), - 0, - secretCodeType.index, - ); - if (res == -1) { - print('DUBP_RS_ERROR: DEWIF file content is corrupted.'); - throw 'DUBP_RS_ERROR: DEWIF file content is corrupted.'; - } else { - return res; - } - } - - /// Get public key (in base 58) of legacy wallet (password + salt) - /// - /// This deprecated method must be used only for compatibility purpose ! - static Future getLegacyPublicKey({String password, String salt}) { - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErr); - native.get_legacy_pubkey( - sendPort.nativePort, - StringUtf8Pointer(salt).toNativeUtf8(), - StringUtf8Pointer(password).toNativeUtf8(), - ); - return completer.future; - } - - /// Load opaque accounts - static Future loadOpaqueAccounts( - List accountsIndex, - String currency, - String dewif, - String secretCode, - ) { - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErrVoid); - native.load_opaque_bip32_accounts( - sendPort.nativePort, - accountsIndex.length, - _listIntToPtrUint32(accountsIndex), - StringUtf8Pointer(currency).toNativeUtf8(), - StringUtf8Pointer(dewif).toNativeUtf8(), - StringUtf8Pointer(secretCode).toNativeUtf8()); - return completer.future; - } - - /// Sign the message `message` with `dewif` keypair encryted - /// in DEWIF format. - /// - /// If you have several messages to sign, use `signSeveral` - /// method instead. - static Future sign( - {int accountIndexOpt, - int addressIndexOpt, - String currency = "g1", - String dewif, - bool externalOpt, - String secretCode, - String message}) { - var externalOptInt = -1; - if (externalOpt != null) { - externalOptInt = externalOpt ? 1 : 0; - } - - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErr); - native.sign( - sendPort.nativePort, - accountIndexOpt ?? -1, - addressIndexOpt ?? -1, - StringUtf8Pointer(currency).toNativeUtf8(), - StringUtf8Pointer(dewif).toNativeUtf8(), - externalOptInt, - StringUtf8Pointer(secretCode).toNativeUtf8(), - StringUtf8Pointer(message).toNativeUtf8(), - ); - return completer.future; - } - - /// Sign several messages `messages` with `dewif` keypair encryted in DEWIF - /// format. - /// - /// This method is optimized to sign several messages at once. If you have - /// several messages to sign, avoid calling the `sign` method for each - /// message. Use this `signSeveral` method instead. - static Future> signSeveral( - {int accountIndexOpt, - int addressIndexOpt, - String currency = "g1", - String dewif, - bool externalOpt, - String secretCode, - List messages}) { - var externalOptInt = -1; - if (externalOpt != null) { - externalOptInt = externalOpt ? 1 : 0; - } - - final completer = Completer>(); - final sendPort = singleCompletePort, List>(completer, - callback: _handleErrList); - - native.sign_several( - sendPort.nativePort, - accountIndexOpt ?? -1, - addressIndexOpt ?? -1, - StringUtf8Pointer(currency).toNativeUtf8(), - StringUtf8Pointer(dewif).toNativeUtf8(), - externalOptInt, - StringUtf8Pointer(secretCode).toNativeUtf8(), - messages.length, - _listStringToPtr(messages), - ); - - return completer.future; - } - - /// Make a simple payment from a transparent account - static Future simplePaymentFromTransparentAccount( - {int accountIndex, - double amount, - String currency = "g1", - String dewif, - String gvaEndpoint, - String recipient, - String secretCode, - String txComment}) { - final completer = Completer(); - final sendPort = - singleCompletePort(completer, callback: _handleErrVoid); - - native.simple_payment_bip32( - sendPort.nativePort, - accountIndex, - amount, - StringUtf8Pointer(currency).toNativeUtf8(), - StringUtf8Pointer(dewif).toNativeUtf8(), - StringUtf8Pointer(gvaEndpoint).toNativeUtf8(), - StringUtf8Pointer(recipient).toNativeUtf8(), - StringUtf8Pointer(secretCode).toNativeUtf8(), - StringUtf8Pointer(txComment).toNativeUtf8(), - ); - - return completer.future; - } - - static Pointer _listIntToPtrUint32(List list) { - final listUint32 = list.map((i) => i.toUnsigned(31)).toList(); - final Pointer ptr = malloc.allocate(listUint32.length); - for (var i = 0; i < listUint32.length; i++) { - ptr[i] = listUint32[i]; - } - return ptr; - } - - static Pointer> _listStringToPtr(List list) { - final listUtf8 = - list.map((s) => StringUtf8Pointer(s).toNativeUtf8()).toList(); - final Pointer> ptr = malloc.allocate(listUtf8.length); - for (var i = 0; i < listUtf8.length; i++) { - ptr[i] = listUtf8[i]; - } - return ptr; - } - - static String _handleErr(String res) { - if (res.startsWith('DUBP_RS_ERROR: ')) { - final error = res; - print(error); - throw error; - } else { - return res; - } - } - - static List _handleErrList(List res) { - final List arr = res.cast(); - if (arr.isNotEmpty && arr[0].startsWith('DUBP_RS_ERROR: ')) { - final error = arr[0]; - print(error); - throw error; - } else { - return arr; - } - } - - static void _handleErrVoid(String res) { - if (res.startsWith('DUBP_RS_ERROR: ')) { - final error = res; - print(error); - throw error; - } - } - - /*static int _handleErrInt(String res) { - if (res.startsWith('DUBP_RS_ERROR: ')) { - final error = res; - print(error); - throw error; - } else { - return int.parse(res); - } - }*/ -} diff --git a/packages/dubp_rs/pubspec.lock b/packages/dubp_rs/pubspec.lock deleted file mode 100644 index e6f0b3d..0000000 --- a/packages/dubp_rs/pubspec.lock +++ /dev/null @@ -1,189 +0,0 @@ -# Generated by pub -# See https://dart.dev/tools/pub/glossary#lockfile -packages: - async: - dependency: transitive - description: - name: async - url: "https://pub.dartlang.org" - source: hosted - version: "2.8.1" - boolean_selector: - dependency: transitive - description: - name: boolean_selector - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.0" - characters: - dependency: transitive - description: - name: characters - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - charcode: - dependency: transitive - description: - name: charcode - url: "https://pub.dartlang.org" - source: hosted - version: "1.3.1" - clock: - dependency: transitive - description: - name: clock - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - collection: - dependency: transitive - description: - name: collection - url: "https://pub.dartlang.org" - source: hosted - version: "1.15.0" - effective_dart: - dependency: "direct dev" - description: - name: effective_dart - url: "https://pub.dartlang.org" - source: hosted - version: "1.3.1" - fake_async: - dependency: transitive - description: - name: fake_async - url: "https://pub.dartlang.org" - source: hosted - version: "1.2.0" - ffi: - dependency: "direct main" - description: - name: ffi - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" - file_utils: - dependency: transitive - description: - name: file_utils - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" - flutter: - dependency: "direct main" - description: flutter - source: sdk - version: "0.0.0" - flutter_test: - dependency: "direct dev" - description: flutter - source: sdk - version: "0.0.0" - globbing: - dependency: transitive - description: - name: globbing - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" - isolate: - dependency: "direct main" - description: - name: isolate - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.3" - matcher: - dependency: transitive - description: - name: matcher - url: "https://pub.dartlang.org" - source: hosted - version: "0.12.10" - meta: - dependency: transitive - description: - name: meta - url: "https://pub.dartlang.org" - source: hosted - version: "1.7.0" - path: - dependency: transitive - description: - name: path - url: "https://pub.dartlang.org" - source: hosted - version: "1.8.0" - sky_engine: - dependency: transitive - description: flutter - source: sdk - version: "0.0.99" - source_span: - dependency: transitive - description: - name: source_span - url: "https://pub.dartlang.org" - source: hosted - version: "1.8.1" - stack_trace: - dependency: transitive - description: - name: stack_trace - url: "https://pub.dartlang.org" - source: hosted - version: "1.10.0" - stream_channel: - dependency: transitive - description: - name: stream_channel - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.0" - string_scanner: - dependency: transitive - description: - name: string_scanner - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - system_info: - dependency: "direct main" - description: - name: system_info - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" - term_glyph: - dependency: transitive - description: - name: term_glyph - url: "https://pub.dartlang.org" - source: hosted - version: "1.2.0" - test_api: - dependency: transitive - description: - name: test_api - url: "https://pub.dartlang.org" - source: hosted - version: "0.4.2" - typed_data: - dependency: transitive - description: - name: typed_data - url: "https://pub.dartlang.org" - source: hosted - version: "1.3.0" - vector_math: - dependency: transitive - description: - name: vector_math - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.0" -sdks: - dart: ">=2.12.0 <3.0.0" - flutter: ">=1.10.0" diff --git a/packages/dubp_rs/pubspec.yaml b/packages/dubp_rs/pubspec.yaml deleted file mode 100644 index bd3f658..0000000 --- a/packages/dubp_rs/pubspec.yaml +++ /dev/null @@ -1,28 +0,0 @@ -name: dubp -description: dubp-rs-libs binding for flutter. -version: 0.0.1 - -environment: - sdk: '>=2.7.0 <3.0.0' - flutter: '>=1.10.0' - -dependencies: - flutter: - sdk: flutter - ffi: ^1.0.0 - isolate: ^2.0.3 - system_info: ^1.0.0 - -dev_dependencies: - effective_dart: ^1.3.1 - flutter_test: - sdk: flutter - -flutter: - plugin: - platforms: - android: - package: com.example.dubp - pluginClass: DubpPlugin - ios: - pluginClass: DubpPlugin diff --git a/pubspec.lock b/pubspec.lock index 92ac05a..c082479 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -50,6 +50,20 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.1.0" + bip32_ed25519: + dependency: transitive + description: + name: bip32_ed25519 + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.1" + bip39_multi_nullsafety: + dependency: transitive + description: + name: bip39_multi_nullsafety + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.7" boolean_selector: dependency: transitive description: @@ -267,6 +281,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "0.5.6" + desktop_window: + dependency: "direct main" + description: + name: desktop_window + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.0" dio: dependency: "direct main" description: @@ -274,13 +295,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "4.0.4" - dubp: + durt: dependency: "direct main" description: - path: "packages/dubp_rs" - relative: true - source: path - version: "0.0.1" + name: durt + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.6" fake_async: dependency: transitive description: @@ -309,13 +330,6 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "6.1.2" - file_utils: - dependency: transitive - description: - name: file_utils - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.1" fixnum: dependency: transitive description: @@ -397,13 +411,6 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.0.2" - globbing: - dependency: transitive - description: - name: globbing - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" gql: dependency: transitive description: @@ -474,6 +481,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.1.0" + hex: + dependency: transitive + description: + name: hex + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.0" hive: dependency: "direct main" description: @@ -577,13 +591,6 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.0.3" - isolate: - dependency: transitive - description: - name: isolate - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.1" jdenticon_dart: dependency: "direct main" description: @@ -689,15 +696,8 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.0.2" - package_info: - dependency: "direct main" - description: - name: package_info - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.2" package_info_plus: - dependency: transitive + dependency: "direct main" description: name: package_info_plus url: "https://pub.dartlang.org" @@ -814,7 +814,7 @@ packages: name: permission_handler url: "https://pub.dartlang.org" source: hosted - version: "8.1.6" + version: "8.3.0" permission_handler_platform_interface: dependency: transitive description: @@ -836,6 +836,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "7.3.0" + pinenacl: + dependency: transitive + description: + name: pinenacl + url: "https://pub.dartlang.org" + source: hosted + version: "0.3.3" platform: dependency: transitive description: @@ -850,6 +857,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.0.2" + pointycastle: + dependency: transitive + description: + name: pointycastle + url: "https://pub.dartlang.org" + source: hosted + version: "3.4.0" pool: dependency: transitive description: @@ -906,6 +920,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.1.0" + qr_flutter: + dependency: "direct main" + description: + name: qr_flutter + url: "https://pub.dartlang.org" + source: hosted + version: "4.0.0" qrscan: dependency: "direct main" description: @@ -1107,13 +1128,6 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "0.3.0" - system_info: - dependency: transitive - description: - name: system_info - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.1" term_glyph: dependency: transitive description: @@ -1226,6 +1240,15 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.2.10" + window_size: + dependency: "direct main" + description: + path: "plugins/window_size" + ref: HEAD + resolved-ref: "03d957e8b5c99fc83cd4a781031b154ab3de8753" + url: "git://github.com/google/flutter-desktop-embedding.git" + source: git + version: "0.1.0" xdg_directories: dependency: transitive description: @@ -1248,5 +1271,5 @@ packages: source: hosted version: "3.1.0" sdks: - dart: ">=2.14.0 <3.0.0" + dart: ">=2.14.4 <3.0.0" flutter: ">=2.5.0" diff --git a/pubspec.yaml b/pubspec.yaml index 76e9a95..4da36af 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -5,24 +5,26 @@ description: Pay with G1. # pub.dev using `pub publish`. This is preferred for private packages. publish_to: 'none' # Remove this line if you wish to publish to pub.dev -version: 0.0.3+14 +version: 0.0.4+8 environment: - sdk: ">=2.7.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' -dependencies: +dependencies: + flutter: + sdk: flutter + flutter_driver: + sdk: flutter + window_size: + git: + url: git://github.com/google/flutter-desktop-embedding.git + path: plugins/window_size assorted_layout_widgets: ^5.2.1 bubble: ^1.2.1 carousel_slider: ^4.0.0 confirm_dialog: ^1.0.0 crypto: ^3.0.1 - dubp: - path: packages/dubp_rs fast_base58: ^0.2.0 - flutter: - sdk: flutter - flutter_driver: - sdk: flutter flutter_launcher_icons: ^0.9.2 flutter_lints: ^1.0.4 flutter_logs: ^2.1.4 @@ -37,14 +39,15 @@ dependencies: intl: ^0.17.0 jdenticon_dart: ^2.0.0 logger: ^1.1.0 - package_info: ^2.0.2 path_provider: ^2.0.3 pdf: ^3.5.0 - permission_handler: 8.1.6 + permission_handler: ^8.3.0 pin_code_fields: ^7.3.0 printing: ^5.6.0 provider: ^6.0.1 qrscan: ^0.3.2 + # qr_code_scanner: ^0.6.1 + qr_flutter: ^4.0.0 responsive_builder: ^0.4.1 responsive_framework: ^0.1.4 sentry: ^6.0.0 @@ -58,6 +61,9 @@ dependencies: xml: ^5.3.0 pull_to_refresh: ^2.0.0 dio: ^4.0.4 + desktop_window: ^0.4.0 + durt: ^0.1.6 + package_info_plus: ^1.3.0 flutter_icons: android: "ic_launcher" diff --git a/scripts/build-apk.sh b/scripts/build-apk.sh index 368a81e..3313821 100755 --- a/scripts/build-apk.sh +++ b/scripts/build-apk.sh @@ -13,8 +13,6 @@ echo "Nom du build final: ${APPNAME}-${VERSION}+${BUILD}.apk" ## To build Rust dependancies # cargo br -echo "To compile Rust binding, exec: cargo br" - flutter clean if [[ $1 == "bundle" ]]; then flutter build appbundle --release --target-platform android-arm,android-arm64 --build-name $VERSION --build-number $BUILD diff --git a/scripts/build-rust.sh b/scripts/build-rust.sh deleted file mode 100755 index bfacd8c..0000000 --- a/scripts/build-rust.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash - -set -e - -MY_PATH="`dirname \"$0\"`" -MY_PATH="`( cd \"$MY_PATH\" && pwd )`" - -cd $MY_PATH/.. - -cargo bd -cargo make android-dev -cargo br - -echo -e "\nRust dependencies have been successfully build !" diff --git a/test_driver/app_test.dart b/test_driver/app_test.dart index 0efe479..ce2e990 100644 --- a/test_driver/app_test.dart +++ b/test_driver/app_test.dart @@ -15,19 +15,19 @@ void main() { final manageWalletsFinder = find.byValueKey('manageWallets'); // final buttonFinder = find.byValueKey('increment'); - FlutterDriver driver; - String pinCode; + FlutterDriver? driver; + String? pinCode; // Connect to the Flutter driver before running any tests. setUpAll(() async { driver = await FlutterDriver.connect(); - await driver.waitUntilFirstFrameRasterized(); + await driver!.waitUntilFirstFrameRasterized(); }); // Close the connection to the driver after the tests have completed. tearDownAll(() async { if (driver != null) { - driver.close(); + driver!.close(); } }); @@ -35,12 +35,12 @@ void main() { // Function to tap the widget by key Future tapOn(String key) async { - await driver.tap(find.byValueKey(key)); + await driver!.tap(find.byValueKey(key)); } // Easy get text Future getText(String text) async { - return await driver.getText(find.byValueKey( + return await driver!.getText(find.byValueKey( text, )); } @@ -63,7 +63,7 @@ void main() { Future isPresent(SerializableFinder byValueKey, {Duration timeout = const Duration(seconds: 1)}) async { try { - await driver.waitFor(byValueKey, timeout: timeout); + await driver!.waitFor(byValueKey, timeout: timeout); return true; } catch (exception) { return false; @@ -97,7 +97,7 @@ void main() { } // Fast creation of new Keychain - Future createNewKeychain(String name) async { + Future createNewKeychain(String name) async { await tapOn('drawerMenu'); await sleep(300); await tapOn('parameters'); @@ -110,9 +110,9 @@ void main() { pinCode = await getText('generatedPin'); await tapOn('storeKeychain'); await sleep(100); - await driver.enterText('triche'); + await driver!.enterText('triche'); await tapOn('walletName'); - await driver.enterText(name); + await driver!.enterText(name); await sleep(50); await tapOn('confirmStorage'); await sleep(300); @@ -124,7 +124,7 @@ void main() { test('OnBoarding - Open wallets management', ( {timeout = Timeout.none}) async { // await driver.runUnsynchronized(() async { // Needed if we want to manage async drivers - await driver.tap(manageWalletsFinder); + await driver!.tap(manageWalletsFinder); // If a wallet exist, go to delete theme all if (!await isPresent(find.byValueKey('goStep1'))) { @@ -132,7 +132,7 @@ void main() { await deleteAllWallets(); - await driver.tap(manageWalletsFinder); + await driver!.tap(manageWalletsFinder); } // Get the SerializableFinder for text widget with key 'textOnboarding' @@ -143,7 +143,7 @@ void main() { await sleep(100); // Verify onboarding is starting, with text - expect(await driver.getText(textOnboarding), + expect(await driver!.getText(textOnboarding), "Je ne connais pour l’instant aucun de vos portefeuilles.\n\nVous pouvez en créer un nouveau, ou bien importer un portefeuille Cesium existant."); }); @@ -157,7 +157,7 @@ void main() { await tapOn('goStep6'); expect( - await driver.getText(find.byValueKey( + await driver!.getText(find.byValueKey( 'step6', )), "J’ai généré votre phrase de restauration !\nTâchez de la garder bien secrète, car elle permet à quiconque la connaît d’accéder à tous vos portefeuilles."); @@ -189,10 +189,10 @@ void main() { )]; // Enter the expected word - await driver.enterText(goodWord); + await driver!.enterText(goodWord); // Check if word is valid - await driver.waitFor(find.text("C'est le bon mot !")); + await driver!.waitFor(find.text("C'est le bon mot !")); // Continue onboarding workflow await tapOn('goStep9'); @@ -245,7 +245,7 @@ void main() { // await tapOn('formKey2'); //Enter good secret code - await driver.enterText(pinCode); + await driver!.enterText(pinCode!); expect(await getText('step13'), "Top !\n\nVotre trousseau de clef et votre portefeuille ont été créés avec un immense succès.\n\nFélicitations !"); @@ -259,29 +259,29 @@ void main() { await sleep(300); // Go to first derivation and rename it - await driver.tap(find.text('Mon portefeuille courant')); + await driver!.tap(find.text('Mon portefeuille courant')); await sleep(300); await tapOn('renameWallet'); await sleep(100); await tapOn('walletName'); await sleep(100); - await driver.enterText('Renommage wallet 1'); + await driver!.enterText('Renommage wallet 1'); await sleep(300); await tapOn('renameWallet'); await sleep(400); - await driver.waitFor(find.text('Renommage wallet 1'), timeout: timeout); + await driver!.waitFor(find.text('Renommage wallet 1'), timeout: timeout); // expect(await getText('walletName'), "Renommage wallet 1"); await goBack(); }); test('My wallets - Create a derivations, open thems, tap all buttons', ( {timeout = const Duration(seconds: 2)}) async { - await driver.waitFor(find.text('Renommage wallet 1'), timeout: timeout); + await driver!.waitFor(find.text('Renommage wallet 1'), timeout: timeout); // Add a second derivation await createDerivation(); // Go to second derivation options - await driver.tap(find.text('Portefeuille 2')); + await driver!.tap(find.text('Portefeuille 2')); await sleep(100); // Test options @@ -297,7 +297,7 @@ void main() { await tapOn('setDefaultWallet'); await sleep(50); await tapOn('copyPubkey'); - await driver.waitFor(find + await driver!.waitFor(find .text('Cette clé publique a été copié dans votre presse-papier.')); await goBack(); @@ -309,7 +309,7 @@ void main() { await sleep(50); // Go to third derivation options - await driver.tap(find.text('Portefeuille 3')); + await driver!.tap(find.text('Portefeuille 3')); await sleep(100); await tapOn('displayBalance'); @@ -320,7 +320,7 @@ void main() { test('My wallets - Extra tests', ( {timeout = const Duration(seconds: 2)}) async { // Add derivation 5,6 and 7 - await driver.waitFor(find.text('Portefeuille 4'), timeout: timeout); + await driver!.waitFor(find.text('Portefeuille 4'), timeout: timeout); await createDerivation(); await createDerivation(); await createDerivation(); @@ -331,27 +331,27 @@ void main() { await tapOn('manageWallets'); await sleep(200); //Enter secret code - await driver.enterText(pinCode); + await driver!.enterText(pinCode!); await sleep(200); // Go to derivation 6 and delete it - await driver.tap(find.text('Portefeuille 6')); + await driver!.tap(find.text('Portefeuille 6')); await sleep(100); await deleteWallet(true); // Go to 2nd derivation and check if it's de default - await driver.tap(find.text('Portefeuille 2')); - await driver.waitFor(find.text('Ce portefeuille est celui par defaut')); + await driver!.tap(find.text('Portefeuille 2')); + await driver!.waitFor(find.text('Ce portefeuille est celui par defaut')); await tapOn('setDefaultWallet'); await sleep(100); - await driver.waitFor(find.text('Ce portefeuille est celui par defaut')); + await driver!.waitFor(find.text('Ce portefeuille est celui par defaut')); await sleep(300); // Display history, copy pubkey, go back and rename wallet name await tapOn('displayHistory'); await sleep(400); await tapOn('copyPubkey'); - await driver.waitFor(find + await driver!.waitFor(find .text('Cette clé publique a été copié dans votre presse-papier.')); await sleep(800); await goBack(); @@ -360,70 +360,70 @@ void main() { await sleep(100); await tapOn('walletName'); await sleep(100); - await driver.enterText('Renommage wallet 2'); + await driver!.enterText('Renommage wallet 2'); await sleep(300); await tapOn('renameWallet'); await sleep(400); await goBack(); - await driver.waitFor(find.text('Renommage wallet 2')); - await driver.scrollIntoView(find.text('+')); + await driver!.waitFor(find.text('Renommage wallet 2')); + await driver!.scrollIntoView(find.text('+')); await createDerivation(); await createDerivation(); - await driver.scrollIntoView(find.text('+')); + await driver!.scrollIntoView(find.text('+')); await createDerivation(); await createDerivation(); - await driver.scrollIntoView(find.text('+')); + await driver!.scrollIntoView(find.text('+')); await createDerivation(); await createDerivation(); - await driver.scrollIntoView(find.text('+')); + await driver!.scrollIntoView(find.text('+')); await createDerivation(); await createDerivation(); - await driver.scrollIntoView(find.text('+')); + await driver!.scrollIntoView(find.text('+')); await createDerivation(); await createDerivation(); - await driver.scrollIntoView(find.text('+')); + await driver!.scrollIntoView(find.text('+')); await createDerivation(); await createDerivation(); - await driver.scrollIntoView(find.text('+')); + await driver!.scrollIntoView(find.text('+')); await createDerivation(); await sleep(400); // Scroll the wallet screen until Derivation 20 and open it - await driver.scrollUntilVisible( + await driver!.scrollUntilVisible( find.byValueKey('listWallets'), find.text('Portefeuille 20'), dyScroll: -300.0, ); - await driver.waitFor(find.text('Portefeuille 20')); + await driver!.waitFor(find.text('Portefeuille 20')); await sleep(400); - await driver.tap(find.text('Portefeuille 20')); + await driver!.tap(find.text('Portefeuille 20')); await tapOn('copyPubkey'); }); test('Search - Search Pi profile, navigate in history transactions', ( {timeout = const Duration(seconds: 2)}) async { - await driver.waitFor(find.text('Portefeuille 20'), timeout: timeout); + await driver!.waitFor(find.text('Portefeuille 20'), timeout: timeout); await goBack(); await goBack(); await sleep(200); await tapOn('searchIcon'); await sleep(400); - await driver.enterText('D2meevcAHFTS2gQMvmRW5Hzi25jDdikk4nC4u1FkwRaU'); + await driver!.enterText('D2meevcAHFTS2gQMvmRW5Hzi25jDdikk4nC4u1FkwRaU'); await sleep(100); await tapOn('copyPubkey'); await sleep(500); await tapOn('switchPayHistory'); await sleep(1200); // await driver.scrollIntoView(find.byValueKey('listTransactions')); - await driver.scrollUntilVisible( + await driver!.scrollUntilVisible( find.byValueKey('listTransactions'), find.byValueKey('transaction35'), dyScroll: -600.0, ); await sleep(100); await tapOn('transaction33'); - await driver.waitFor(find.text('Commentaire:')); + await driver!.waitFor(find.text('Commentaire:')); // Want to paste pubkey copied, but doesn't work actualy with flutter driver: https://github.com/flutter/flutter/issues/47448 // final ClipboardData pubkeyCopied = @@ -435,19 +435,19 @@ void main() { test('Wallet generation - Fast wallets generations', ( {timeout = const Duration(seconds: 2)}) async { - await driver.waitFor(find.text('Commentaire:'), timeout: timeout); + await driver!.waitFor(find.text('Commentaire:'), timeout: timeout); await goBack(); await goBack(); await deleteAllWallets(); await sleep(100); - final String pincode = await createNewKeychain('Fast wallet'); + final String? pincode = await (createNewKeychain('Fast wallet')); await sleep(200); - await driver.enterText(pincode); + await driver!.enterText(pincode!); await sleep(100); await createDerivation(); await sleep(100); - await driver.tap(find.text('Fast wallet')); - await driver.waitFor(find.text('Fast wallet')); + await driver!.tap(find.text('Fast wallet')); + await driver!.waitFor(find.text('Fast wallet')); // Wait 3 seconds at the end await sleep(3000); });