From 20f3abf07435759b6a3aa111ac4909c6bc4de0a9 Mon Sep 17 00:00:00 2001 From: Mathieu Baudet Date: Fri, 3 Apr 2020 16:05:58 -0700 Subject: [PATCH] initial commit remove deprecated comments for markdown generation update README fix licence line in python files clean up .pyc file Rename Libra into Primary update cargo dependencies (except ed25519-dalek and rand) Tiny cleanups / wart-removal Removing env_logger from fastpay_core Removing log from fastpay_core Update version dependencies Also introduces a workaround to https://github.com/dalek-cryptography/ed25519-dalek/issues/126 (see workspace Cargo.toml) Update license --- .assets/calibra.png | Bin 0 -> 31754 bytes .gitignore | 13 + CODE_OF_CONDUCT.md | 5 + CONTRIBUTING.md | 46 + Cargo.lock | 960 ++++++++++++++++++ Cargo.toml | 22 + LICENSE | 201 ++++ LICENSE-docs | 384 +++++++ README.md | 78 ++ rust/fastpay/Cargo.toml | 32 + rust/fastpay/src/bench.rs | 336 ++++++ rust/fastpay/src/client.rs | 545 ++++++++++ rust/fastpay/src/config.rs | 215 ++++ rust/fastpay/src/lib.rs | 12 + rust/fastpay/src/network.rs | 463 +++++++++ rust/fastpay/src/server.rs | 243 +++++ rust/fastpay/src/transport.rs | 376 +++++++ .../fastpay/src/unit_tests/transport_tests.rs | 93 ++ rust/fastpay_core/Cargo.toml | 16 + rust/fastpay_core/src/authority.rs | 379 +++++++ rust/fastpay_core/src/base_types.rs | 371 +++++++ rust/fastpay_core/src/client.rs | 692 +++++++++++++ rust/fastpay_core/src/committee.rs | 54 + rust/fastpay_core/src/downloader.rs | 167 +++ rust/fastpay_core/src/error.rs | 99 ++ .../src/fastpay_smart_contract.rs | 114 +++ rust/fastpay_core/src/lib.rs | 24 + rust/fastpay_core/src/messages.rs | 332 ++++++ rust/fastpay_core/src/serialize.rs | 121 +++ .../src/unit_tests/authority_tests.rs | 516 ++++++++++ .../src/unit_tests/base_types_tests.rs | 21 + .../src/unit_tests/client_tests.rs | 420 ++++++++ .../src/unit_tests/downloader_tests.rs | 44 + .../fastpay_smart_contract_tests.rs | 180 ++++ .../src/unit_tests/messages_tests.rs | 84 ++ .../src/unit_tests/serialize_tests.rs | 338 ++++++ rust/rust-toolchain | 1 + .../aggregated_latency_log.txt | 1 + ...set - x-1000000-z-4-aggregated_tps_log.txt | 1 + .../x-1000000-z-4-aggregated_tps_log.txt | 1 + .../x-z-1000-4-aggregated_tps_log.txt | 1 + .../z-1000000-1000-x-aggregated_tps_log.txt | 1 + scripts/aggregated_tps_log.txt | 1 + scripts/aws_plot.py | 89 ++ scripts/bench.sh | 68 ++ scripts/fabfile.py | 433 ++++++++ scripts/latency.py | 122 +++ scripts/latency_with_crash.py | 44 + scripts/microbenchmark.py | 28 + scripts/throughput.py | 198 ++++ 50 files changed, 8985 insertions(+) create mode 100644 .assets/calibra.png create mode 100644 .gitignore create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 LICENSE-docs create mode 100644 README.md create mode 100644 rust/fastpay/Cargo.toml create mode 100644 rust/fastpay/src/bench.rs create mode 100644 rust/fastpay/src/client.rs create mode 100644 rust/fastpay/src/config.rs create mode 100644 rust/fastpay/src/lib.rs create mode 100644 rust/fastpay/src/network.rs create mode 100644 rust/fastpay/src/server.rs create mode 100644 rust/fastpay/src/transport.rs create mode 100644 rust/fastpay/src/unit_tests/transport_tests.rs create mode 100644 rust/fastpay_core/Cargo.toml create mode 100644 rust/fastpay_core/src/authority.rs create mode 100644 rust/fastpay_core/src/base_types.rs create mode 100644 rust/fastpay_core/src/client.rs create mode 100644 rust/fastpay_core/src/committee.rs create mode 100644 rust/fastpay_core/src/downloader.rs create mode 100644 rust/fastpay_core/src/error.rs create mode 100644 rust/fastpay_core/src/fastpay_smart_contract.rs create mode 100644 rust/fastpay_core/src/lib.rs create mode 100644 rust/fastpay_core/src/messages.rs create mode 100644 rust/fastpay_core/src/serialize.rs create mode 100644 rust/fastpay_core/src/unit_tests/authority_tests.rs create mode 100644 rust/fastpay_core/src/unit_tests/base_types_tests.rs create mode 100644 rust/fastpay_core/src/unit_tests/client_tests.rs create mode 100644 rust/fastpay_core/src/unit_tests/downloader_tests.rs create mode 100644 rust/fastpay_core/src/unit_tests/fastpay_smart_contract_tests.rs create mode 100644 rust/fastpay_core/src/unit_tests/messages_tests.rs create mode 100644 rust/fastpay_core/src/unit_tests/serialize_tests.rs create mode 100644 rust/rust-toolchain create mode 100644 scripts/aggregated_parsed_logs/aggregated_latency_log.txt create mode 100644 scripts/aggregated_parsed_logs/taskset - x-1000000-z-4-aggregated_tps_log.txt create mode 100644 scripts/aggregated_parsed_logs/x-1000000-z-4-aggregated_tps_log.txt create mode 100644 scripts/aggregated_parsed_logs/x-z-1000-4-aggregated_tps_log.txt create mode 100644 scripts/aggregated_parsed_logs/z-1000000-1000-x-aggregated_tps_log.txt create mode 100644 scripts/aggregated_tps_log.txt create mode 100644 scripts/aws_plot.py create mode 100755 scripts/bench.sh create mode 100644 scripts/fabfile.py create mode 100644 scripts/latency.py create mode 100644 scripts/latency_with_crash.py create mode 100644 scripts/microbenchmark.py create mode 100644 scripts/throughput.py diff --git a/.assets/calibra.png b/.assets/calibra.png new file mode 100644 index 0000000000000000000000000000000000000000..258bf2796fd088ec354ec7fb366270fd2d536ddb GIT binary patch literal 31754 zcmeFZ_g~Wg*FTP?shQc-%1kRq=E{+j1I==$mYM@xWoEd@+zYgwJ7-QBj?6s}H#XGV zhI@hL#D#*02*Q`%ug`T|UDr?FKj8HXc;ogQk8#fZ+|T`-hi`7183-IWeEp3pN1m2r(5}p%-PxhuI z&HYS8>2EVe{MS~ps;J!=D7cE-cDIU&5PhA543|2}$txZK`1?b(TIbcvQqhzf01mFh zI)8mc_Hpw99*h5<%f)YVa&Q79M?0*J{GaRDKcCt6f1jSL69LfS3sAm$^RFlWxiJC& zX#Zd1`12mg!{UJ3PqS~GIP&*E*q4g~T9p3xu*D;E__%lh$yrN>$^U}ae{uWYaP$A-_P@dXzfkhO`NO}QSh11miYmnREZe4`0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H3J*zvOm;kAG&6qy`2(N2?VGR714Hu@Q^QBsZ_t`|? z4h9(Z6xKF|;8#qC@-Dgp%(h=Q47;;Lt@AUuNGGT^)eyf~r-iaTLN|W@+yG+yP3UG8 zztEHMp>#G9JJAFnrQaxeTR(Uc>OYm{kmZ1WlU}2fEM4_8SL^vc5?*T^(CR4R!qLHb zM%6nLbmuuY%MXeTmqD1>ko(Tu<^6da95s^OMj});YL~{1$3x!i8F7D;!H+of~6+JQtR<0X}r59tU2hQwL@$b}{1o%N4a<_%MpB zmC0eogUsv#>Or7j2^JnuIYOno&cK#nJG)6u@>g5otEfi}sf`+Rakt2{L?yH|C1poB zj8kjU=2nwV?v-NLEB=W43aHe^9HY;YM>teTw3RL_Fl!UVk(j zj`oS_MtA3tf36nz2-StvZ)A+h{xaU;VzS@Mrn|9q=|hSeWu z^~bONnXUHE3x6ioKg*RrE2}^2)jvz?|92Y}1Sm~r9K2$O-39?a9SwuO3U1my{Xat` B^{@Z{ literal 0 HcmV?d00001 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000..e3eb04bff1d10 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +/target + +.DS_Store + +# Thumbnails +._* + +# Emacs +\#*\# +.\#* + +# Python +.pyc diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000..d347f460715b4 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,5 @@ +# Code of Conduct + +Please see Libra's +[Code of Conduct](https://developers.libra.org/docs/policies/code-of-conduct), +which describes the expectations for interactions within the community. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000000..402708e9adc7f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,46 @@ +# Contribution Guide + +Our goal is to make contributing to the Libra and Calibra projects easy and transparent. + +
+The repository Calibra Research is meant to share content related to the research projects of Calibra. +
+ +## Contributing to Calibra Research + +To contribute, ensure that you have the latest version of the codebase. To clone the repository, run the following: +```bash +$ git clone https://github.com/calibra/research.git calibra-research +$ cd calibra-research +$ cargo build --all --all-targets +$ cargo test +``` + +## Coding Guidelines for Rust code + +For detailed guidance on how to contribute to the Rust code in the Calibra Research repository refer to [Coding Guidelines](https://developers.libra.org/docs/coding-guidelines). + +## Pull Requests + +Please refer to the documentation to determine the status of each project (e.g. actively developed vs. archived) before submitting a pull request. + +To submit your pull request: + +1. Fork Calibra's `research` repository and create your branch from `master`. +2. If you have added code that should be tested, add unit tests. +3. If you have made changes to APIs, update the relevant documentation, and build and test the developer site. +4. Verify and ensure that the test suite passes. +5. Make sure your code passes both linters. +6. Complete the Contributor License Agreement (CLA), if you haven't already done so. +7. Submit your pull request. + +## Contributor License Agreement + +For your pull requests to be accepted by any Libra and Calibra project, you will need to sign a CLA. You will need to do this only once to work on any Libra open source project. Individuals contributing on their own behalf can sign the [Individual CLA](https://github.com/libra/libra/blob/master/contributing/individual-cla.pdf). If you are contributing on behalf of your employer, please ask them to sign the [Corporate CLA](https://github.com/libra/libra/blob/master/contributing/corporate-cla.pdf). + +## Code of Conduct +Please refer to the [Code of Conduct](https://github.com/libra/libra/blob/master/CODE_OF_CONDUCT.md) for guidelines on interacting with the community. + +## Issues + +Calibra uses [GitHub issues](https://github.com/calibra/research/issues) to track bugs. Please include necessary information and instructions to reproduce your issue. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000000000..bdc6331ccbe67 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,960 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "aho-corasick" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8716408b8bc624ed7f65d223ddb9ac2d044c0547b6fa4b0d554f3a9540496ada" +dependencies = [ + "memchr", +] + +[[package]] +name = "ansi_term" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" +dependencies = [ + "winapi 0.3.8", +] + +[[package]] +name = "arc-swap" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d663a8e9a99154b5fb793032533f6328da35e23aac63d5c152279aa8ba356825" + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi 0.3.8", +] + +[[package]] +name = "backtrace" +version = "0.3.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e692897359247cc6bb902933361652380af0f1b7651ae5c5013407f30e109e" +dependencies = [ + "backtrace-sys", + "cfg-if", + "libc", + "rustc-demangle", +] + +[[package]] +name = "backtrace-sys" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de8aba10a69c8e8d7622c5710229485ec32e9d55fdad160ea559c086fdcd118" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "base64" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5ca2cd0adc3f48f9e9ea5a6bbdf9ccc0bfade884847e484d452414c7ccffb3" + +[[package]] +name = "bincode" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5753e2a71534719bf3f4e57006c3a4f0d2c672a4b676eec84161f763eca87dbf" +dependencies = [ + "byteorder", + "serde", +] + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" + +[[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", +] + +[[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 = "byte-tools" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" + +[[package]] +name = "byteorder" +version = "1.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" + +[[package]] +name = "bytes" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "130aac562c0dd69c56b3b1cc8ffd2e17be31d0b6c25b61c96b76231aa23e39e1" + +[[package]] +name = "cc" +version = "1.0.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e28fa049fda1c330bcf9d723be7663a899c4679724b34c81e9f5a326aab8cd" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "clap" +version = "2.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" +dependencies = [ + "ansi_term", + "atty", + "bitflags", + "strsim", + "textwrap", + "unicode-width", + "vec_map", +] + +[[package]] +name = "clear_on_drop" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97276801e127ffb46b66ce23f35cc96bd454fa311294bced4bbace7baa8b1d17" +dependencies = [ + "cc", +] + +[[package]] +name = "curve25519-dalek" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26778518a7f6cffa1d25a44b602b62b979bd88adb9e99ffec546998cf3404839" +dependencies = [ + "byteorder", + "digest", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" +dependencies = [ + "generic-array", +] + +[[package]] +name = "ed25519-dalek" +version = "1.0.0-pre.3" +source = "git+http://github.com/dalek-cryptography/ed25519-dalek#36a51acbf0ca2c10d974940182c0ff63f530c9d3" +dependencies = [ + "clear_on_drop", + "curve25519-dalek", + "merlin", + "rand", + "sha2", +] + +[[package]] +name = "env_logger" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" +dependencies = [ + "atty", + "humantime", + "log", + "regex", + "termcolor", +] + +[[package]] +name = "failure" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8529c2421efa3066a5cbd8063d2244603824daccb6936b079010bb2aa89464b" +dependencies = [ + "backtrace", + "failure_derive", +] + +[[package]] +name = "failure_derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "030a733c8287d6213886dd487564ff5c8f6aae10278b3588ed177f9d18f8d231" +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 = "fastpay" +version = "0.1.0" +dependencies = [ + "bytes", + "clap", + "env_logger", + "failure", + "fastpay_core", + "futures", + "log", + "net2", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "fastpay_core" +version = "0.1.0" +dependencies = [ + "base64", + "bincode", + "ed25519-dalek", + "failure", + "futures", + "rand", + "serde", + "tokio", +] + +[[package]] +name = "fnv" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3" + +[[package]] +name = "fuchsia-zircon" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +dependencies = [ + "bitflags", + "fuchsia-zircon-sys", +] + +[[package]] +name = "fuchsia-zircon-sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" + +[[package]] +name = "futures" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c329ae8753502fb44ae4fc2b622fa2a94652c41e795143765ba0927f92ab780" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0c77d04ce8edd9cb903932b608268b3fffec4163dc053b3b402bf47eac1f1a8" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f25592f769825e89b92358db00d26f965761e094951ac44d3663ef25b7ac464a" + +[[package]] +name = "futures-executor" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f674f3e1bcb15b37284a90cedf55afdba482ab061c407a9c0ebbd0f3109741ba" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a638959aa96152c7a4cddf50fcb1e3fede0583b27157c26e67d6f99904090dc6" + +[[package]] +name = "futures-macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a5081aa3de1f7542a794a397cde100ed903b0630152d0973479018fd85423a7" +dependencies = [ + "proc-macro-hack", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3466821b4bc114d95b087b850a724c6f83115e929bc88f1fa98a3304a944c8a6" + +[[package]] +name = "futures-task" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b0a34e53cf6cdcd0178aa573aed466b646eb3db769570841fda0c7ede375a27" + +[[package]] +name = "futures-util" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22766cf25d64306bedf0384da004d05c9974ab104fcc4528f1236181c18004c5" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-utils", + "proc-macro-hack", + "proc-macro-nested", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec" +dependencies = [ + "typenum", +] + +[[package]] +name = "getrandom" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7abc8dd8451921606d809ba32e95b6111925cd2906060d2dcc29c070220503eb" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hermit-abi" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a0d737e0f947a1864e93d33fdef4af8445a00d1ed8dc0c8ddb73139ea6abf15" +dependencies = [ + "libc", +] + +[[package]] +name = "humantime" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" +dependencies = [ + "quick-error", +] + +[[package]] +name = "iovec" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e" +dependencies = [ + "libc", +] + +[[package]] +name = "itoa" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" + +[[package]] +name = "keccak" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c21572b4949434e4fc1e1978b99c5f77064153c59d998bf13ecd96fb5ecba7" + +[[package]] +name = "kernel32-sys" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] + +[[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.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99e85c08494b21a9054e7fe1374a732aeadaff3980b6990b94bfd3a70f690005" + +[[package]] +name = "log" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" + +[[package]] +name = "merlin" +version = "1.2.1" +source = "git+https://github.com/isislovecruft/merlin?branch=develop#c483190db3506732691d4a502a97de9774642111" +dependencies = [ + "byteorder", + "clear_on_drop", + "keccak", + "rand_core", +] + +[[package]] +name = "mio" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302dec22bcf6bae6dfb69c647187f4b4d0fb6f535521f7bc022430ce8e12008f" +dependencies = [ + "cfg-if", + "fuchsia-zircon", + "fuchsia-zircon-sys", + "iovec", + "kernel32-sys", + "libc", + "log", + "miow 0.2.1", + "net2", + "slab", + "winapi 0.2.8", +] + +[[package]] +name = "mio-named-pipes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e374eff525ce1c5b7687c4cef63943e7686524a387933ad27ca7ec43779cb3" +dependencies = [ + "log", + "mio", + "miow 0.3.3", + "winapi 0.3.8", +] + +[[package]] +name = "mio-uds" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "966257a94e196b11bb43aca423754d87429960a768de9414f3691d6957abf125" +dependencies = [ + "iovec", + "libc", + "mio", +] + +[[package]] +name = "miow" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" +dependencies = [ + "kernel32-sys", + "net2", + "winapi 0.2.8", + "ws2_32-sys", +] + +[[package]] +name = "miow" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396aa0f2003d7df8395cb93e09871561ccc3e785f0acb369170e8cc74ddf9226" +dependencies = [ + "socket2", + "winapi 0.3.8", +] + +[[package]] +name = "net2" +version = "0.2.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" +dependencies = [ + "cfg-if", + "libc", + "winapi 0.3.8", +] + +[[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 = "opaque-debug" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" + +[[package]] +name = "pin-project-lite" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "237844750cfbb86f67afe27eee600dfbbcb6188d734139b534cbfbf4f96792ae" + +[[package]] +name = "pin-utils" +version = "0.1.0-alpha.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5894c618ce612a3fa23881b152b608bafb8c56cfc22f434a3ba3120b40f7b587" + +[[package]] +name = "ppv-lite86" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74490b50b9fbe561ac330df47c08f3f33073d2d00c150f719147d7c54522fa1b" + +[[package]] +name = "proc-macro-hack" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d659fe7c6d27f25e9d80a1a094c223f5246f6a6596453e09d7229bf42750b63" + +[[package]] +name = "proc-macro-nested" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e946095f9d3ed29ec38de908c22f95d9ac008e424c7bcae54c75a79c527c694" + +[[package]] +name = "proc-macro2" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df246d292ff63439fea9bc8c0a270bed0e390d5ebd4db4ba15aba81111b5abe3" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quote" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bdc6c187c65bca4260c9011c9e3132efe4909da44726bad24cf7572ae338d7f" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom", + "libc", + "rand_chacha", + "rand_core", + "rand_hc", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core", +] + +[[package]] +name = "redox_syscall" +version = "0.1.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" + +[[package]] +name = "regex" +version = "1.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6946991529684867e47d86474e3a6d0c0ab9b82d5821e314b1ede31fa3a4b3" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", + "thread_local", +] + +[[package]] +name = "regex-syntax" +version = "0.6.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fe5bd57d1d7414c6b5ed48563a2c855d995ff777729dcd91c369ec7fea395ae" + +[[package]] +name = "rustc-demangle" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" + +[[package]] +name = "ryu" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "535622e6be132bccd223f4bb2b8ac8d53cda3c7a6394944d3b2b33fb974f9d76" + +[[package]] +name = "serde" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36df6ac6412072f67cf767ebbde4133a5b2e88e76dc6187fa7104cd16f783399" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e549e3abf4fb8621bd1609f11dfc9f5e50320802273b12f3811a67e6716ea6c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da07b57ee2623368351e9a0488bb0b261322a15a6e0ae53e243cbdc0f4208da9" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27044adfd2e1f077f649f59deb9490d3941d674002f7d062870a60ebe9bd47a0" +dependencies = [ + "block-buffer", + "digest", + "fake-simd", + "opaque-debug", +] + +[[package]] +name = "signal-hook-registry" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f478ede9f64724c5d173d7bb56099ec3e2d9fc2774aac65d34b8b890405f41" +dependencies = [ + "arc-swap", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" + +[[package]] +name = "socket2" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03088793f677dce356f3ccc2edb1b314ad191ab702a5de3faf49304f7e104918" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "winapi 0.3.8", +] + +[[package]] +name = "strsim" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" + +[[package]] +name = "subtle" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c65d530b10ccaeac294f349038a597e435b18fb456aadd0840a623f83b9e941" + +[[package]] +name = "syn" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0df0eb663f387145cab623dea85b09c2c5b4b0aef44e945d928e682fce71bb03" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "synstructure" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67656ea1dc1b41b1451851562ea232ec2e5a80242139f7e679ceccfb5d61f545" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "unicode-xid", +] + +[[package]] +name = "termcolor" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "textwrap" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "thread_local" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d40c6d1b69745a6ec6fb1ca717914848da4b44ae29d9b3080cbee91d72a69b14" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "tokio" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34ef16d072d2b6dc8b4a56c70f5c5ced1a37752116f8e7c1e80c659aa7cb6713" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "iovec", + "lazy_static", + "libc", + "memchr", + "mio", + "mio-named-pipes", + "mio-uds", + "num_cpus", + "pin-project-lite", + "signal-hook-registry", + "slab", + "tokio-macros", + "winapi 0.3.8", +] + +[[package]] +name = "tokio-macros" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0c3acc6aa564495a0f2e1d59fab677cd7f81a19994cfc7f3ad0e64301560389" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "typenum" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "373c8a200f9e67a0c95e62a4f52fbf80c23b4381c05a17845531982fa99e6b33" + +[[package]] +name = "unicode-width" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479" + +[[package]] +name = "unicode-xid" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" + +[[package]] +name = "vec_map" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "winapi" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" + +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-build" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa515c5163a99cc82bab70fd3bfdd36d827be85de63737b40fcef2ce084a436e" +dependencies = [ + "winapi 0.3.8", +] + +[[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 = "ws2_32-sys" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] + +[[package]] +name = "zeroize" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbac2ed2ba24cc90f5e06485ac8c7c1e5449fe8911aef4d8877218af021a5b8" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000000000..3a968c00e15a5 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,22 @@ +[workspace] +members = [ + "rust/fastpay_core", + "rust/fastpay", +] + +[profile.release] +debug = true + +[profile.bench] +debug = true + +# This is a workaround to the following ed25519 issue +# https://github.com/dalek-cryptography/ed25519-dalek/issues/126 +# It forces cargo resolution for ed25519 to follow the "git" flavor over +# version numbers, depending on the particular patched merlin that "works" +# given our usage of the "batch" feature. This comment and the following two +# lines should just be deleted once #126 above is fixed, along with updating +# the verison requirement of ed25519-dalek to the (presumptive) version +# 1.0.0-pre.4 +[patch.crates-io] +ed25519-dalek = { git = "http://github.com/dalek-cryptography/ed25519-dalek" } diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000..261eeb9e9f8b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-docs b/LICENSE-docs new file mode 100644 index 0000000000000..a6d7fd364bcc1 --- /dev/null +++ b/LICENSE-docs @@ -0,0 +1,384 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + +b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + +c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + +d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + +e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + +f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + +g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + +h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + +i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + +j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + +k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + +Section 2 -- Scope. + +a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + +b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + +a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + +b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + +c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + +a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + +b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + +c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + +Section 6 -- Term and Termination. + +a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + +c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + +d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + +Section 7 -- Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + +Section 8 -- Interpretation. + +a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + +b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + +c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + +d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public licenses. +Notwithstanding, Creative Commons may elect to apply one of its public +licenses to material it publishes and in those instances will be +considered the "Licensor." Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the public +licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000..c3d682737b327 --- /dev/null +++ b/README.md @@ -0,0 +1,78 @@ + + Calibra Logo + + +
+ +# FastPay + +[![License](https://img.shields.io/badge/license-Apache-green.svg)](LICENSE.md) + +This repository is dedicated to sharing material related to the FastPay protocol, developed at Calibra Research. Software is provided for research-purpose only and is not meant to be used in production. + +## Summary + +FastPay allows a set of distributed authorities, some of which are Byzantine, to maintain a high-integrity and availability settlement system for pre-funded payments. It can be used to settle payments in a native unit of value (crypto-currency), or as a financial side-infrastructure to support retail payments in fiat currencies. FastPay is based on Byzantine Consistent Broadcast as its core primitive, foregoing the expenses of full atomic commit channels (consensus). The resulting system has low-latency for both confirmation and payment finality. Remarkably, each authority can be sharded across many machines to allow unbounded horizontal scalability. Our experiments demonstrate intra-continental confirmation latency of less than 100ms, making FastPay applicable to point of sale payments. In laboratory environments, we achieve over 80,000 transactions per second with 20 authorities---surpassing the requirements of current retail card payment networks, while significantly increasing their robustness. + +## Quickstart with FastPay Prototype + +```bash +cargo build --release +cd target/release + +# Create configuration files for 4 authorities with 4 shards each. +# * Private server states are stored in `server*.json`. +# * `committee.json` is the public description of the FastPay committee. +for I in 1 2 3 4 +do + ./server -- --server server"$I".json generate --host 127.0.0.1 --port 9"$I"00 --shards 4 >> committee.json +done + +# Create configuration files for 1000 user accounts. +# * Private account states are stored in one local wallet `accounts.json`. +# * `initial_accounts.json` is used to mint initial balances on the server side. +./client --committee committee.json --accounts accounts.json create_accounts 1000 --initial_funding 100 >> initial_accounts.json + +# Start servers +for I in 1 2 3 4 +do + for J in $(seq 0 3) + do + ./server --server server"$I".json run --shard "$J" --initial_accounts initial_accounts.json --initial_balance 100 --committee committee.json & + done +done + +# Query (locally cached) balance for first and last user account +ACCOUNT1="`head -n 1 initial_accounts.json`" +ACCOUNT2="`tail -n -1 initial_accounts.json`" +./client --committee committee.json --accounts accounts.json query_balance "$ACCOUNT1" +./client --committee committee.json --accounts accounts.json query_balance "$ACCOUNT2" + +# Transfer 10 units +./client --committee committee.json --accounts accounts.json transfer 10 --from "$ACCOUNT1" --to "$ACCOUNT2" + +# Query balances again +./client --committee committee.json --accounts accounts.json query_balance "$ACCOUNT1" +./client --committee committee.json --accounts accounts.json query_balance "$ACCOUNT2" + +# Launch local benchmark using all user accounts +./client --committee committee.json --accounts accounts.json benchmark + +# Inspect state of first account +grep "$ACCOUNT1" accounts.json + +# Kill servers +kill %1 %2 %3 %4 %5 %6 %7 %8 %9 %10 %11 %12 %13 %14 %15 %16 +``` + +## References + +* [FastPay: High-Performance Byzantine Fault Tolerant Settlement](https://arxiv.org/abs/2003.11506) + +## Contributing + +Read our [Contributing guide](https://developers.libra.org/docs/community/contributing). + +## License + +The content of this repository is licensed as [Apache 2.0](https://github.com/calibra/research/blob/master/LICENSE) diff --git a/rust/fastpay/Cargo.toml b/rust/fastpay/Cargo.toml new file mode 100644 index 0000000000000..ba46e6a4cf599 --- /dev/null +++ b/rust/fastpay/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "fastpay" +version = "0.1.0" +authors = ["Libra "] +publish = false +edition = "2018" + +[dependencies] +bytes = "0.5.4" +clap = "2.33.0" +env_logger = "0.7.1" +failure = "0.1.7" +futures = "0.3.4" +log = "0.4.8" +net2 = "0.2.33" +serde = { version = "1.0.106", features = ["derive"] } +serde_json = "1.0.51" +tokio = { version = "0.2.18", features = ["full"] } + +fastpay_core = { path = "../fastpay_core" } + +[[bin]] +name = "client" +path = "src/client.rs" + +[[bin]] +name = "server" +path = "src/server.rs" + +[[bin]] +name = "bench" +path = "src/bench.rs" diff --git a/rust/fastpay/src/bench.rs b/rust/fastpay/src/bench.rs new file mode 100644 index 0000000000000..a93bac38562cf --- /dev/null +++ b/rust/fastpay/src/bench.rs @@ -0,0 +1,336 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +#![deny(warnings)] + +extern crate fastpay; +extern crate fastpay_core; +extern crate log; + +use fastpay::{network, transport}; +use fastpay_core::authority::*; +use fastpay_core::base_types::*; +use fastpay_core::committee::*; +use fastpay_core::messages::*; +use fastpay_core::serialize::*; + +use bytes::Bytes; +use clap::{App, Arg}; +use futures::stream::StreamExt; +use log::*; +use std::collections::HashMap; +use std::time::{Duration, Instant}; +use tokio::runtime::Builder; +use tokio::time; + +use std::thread; + +#[derive(Debug, Clone)] +struct ClientServerBenchmark { + network_protocol: transport::NetworkProtocol, + host: String, + port: u32, + committee_size: usize, + num_shards: u32, + max_in_flight: usize, + num_accounts: usize, + send_timeout: Duration, + recv_timeout: Duration, + buffer_size: usize, + cross_shard_queue_size: usize, +} + +fn main() { + env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); + let benchmark = ClientServerBenchmark::from_command_line(); + + let (states, orders) = benchmark.make_structures(); + + // Start the servers on the thread pool + for state in states { + // Make special single-core runtime for each server + let b = benchmark.clone(); + thread::spawn(move || { + let mut runtime = Builder::new() + .enable_all() + .basic_scheduler() + .thread_stack_size(15 * 1024 * 1024) + .build() + .unwrap(); + + runtime.block_on(async move { + let server = b.spawn_server(state).await; + if let Err(err) = server.join().await { + error!("Server ended with an error: {}", err); + } + }); + }); + } + + let mut runtime = Builder::new() + .enable_all() + .basic_scheduler() + .thread_stack_size(15 * 1024 * 1024) + .build() + .unwrap(); + runtime.block_on(benchmark.launch_client(orders)); +} + +impl ClientServerBenchmark { + fn make_structures(&self) -> (Vec, Vec<(u32, Bytes)>) { + info!("Preparing accounts."); + let mut keys = Vec::new(); + for _ in 0..self.committee_size { + keys.push(get_key_pair()); + } + let committee = Committee { + voting_rights: keys.iter().map(|(k, _)| (*k, 1)).collect(), + total_votes: self.committee_size, + }; + + // Pick an authority and create one state per shard. + let (public_auth0, secret_auth0) = keys.pop().unwrap(); + let mut states = Vec::new(); + for i in 0..self.num_shards { + let state = AuthorityState::new_shard( + committee.clone(), + public_auth0.clone(), + secret_auth0.copy(), + i as u32, + self.num_shards, + ); + states.push(state); + } + + // Seed user accounts. + let mut account_keys = Vec::new(); + for _ in 0..self.num_accounts { + let keypair = get_key_pair(); + let i = AuthorityState::get_shard(self.num_shards, &keypair.0) as usize; + assert!(states[i].in_shard(&keypair.0)); + let client = AccountOffchainState { + balance: Balance::from(Amount::from(100)), + next_sequence_number: SequenceNumber::from(0), + pending_confirmation: None, + confirmed_log: Vec::new(), + synchronization_log: Vec::new(), + received_log: Vec::new(), + }; + states[i].accounts.insert(keypair.0, client); + account_keys.push(keypair); + } + + info!("Preparing transactions."); + // Make one transaction per account (transfer order + confirmation). + let mut orders: Vec<(u32, Bytes)> = Vec::new(); + let mut next_recipient = get_key_pair().0; + for (pubx, secx) in account_keys.iter() { + let transfer = Transfer { + sender: pubx.clone(), + recipient: Address::FastPay(next_recipient), + amount: Amount::from(50), + sequence_number: SequenceNumber::from(0), + user_data: UserData::default(), + }; + next_recipient = *pubx; + let order = TransferOrder::new(transfer.clone(), secx); + let shard = AuthorityState::get_shard(self.num_shards, &pubx); + + // Serialize order + let bufx = serialize_transfer_order(&order); + assert!(bufx.len() > 0); + + // Make certificate + let mut certificate = CertifiedTransferOrder { + value: order, + signatures: Vec::new(), + }; + for i in 0..committee.quorum_threshold() { + let (pubx, secx) = keys.get(i).unwrap(); + let sig = Signature::new(&certificate.value, secx); + certificate.signatures.push((*pubx, sig)); + } + + let bufx2 = serialize_cert(&certificate); + assert!(bufx2.len() > 0); + + orders.push((shard, bufx2.into())); + orders.push((shard, bufx.into())); + } + + (states, orders) + } + + async fn spawn_server(&self, state: AuthorityState) -> transport::SpawnedServer { + let server = network::Server::new( + self.network_protocol, + self.host.clone(), + self.port, + state, + self.buffer_size, + self.cross_shard_queue_size, + ); + server.spawn().await.unwrap() + } + + async fn launch_client(&self, mut orders: Vec<(u32, Bytes)>) { + time::delay_for(Duration::from_millis(1000)).await; + + let items_number = orders.len() / 2; + let time_start = Instant::now(); + + let max_in_flight = (self.max_in_flight / self.num_shards as usize) as usize; + info!("Set max_in_flight per shard to {}", max_in_flight); + + info!("Sending requests."); + if self.max_in_flight > 0 { + let mass_client = network::MassClient::new( + self.network_protocol, + self.host.clone(), + self.port, + self.buffer_size, + self.send_timeout, + self.recv_timeout, + max_in_flight as u64, + ); + let mut sharded_requests = HashMap::new(); + for (shard, buf) in orders.iter().rev() { + sharded_requests + .entry(*shard) + .or_insert(Vec::new()) + .push(buf.clone()); + } + let responses = mass_client.run(sharded_requests).concat().await; + info!("Received {} responses.", responses.len(),); + } else { + // Use actual client core + let mut client = network::Client::new( + self.network_protocol, + self.host.clone(), + self.port, + self.num_shards, + self.buffer_size, + self.send_timeout, + self.recv_timeout, + ); + + while orders.len() > 0 { + if orders.len() % 1000 == 0 { + info!("Process message {}...", orders.len()); + } + let (shard, order) = orders.pop().unwrap(); + let status = client.send_recv_bytes(shard, order.to_vec()).await; + match status { + Ok(info) => { + debug!("Query response: {:?}", info); + } + Err(error) => { + error!("Failed to execute order: {}", error); + } + } + } + } + + let time_total = time_start.elapsed().as_micros(); + warn!( + "Total time: {}ms, items: {}, tx/sec: {}", + time_total, + items_number, + 1000000.0 * (items_number as f64) / (time_total as f64) + ); + } + + fn from_command_line() -> Self { + let matches = App::new("FastPay benchmark") + .about("Local end-to-end test and benchmark of the FastPay protocol") + .arg( + Arg::with_name("protocol") + .long("protocol") + .help("Choose a network protocol between Udp and Tcp") + .default_value("Udp"), + ) + .arg( + Arg::with_name("host") + .long("host") + .help("Hostname") + .default_value("127.0.0.1"), + ) + .arg( + Arg::with_name("port") + .long("port") + .help("Base port number") + .default_value("9555"), + ) + .arg( + Arg::with_name("committee_size") + .long("committee_size") + .help("Size of the FastPay committee") + .default_value("10"), + ) + .arg( + Arg::with_name("num_shards") + .long("num_shards") + .help("Number of shards per FastPay authority") + .default_value("15"), + ) + .arg( + Arg::with_name("max_in_flight") + .long("max_in_flight") + .help("Maximum number of requests in flight (0 for blocking client)") + .default_value("1000"), + ) + .arg( + Arg::with_name("num_accounts") + .long("num_accounts") + .help("Number of accounts and transactions used in the benchmark") + .default_value("40000"), + ) + .arg( + Arg::with_name("send_timeout") + .long("send_timeout") + .help("Timeout for sending queries (us)") + .default_value("4000000"), + ) + .arg( + Arg::with_name("recv_timeout") + .long("recv_timeout") + .help("Timeout for receiving responses (us)") + .default_value("4000000"), + ) + .arg( + Arg::with_name("buffer_size") + .long("buffer_size") + .help("Maximum size of datagrams received and sent (bytes") + .default_value(transport::DEFAULT_MAX_DATAGRAM_SIZE), + ) + .arg( + Arg::with_name("cross_shard_queue_size") + .long("cross_shard_queue_size") + .help("Number of cross shards messages allowed before blocking the main server loop") + .default_value("1"), + ) + .get_matches(); + + Self { + network_protocol: matches.value_of("protocol").unwrap().parse().unwrap(), + host: matches.value_of("host").unwrap().to_string(), + port: matches.value_of("port").unwrap().parse().unwrap(), + committee_size: matches.value_of("committee_size").unwrap().parse().unwrap(), + num_shards: matches.value_of("num_shards").unwrap().parse().unwrap(), + max_in_flight: matches.value_of("max_in_flight").unwrap().parse().unwrap(), + num_accounts: matches.value_of("num_accounts").unwrap().parse().unwrap(), + send_timeout: Duration::from_micros( + matches.value_of("send_timeout").unwrap().parse().unwrap(), + ), + recv_timeout: Duration::from_micros( + matches.value_of("recv_timeout").unwrap().parse().unwrap(), + ), + buffer_size: matches.value_of("buffer_size").unwrap().parse().unwrap(), + cross_shard_queue_size: matches + .value_of("cross_shard_queue_size") + .unwrap() + .parse() + .unwrap(), + } + } +} diff --git a/rust/fastpay/src/client.rs b/rust/fastpay/src/client.rs new file mode 100644 index 0000000000000..a4ae8aa3d5652 --- /dev/null +++ b/rust/fastpay/src/client.rs @@ -0,0 +1,545 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +#![deny(warnings)] + +extern crate clap; +extern crate env_logger; +extern crate fastpay; +extern crate fastpay_core; + +use fastpay::config::*; +use fastpay::{network, transport}; +use fastpay_core::authority::*; +use fastpay_core::base_types::*; +use fastpay_core::client::*; +use fastpay_core::committee::Committee; +use fastpay_core::messages::*; +use fastpay_core::serialize::*; + +use bytes::Bytes; +use clap::{App, Arg, SubCommand}; +use futures::stream::StreamExt; +use log::*; +use std::collections::{HashMap, HashSet}; +use std::time::{Duration, Instant}; +use tokio::runtime::Runtime; + +fn make_authority_clients( + committee_config: &CommitteeConfig, + buffer_size: usize, + send_timeout: std::time::Duration, + recv_timeout: std::time::Duration, +) -> HashMap { + let mut authority_clients = HashMap::new(); + for config in &committee_config.authorities { + let config = config.clone(); + let client = network::Client::new( + config.network_protocol, + config.host, + config.base_port, + config.num_shards, + buffer_size, + send_timeout, + recv_timeout, + ); + authority_clients.insert(config.address, client); + } + authority_clients +} + +fn make_authority_mass_clients( + committee_config: &CommitteeConfig, + buffer_size: usize, + send_timeout: std::time::Duration, + recv_timeout: std::time::Duration, + max_in_flight: u64, +) -> Vec<(u32, network::MassClient)> { + let mut authority_clients = Vec::new(); + for config in &committee_config.authorities { + let client = network::MassClient::new( + config.network_protocol, + config.host.clone(), + config.base_port, + buffer_size, + send_timeout, + recv_timeout, + max_in_flight / config.num_shards as u64, // Distribute window to diff shards + ); + authority_clients.push((config.num_shards, client)); + } + authority_clients +} + +fn make_client_state( + accounts: &AccountsConfig, + committee_config: &CommitteeConfig, + address: FastPayAddress, + buffer_size: usize, + send_timeout: std::time::Duration, + recv_timeout: std::time::Duration, +) -> ClientState { + let account = accounts.get(&address).expect("Unknown account"); + let committee = Committee::new(committee_config.voting_rights()); + let authority_clients = + make_authority_clients(committee_config, buffer_size, send_timeout, recv_timeout); + ClientState::new( + address, + account.key.copy(), + committee, + authority_clients, + account.next_sequence_number, + account.sent_certificates.clone(), + account.received_certificates.clone(), + account.balance, + ) +} + +/// Make one transfer order per account, up to `max_orders` transfers. +fn make_benchmark_transfer_orders( + accounts_config: &mut AccountsConfig, + max_orders: usize, +) -> (Vec, Vec<(FastPayAddress, Bytes)>) { + let mut orders = Vec::new(); + let mut serialized_orders = Vec::new(); + // TODO: deterministic sequence of orders to recover from interrupted benchmarks. + let mut next_recipient = get_key_pair().0; + for account in accounts_config.accounts_mut() { + let transfer = Transfer { + sender: account.address, + recipient: Address::FastPay(next_recipient), + amount: Amount::from(1), + sequence_number: account.next_sequence_number, + user_data: UserData::default(), + }; + debug!("Preparing transfer order: {:?}", transfer); + account.next_sequence_number = account.next_sequence_number.increment().unwrap(); + next_recipient = account.address; + let order = TransferOrder::new(transfer.clone(), &account.key); + orders.push(order.clone()); + let serialized_order = serialize_transfer_order(&order); + serialized_orders.push((account.address, serialized_order.into())); + if serialized_orders.len() >= max_orders { + break; + } + } + (orders, serialized_orders) +} + +/// Try to make certificates from orders and server configs +fn make_benchmark_certificates_from_orders_and_server_configs( + orders: Vec, + server_config: Vec<&str>, +) -> Vec<(FastPayAddress, Bytes)> { + let mut keys = Vec::new(); + for file in server_config { + let server_config = AuthorityServerConfig::read(file).expect("Fail to read server config"); + keys.push((server_config.authority.address, server_config.key)); + } + let mut serialized_certificates = Vec::new(); + for order in orders { + let mut certificate = CertifiedTransferOrder { + value: order.clone(), + signatures: Vec::new(), + }; + let committee = Committee { + voting_rights: keys.iter().map(|(k, _)| (*k, 1)).collect(), + total_votes: keys.len(), + }; + for i in 0..committee.quorum_threshold() { + let (pubx, secx) = keys.get(i).unwrap(); + let sig = Signature::new(&certificate.value, secx); + certificate.signatures.push((*pubx, sig)); + } + let serialized_certificate = serialize_cert(&certificate); + serialized_certificates.push((order.transfer.sender, serialized_certificate.into())); + } + serialized_certificates +} + +/// Try to aggregate votes into certificates. +fn make_benchmark_certificates_from_votes( + committee_config: &CommitteeConfig, + votes: Vec, +) -> Vec<(FastPayAddress, Bytes)> { + let committee = Committee::new(committee_config.voting_rights()); + let mut aggregators = HashMap::new(); + let mut certificates = Vec::new(); + let mut done_senders = HashSet::new(); + for vote in votes { + // We aggregate votes indexed by sender. + let address = vote.value.transfer.sender; + if done_senders.contains(&address) { + continue; + } + debug!( + "Processing vote on {}'s transfer by {}", + encode_address(&address), + encode_address(&vote.authority) + ); + let value = vote.value; + let aggregator = aggregators + .entry(address) + .or_insert_with(|| SignatureAggregator::try_new(value, &committee).unwrap()); + match aggregator.append(vote.authority, vote.signature) { + Ok(Some(certificate)) => { + debug!("Found certificate: {:?}", certificate); + let buf = serialize_cert(&certificate); + certificates.push((address, buf.into())); + done_senders.insert(address); + } + Ok(None) => { + debug!("Added one vote"); + } + Err(error) => { + error!("Failed to aggregate vote: {}", error); + } + } + } + certificates +} + +/// Broadcast a bulk of requests to each authority. +async fn mass_broadcast_orders( + phase: &'static str, + committee_config: &CommitteeConfig, + buffer_size: usize, + send_timeout: std::time::Duration, + recv_timeout: std::time::Duration, + max_in_flight: u64, + orders: Vec<(FastPayAddress, Bytes)>, +) -> Vec { + let time_start = Instant::now(); + info!("Broadcasting {} {} orders", orders.len(), phase); + let authority_clients = make_authority_mass_clients( + committee_config, + buffer_size, + send_timeout, + recv_timeout, + max_in_flight, + ); + let mut streams = Vec::new(); + for (num_shards, client) in authority_clients { + // Re-index orders by shard for this particular authority client. + let mut sharded_requests = HashMap::new(); + for (address, buf) in &orders { + let shard = AuthorityState::get_shard(num_shards, address); + sharded_requests + .entry(shard) + .or_insert(Vec::new()) + .push(buf.clone()); + } + streams.push(client.run(sharded_requests)); + } + let responses = futures::stream::select_all(streams).concat().await; + let time_elapsed = time_start.elapsed(); + warn!( + "Received {} responses in {} ms.", + responses.len(), + time_elapsed.as_millis() + ); + warn!( + "Estimated server throughput: {} {} orders per sec", + (orders.len() as u128) * 1000000 / time_elapsed.as_micros(), + phase + ); + responses +} + +fn mass_update_recipients( + accounts_config: &mut AccountsConfig, + certificates: Vec<(FastPayAddress, Bytes)>, +) { + for (_sender, buf) in certificates { + if let Ok(SerializedMessage::Cert(certificate)) = deserialize_message(&buf[..]) { + accounts_config.update_for_received_transfer(certificate); + } + } +} + +fn deserialize_response(response: &[u8]) -> Option { + match deserialize_message(response) { + Ok(SerializedMessage::InfoResp(info)) => Some(info), + Ok(SerializedMessage::Error(error)) => { + error!("Received error value: {}", error); + None + } + Ok(_) => { + error!("Unexpected return value"); + None + } + Err(error) => { + error!( + "Unexpected error: {} while deserializing {:?}", + error, response + ); + None + } + } +} + +fn main() { + env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); + let matches = App::new("FastPay client") + .about("A Byzantine fault tolerant payments sidechain with low-latency finality and high throughput") + .args_from_usage(" + --accounts= 'Sets the file storing the state of our user accounts (an empty one will be created if missing)' + --committee= 'Sets the file describing the public configurations of all authorities' + ") + .arg( + Arg::with_name("send_timeout") + .long("send_timeout") + .help("Timeout for sending queries (us)") + .default_value("4000000"), + ) + .arg( + Arg::with_name("recv_timeout") + .long("recv_timeout") + .help("Timeout for receiving responses (us)") + .default_value("4000000"), + ) + .arg( + Arg::with_name("buffer_size") + .long("buffer_size") + .help("Maximum size of datagrams received and sent (bytes") + .default_value(transport::DEFAULT_MAX_DATAGRAM_SIZE), + ) + .subcommand(SubCommand::with_name("transfer") + .about("Transfer funds") + .args_from_usage(" + --from=
'Sending address (must be one of our accounts)' + --to=
'Recipient address' + 'Amount to transfer' + ")) + .subcommand(SubCommand::with_name("query_balance") + .about("Obtain the spendable balance") + .args_from_usage(" +
'Address of the account' + ")) + .subcommand(SubCommand::with_name("benchmark") + .about("Send one transfer per account in bulk mode") + .arg( + Arg::with_name("max_in_flight") + .long("max_in_flight") + .help("Maximum number of requests in flight") + .default_value("200"), + ) + .arg( + Arg::with_name("max_orders") + .long("max_orders") + .help("Use a subset of the accounts to generate N transfers") + .default_value(""), + ) + .arg( + Arg::with_name("server_configs") + .long("server_configs") + .help("Use server configuration files to generate certificates (instead of aggregating received votes).") + .min_values(1), + )) + .subcommand(SubCommand::with_name("create_accounts") + .about("Create new user accounts and print the public keys") + .arg( + Arg::with_name("initial_funding") + .long("initial_funding") + .help("known initial balance of the account") + .default_value("0"), + ) + .args_from_usage(" + 'Number of additional accounts to create' + ")) + .get_matches(); + + let send_timeout = + Duration::from_micros(matches.value_of("send_timeout").unwrap().parse().unwrap()); + let recv_timeout = + Duration::from_micros(matches.value_of("recv_timeout").unwrap().parse().unwrap()); + let accounts_config_path = matches.value_of("accounts").unwrap(); + let committee_config_path = matches.value_of("committee").unwrap(); + let buffer_size = matches + .value_of("buffer_size") + .unwrap() + .parse::() + .unwrap(); + + let mut accounts_config = + AccountsConfig::read_or_create(accounts_config_path).expect("Unable to read user accounts"); + let committee_config = + CommitteeConfig::read(committee_config_path).expect("Unable to read committee config file"); + + match matches.subcommand() { + ("transfer", Some(subm)) => { + let sender = decode_address(&subm.value_of("from").unwrap().to_string()) + .expect("Failed to decode sender's address"); + let recipient = decode_address(&subm.value_of("to").unwrap().to_string()) + .expect("Failed to decode recipient's address"); + let amount = Amount::from(subm.value_of("amount").unwrap().parse::().unwrap()); + + let mut rt = Runtime::new().unwrap(); + rt.block_on(async move { + let mut client_state = make_client_state( + &accounts_config, + &committee_config, + sender, + buffer_size, + send_timeout, + recv_timeout, + ); + info!("Starting transfer"); + let time_start = Instant::now(); + let cert = client_state + .transfer_to_fastpay(amount, recipient, UserData::default()) + .await + .unwrap(); + let time_total = time_start.elapsed().as_micros(); + info!("Transfer confirmed after {} us", time_total); + println!("{:?}", cert); + accounts_config.update_from_state(&client_state); + info!("Updating recipient's local balance"); + let mut recipient_client_state = make_client_state( + &accounts_config, + &committee_config, + recipient, + buffer_size, + send_timeout, + recv_timeout, + ); + recipient_client_state + .receive_from_fastpay(cert) + .await + .unwrap(); + accounts_config.update_from_state(&recipient_client_state); + accounts_config + .write(accounts_config_path) + .expect("Unable to write user accounts"); + info!("Saved user account states"); + }); + } + ("query_balance", Some(subm)) => { + let address = decode_address(&subm.value_of("address").unwrap().to_string()) + .expect("Failed to decode address"); + + let mut rt = Runtime::new().unwrap(); + rt.block_on(async move { + let mut client_state = make_client_state( + &accounts_config, + &committee_config, + address, + buffer_size, + send_timeout, + recv_timeout, + ); + info!("Starting balance query"); + let time_start = Instant::now(); + let amount = client_state.get_spendable_amount().await.unwrap(); + let time_total = time_start.elapsed().as_micros(); + info!("Balance confirmed after {} us", time_total); + println!("{:?}", amount); + accounts_config.update_from_state(&client_state); + accounts_config + .write(accounts_config_path) + .expect("Unable to write user accounts"); + info!("Saved client account state"); + }); + } + ("benchmark", Some(subm)) => { + let max_in_flight: u64 = subm.value_of("max_in_flight").unwrap().parse().unwrap(); + let max_orders: usize = subm + .value_of("max_orders") + .unwrap() + .parse() + .unwrap_or(accounts_config.num_accounts()); + let server_configs = if subm.is_present("server_configs") { + let files: Vec<_> = subm.values_of("server_configs").unwrap().collect(); + Some(files) + } else { + None + }; + + let mut rt = Runtime::new().unwrap(); + rt.block_on(async move { + warn!("Starting benchmark phase 1 (transfer orders)"); + let (orders, serialize_orders) = + make_benchmark_transfer_orders(&mut accounts_config, max_orders); + let responses = mass_broadcast_orders( + "transfer", + &committee_config, + buffer_size, + send_timeout, + recv_timeout, + max_in_flight, + serialize_orders, + ) + .await; + let votes: Vec<_> = responses + .into_iter() + .filter_map(|buf| { + deserialize_response(&buf[..]).and_then(|info| info.pending_confirmation) + }) + .collect(); + warn!("Received {} valid votes.", votes.len()); + + warn!("Starting benchmark phase 2 (confirmation orders)"); + let certificates = if let Some(files) = server_configs { + make_benchmark_certificates_from_orders_and_server_configs(orders, files) + } else { + make_benchmark_certificates_from_votes(&committee_config, votes) + }; + let responses = mass_broadcast_orders( + "confirmation", + &committee_config, + buffer_size, + send_timeout, + recv_timeout, + max_in_flight, + certificates.clone(), + ) + .await; + let mut confirmed = HashSet::new(); + let num_valid = + responses + .iter() + .fold(0, |acc, buf| match deserialize_response(&buf[..]) { + Some(info) => { + confirmed.insert(info.sender); + acc + 1 + } + None => acc, + }); + warn!( + "Received {} valid confirmations for {} transfers.", + num_valid, + confirmed.len() + ); + + warn!("Updating local state of user accounts"); + // Make sure that the local balances are accurate so that future + // balance checks of the non-mass client pass. + mass_update_recipients(&mut accounts_config, certificates); + accounts_config + .write(accounts_config_path) + .expect("Unable to write user accounts"); + info!("Saved client account state"); + }); + } + ("create_accounts", Some(subm)) => { + let num_accounts: u32 = subm.value_of("num").unwrap().parse().unwrap(); + let known_initial_funding = subm + .value_of("initial_funding") + .unwrap() + .parse::() + .unwrap(); + + for _ in 0..num_accounts { + let account = UserAccount::new(Balance::from(known_initial_funding)); + println!("{}", encode_address(&account.address)); + accounts_config.insert(account); + } + accounts_config + .write(accounts_config_path) + .expect("Unable to write user accounts"); + } + _ => { + error!("Unknown command"); + } + } +} diff --git a/rust/fastpay/src/config.rs b/rust/fastpay/src/config.rs new file mode 100644 index 0000000000000..bc74227be9188 --- /dev/null +++ b/rust/fastpay/src/config.rs @@ -0,0 +1,215 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use crate::fastpay_core::base_types::*; +use crate::fastpay_core::client::ClientState; +use crate::fastpay_core::messages::{Address, CertifiedTransferOrder}; +use crate::transport::NetworkProtocol; + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs::{self, File, OpenOptions}; +use std::io::{BufRead, BufReader, BufWriter, Write}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct AuthorityConfig { + pub network_protocol: NetworkProtocol, + #[serde( + serialize_with = "address_as_base64", + deserialize_with = "address_from_base64" + )] + pub address: FastPayAddress, + pub host: String, + pub base_port: u32, + pub num_shards: u32, +} + +impl AuthorityConfig { + pub fn print(&self) { + let data = serde_json::to_string(self).unwrap(); + println!("{}", data); + } +} + +#[derive(Serialize, Deserialize)] +pub struct AuthorityServerConfig { + pub authority: AuthorityConfig, + pub key: SecretKey, +} + +impl AuthorityServerConfig { + pub fn read(path: &str) -> Result { + let data = fs::read(path)?; + Ok(serde_json::from_slice(data.as_slice())?) + } + + pub fn write(&self, path: &str) -> Result<(), std::io::Error> { + let file = OpenOptions::new().create(true).write(true).open(path)?; + let mut writer = BufWriter::new(file); + let data = serde_json::to_string_pretty(self).unwrap(); + writer.write_all(data.as_ref())?; + writer.write_all(b"\n")?; + Ok(()) + } +} + +pub struct CommitteeConfig { + pub authorities: Vec, +} + +impl CommitteeConfig { + pub fn read(path: &str) -> Result { + let file = File::open(path)?; + let reader = BufReader::new(file); + let stream = serde_json::Deserializer::from_reader(reader).into_iter(); + Ok(Self { + authorities: stream.filter_map(Result::ok).collect(), + }) + } + + pub fn write(&self, path: &str) -> Result<(), std::io::Error> { + let file = OpenOptions::new().create(true).write(true).open(path)?; + let mut writer = BufWriter::new(file); + for config in &self.authorities { + serde_json::to_writer(&mut writer, config)?; + writer.write_all(b"\n")?; + } + Ok(()) + } + + pub fn voting_rights(&self) -> BTreeMap { + let mut map = BTreeMap::new(); + for authority in &self.authorities { + map.insert(authority.address, 1); + } + map + } +} + +#[derive(Serialize, Deserialize)] +pub struct UserAccount { + #[serde( + serialize_with = "address_as_base64", + deserialize_with = "address_from_base64" + )] + pub address: FastPayAddress, + pub key: SecretKey, + pub next_sequence_number: SequenceNumber, + pub balance: Balance, + pub sent_certificates: Vec, + pub received_certificates: Vec, +} + +impl UserAccount { + pub fn new(balance: Balance) -> Self { + let (address, key) = get_key_pair(); + Self { + address, + key, + next_sequence_number: SequenceNumber::new(), + balance, + sent_certificates: Vec::new(), + received_certificates: Vec::new(), + } + } +} + +pub struct AccountsConfig { + accounts: BTreeMap, +} + +impl AccountsConfig { + pub fn get(&self, address: &FastPayAddress) -> Option<&UserAccount> { + self.accounts.get(address) + } + + pub fn insert(&mut self, account: UserAccount) { + self.accounts.insert(account.address, account); + } + + pub fn num_accounts(&self) -> usize { + self.accounts.len() + } + + pub fn accounts_mut(&mut self) -> impl Iterator { + self.accounts.values_mut() + } + + pub fn update_from_state(&mut self, state: &ClientState) { + let account = self + .accounts + .get_mut(&state.address()) + .expect("Updated account should already exist"); + account.next_sequence_number = state.next_sequence_number(); + account.balance = state.balance(); + account.sent_certificates = state.sent_certificates().clone(); + account.received_certificates = state.received_certificates().cloned().collect(); + } + + pub fn update_for_received_transfer(&mut self, certificate: CertifiedTransferOrder) { + let transfer = &certificate.value.transfer; + if let Address::FastPay(recipient) = &transfer.recipient { + if let Some(config) = self.accounts.get_mut(recipient) { + if let Err(position) = config + .received_certificates + .binary_search_by_key(&certificate.key(), CertifiedTransferOrder::key) + { + config.balance = config.balance.add(transfer.amount.into()).unwrap(); + config.received_certificates.insert(position, certificate) + } + } + } + } + + pub fn read_or_create(path: &str) -> Result { + let file = OpenOptions::new() + .create(true) + .write(true) + .read(true) + .open(path)?; + let reader = BufReader::new(file); + let stream = serde_json::Deserializer::from_reader(reader).into_iter(); + Ok(Self { + accounts: stream + .filter_map(Result::ok) + .map(|account: UserAccount| (account.address, account)) + .collect(), + }) + } + + pub fn write(&self, path: &str) -> Result<(), std::io::Error> { + let file = OpenOptions::new().write(true).open(path)?; + let mut writer = BufWriter::new(file); + for account in self.accounts.values() { + serde_json::to_writer(&mut writer, account)?; + writer.write_all(b"\n")?; + } + Ok(()) + } +} + +pub struct InitialStateConfig { + pub addresses: Vec, +} + +impl InitialStateConfig { + pub fn read(path: &str) -> Result { + let file = File::open(path)?; + let reader = BufReader::new(file); + let mut addresses = Vec::new(); + for line in reader.lines() { + addresses.push(decode_address(&line?)?); + } + Ok(Self { addresses }) + } + + pub fn write(&self, path: &str) -> Result<(), std::io::Error> { + let file = OpenOptions::new().create(true).write(true).open(path)?; + let mut writer = BufWriter::new(file); + for address in &self.addresses { + writer.write_all(encode_address(address).as_ref())?; + writer.write_all(b"\n")?; + } + Ok(()) + } +} diff --git a/rust/fastpay/src/lib.rs b/rust/fastpay/src/lib.rs new file mode 100644 index 0000000000000..61d2c056edd72 --- /dev/null +++ b/rust/fastpay/src/lib.rs @@ -0,0 +1,12 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +#![deny(warnings)] + +extern crate failure; +extern crate fastpay_core; +extern crate log; + +pub mod config; +pub mod network; +pub mod transport; diff --git a/rust/fastpay/src/network.rs b/rust/fastpay/src/network.rs new file mode 100644 index 0000000000000..4d2a0167e9669 --- /dev/null +++ b/rust/fastpay/src/network.rs @@ -0,0 +1,463 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use crate::transport::*; +use fastpay_core::authority::*; +use fastpay_core::base_types::*; +use fastpay_core::client::*; +use fastpay_core::error::*; +use fastpay_core::messages::*; +use fastpay_core::serialize::*; + +use bytes::Bytes; +use futures::channel::mpsc; +use futures::future::FutureExt; +use futures::sink::SinkExt; +use futures::stream::StreamExt; +use log::*; +use std::io; +use tokio::time; + +pub struct Server { + network_protocol: NetworkProtocol, + base_address: String, + base_port: u32, + state: AuthorityState, + buffer_size: usize, + cross_shard_queue_size: usize, + // Stats + packets_processed: u64, + user_errors: u64, +} + +impl Server { + pub fn new( + network_protocol: NetworkProtocol, + base_address: String, + base_port: u32, + state: AuthorityState, + buffer_size: usize, + cross_shard_queue_size: usize, + ) -> Self { + Self { + network_protocol, + base_address, + base_port, + state, + buffer_size, + cross_shard_queue_size, + packets_processed: 0, + user_errors: 0, + } + } + + pub fn packets_processed(&self) -> u64 { + self.packets_processed + } + + pub fn user_errors(&self) -> u64 { + self.user_errors + } + + async fn forward_cross_shard_queries( + network_protocol: NetworkProtocol, + base_address: String, + base_port: u32, + this_shard: ShardId, + mut receiver: mpsc::Receiver<(Vec, ShardId)>, + ) { + let mut pool = network_protocol + .make_outgoing_connection_pool() + .await + .expect("Initialization should not fail"); + + let mut queries_sent = 0u64; + while let Some((buf, shard)) = receiver.next().await { + // Send cross-shard query. + let remote_address = format!("{}:{}", base_address, base_port + shard); + let status = pool.send_data_to(&buf, &remote_address).await; + if let Err(error) = status { + error!("Failed to send cross-shard query: {}", error); + } else { + debug!("Sent cross shard query: {} -> {}", this_shard, shard); + queries_sent += 1; + if queries_sent % 2000 == 0 { + info!( + "{}:{} (shard {}) has sent {} cross-shard queries", + base_address, + base_port + this_shard, + this_shard, + queries_sent + ); + } + } + } + } + + pub async fn spawn(self) -> Result { + info!( + "Listening to {} traffic on {}:{}", + self.network_protocol, + self.base_address, + self.base_port + self.state.shard_id + ); + let address = format!( + "{}:{}", + self.base_address, + self.base_port + self.state.shard_id + ); + + let (cross_shard_sender, cross_shard_receiver) = mpsc::channel(self.cross_shard_queue_size); + tokio::spawn(Self::forward_cross_shard_queries( + self.network_protocol, + self.base_address.clone(), + self.base_port, + self.state.shard_id, + cross_shard_receiver, + )); + + let buffer_size = self.buffer_size; + let protocol = self.network_protocol; + let state = RunningServerState { + server: self, + cross_shard_sender, + }; + // Launch server for the appropriate protocol. + protocol.spawn_server(&address, state, buffer_size).await + } +} + +struct RunningServerState { + server: Server, + cross_shard_sender: mpsc::Sender<(Vec, ShardId)>, +} + +impl MessageHandler for RunningServerState { + fn handle_message<'a>( + &'a mut self, + buffer: &'a [u8], + ) -> futures::future::BoxFuture<'a, Option>> { + Box::pin(async move { + let result = deserialize_message(buffer); + let reply = match result { + Err(_) => Err(FastPayError::InvalidDecoding), + Ok(result) => { + match result { + SerializedMessage::Order(message) => self + .server + .state + .handle_transfer_order(message) + .map(|info| Some(serialize_info_response(&info))), + SerializedMessage::Cert(message) => { + let confirmation_order = ConfirmationOrder { + transfer_certificate: message.clone(), + }; + match self + .server + .state + .handle_confirmation_order(confirmation_order) + { + Ok((info, send_shard)) => { + // Send a message to other shard + if let Some(cross_shard_update) = send_shard { + let shard = cross_shard_update.shard_id; + let tmp_out = serialize_cross_shard(&message); + debug!( + "Scheduling cross shard query: {} -> {}", + self.server.state.shard_id, shard + ); + self.cross_shard_sender + .send((tmp_out, shard)) + .await + .expect("internal channel should not fail"); + }; + + // Response + Ok(Some(serialize_info_response(&info))) + } + Err(error) => Err(error), + } + } + SerializedMessage::InfoReq(message) => self + .server + .state + .handle_account_info_request(message) + .map(|info| Some(serialize_info_response(&info))), + SerializedMessage::CrossShard(message) => { + match self + .server + .state + .handle_cross_shard_recipient_commit(message) + { + Ok(_) => Ok(None), // Nothing to reply + Err(error) => { + error!("Failed to handle cross-shard query: {}", error); + Ok(None) // Nothing to reply + } + } + } + _ => Err(FastPayError::UnexpectedMessage), + } + } + }; + + self.server.packets_processed += 1; + if self.server.packets_processed % 5000 == 0 { + info!( + "{}:{} (shard {}) has processed {} packets", + self.server.base_address, + self.server.base_port + self.server.state.shard_id, + self.server.state.shard_id, + self.server.packets_processed + ); + } + + match reply { + Ok(x) => { + return x; + } + Err(error) => { + warn!("User query failed: {}", error); + self.server.user_errors += 1; + return Some(serialize_error(&error)); + } + }; + }) + } +} + +#[derive(Clone)] +pub struct Client { + network_protocol: NetworkProtocol, + base_address: String, + base_port: u32, + num_shards: u32, + buffer_size: usize, + send_timeout: std::time::Duration, + recv_timeout: std::time::Duration, +} + +impl Client { + pub fn new( + network_protocol: NetworkProtocol, + base_address: String, + base_port: u32, + num_shards: u32, + buffer_size: usize, + send_timeout: std::time::Duration, + recv_timeout: std::time::Duration, + ) -> Self { + Self { + network_protocol, + base_address, + base_port, + num_shards, + buffer_size, + send_timeout, + recv_timeout, + } + } + + async fn send_recv_bytes_internal( + &mut self, + shard: ShardId, + buf: Vec, + ) -> Result, io::Error> { + let address = format!("{}:{}", self.base_address, self.base_port + shard); + let mut stream = self + .network_protocol + .connect(address, self.buffer_size) + .await?; + // Send message + time::timeout(self.send_timeout, stream.write_data(&buf)).await??; + // Wait for reply + time::timeout(self.recv_timeout, stream.read_data()).await? + } + + pub async fn send_recv_bytes( + &mut self, + shard: ShardId, + buf: Vec, + ) -> Result { + match self.send_recv_bytes_internal(shard, buf).await { + Err(error) => { + return Err(FastPayError::ClientIOError { + error: format!("{}", error), + }); + } + Ok(response) => { + // Parse reply + match deserialize_message(&response[..]) { + Ok(SerializedMessage::InfoResp(resp)) => Ok(resp), + Ok(SerializedMessage::Error(error)) => Err(error), + Err(_) => Err(FastPayError::InvalidDecoding), + _ => Err(FastPayError::UnexpectedMessage), + } + } + } + } +} + +impl AuthorityClient for Client { + /// Initiate a new transfer to a FastPay or Primary account. + fn handle_transfer_order( + &mut self, + order: TransferOrder, + ) -> AsyncResult { + Box::pin(async move { + let shard = AuthorityState::get_shard(self.num_shards, &order.transfer.sender); + self.send_recv_bytes(shard, serialize_transfer_order(&order)) + .await + }) + } + + /// Confirm a transfer to a FastPay or Primary account. + fn handle_confirmation_order( + &mut self, + order: ConfirmationOrder, + ) -> AsyncResult { + Box::pin(async move { + let shard = AuthorityState::get_shard( + self.num_shards, + &order.transfer_certificate.value.transfer.sender, + ); + self.send_recv_bytes(shard, serialize_cert(&order.transfer_certificate)) + .await + }) + } + + /// Handle information requests for this account. + fn handle_account_info_request( + &mut self, + request: AccountInfoRequest, + ) -> AsyncResult { + Box::pin(async move { + let shard = AuthorityState::get_shard(self.num_shards, &request.sender); + self.send_recv_bytes(shard, serialize_info_request(&request)) + .await + }) + } +} + +#[derive(Clone)] +pub struct MassClient { + network_protocol: NetworkProtocol, + base_address: String, + base_port: u32, + buffer_size: usize, + send_timeout: std::time::Duration, + recv_timeout: std::time::Duration, + max_in_flight: u64, +} + +impl MassClient { + pub fn new( + network_protocol: NetworkProtocol, + base_address: String, + base_port: u32, + buffer_size: usize, + send_timeout: std::time::Duration, + recv_timeout: std::time::Duration, + max_in_flight: u64, + ) -> Self { + Self { + network_protocol, + base_address, + base_port, + buffer_size, + send_timeout, + recv_timeout, + max_in_flight, + } + } + + async fn run_shard(&self, shard: u32, requests: Vec) -> Result, io::Error> { + let address = format!("{}:{}", self.base_address, self.base_port + shard); + let mut stream = self + .network_protocol + .connect(address, self.buffer_size) + .await?; + let mut requests = requests.iter(); + let mut in_flight: u64 = 0; + let mut responses = Vec::new(); + + loop { + while in_flight < self.max_in_flight { + let request = match requests.next() { + None => { + if in_flight == 0 { + return Ok(responses); + } + // No more entries to send. + break; + } + Some(request) => request, + }; + let status = time::timeout(self.send_timeout, stream.write_data(&request)).await; + if let Err(error) = status { + error!("Failed to send request: {}", error); + continue; + } + in_flight += 1; + } + if requests.len() % 5000 == 0 && requests.len() > 0 { + info!("In flight {} Remaining {}", in_flight, requests.len()); + } + match time::timeout(self.recv_timeout, stream.read_data()).await { + Ok(Ok(buffer)) => { + in_flight -= 1; + responses.push(Bytes::from(buffer)); + } + Ok(Err(error)) => { + if error.kind() == io::ErrorKind::UnexpectedEof { + info!("Socket closed by server"); + return Ok(responses); + } + error!("Received error response: {}", error); + } + Err(error) => { + error!( + "Timeout while receiving response: {} (in flight: {})", + error, in_flight + ); + } + } + } + } + + /// Spin off one task for each shard based on this authority client. + pub fn run(&self, sharded_requests: I) -> impl futures::stream::Stream> + where + I: IntoIterator)>, + { + let handles = futures::stream::FuturesUnordered::new(); + for (shard, requests) in sharded_requests { + let client = self.clone(); + handles.push( + tokio::spawn(async move { + info!( + "Sending {} requests to {}:{} (shard {})", + client.network_protocol, + client.base_address, + client.base_port + shard, + shard + ); + let responses = client + .run_shard(shard, requests) + .await + .unwrap_or(Vec::new()); + info!( + "Done sending {} requests to {}:{} (shard {})", + client.network_protocol, + client.base_address, + client.base_port + shard, + shard + ); + responses + }) + .then(|x| async { x.unwrap_or(Vec::new()) }), + ); + } + handles + } +} diff --git a/rust/fastpay/src/server.rs b/rust/fastpay/src/server.rs new file mode 100644 index 0000000000000..6f4e1b71ab39f --- /dev/null +++ b/rust/fastpay/src/server.rs @@ -0,0 +1,243 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +#![deny(warnings)] + +extern crate clap; +extern crate env_logger; +extern crate fastpay; +extern crate fastpay_core; + +use fastpay::config::*; +use fastpay::network; +use fastpay::transport; +use fastpay_core::authority::*; +use fastpay_core::base_types::*; +use fastpay_core::committee::Committee; + +use clap::{App, Arg, SubCommand}; +use futures::future::join_all; +use log::*; +use tokio::runtime::Runtime; + +fn make_shard_server( + local_ip_addr: &str, + server_config_path: &str, + committee_config_path: &str, + initial_accounts_config_path: &str, + initial_balance: Balance, + buffer_size: usize, + cross_shard_queue_size: usize, + shard: u32, +) -> network::Server { + let server_config = + AuthorityServerConfig::read(server_config_path).expect("Fail to read server config"); + let committee_config = + CommitteeConfig::read(committee_config_path).expect("Fail to read committee config"); + let initial_accounts_config = InitialStateConfig::read(initial_accounts_config_path) + .expect("Fail to read initial account config"); + + let committee = Committee::new(committee_config.voting_rights()); + let num_shards = server_config.authority.num_shards; + + let mut state = AuthorityState::new_shard( + committee.clone(), + server_config.authority.address, + server_config.key.copy(), + shard, + num_shards, + ); + + // Load initial states + for address in &initial_accounts_config.addresses { + if AuthorityState::get_shard(num_shards, address) != shard { + continue; + } + let client = AccountOffchainState { + balance: initial_balance, + next_sequence_number: SequenceNumber::from(0), + pending_confirmation: None, + confirmed_log: Vec::new(), + synchronization_log: Vec::new(), + received_log: Vec::new(), + }; + state.accounts.insert(*address, client); + } + + network::Server::new( + server_config.authority.network_protocol, + local_ip_addr.to_string(), + server_config.authority.base_port, + state, + buffer_size, + cross_shard_queue_size, + ) +} + +fn make_servers( + local_ip_addr: &str, + server_config_path: &str, + committee_config_path: &str, + initial_accounts_config_path: &str, + initial_balance: Balance, + buffer_size: usize, + cross_shard_queue_size: usize, +) -> Vec { + let server_config = + AuthorityServerConfig::read(server_config_path).expect("Fail to read server config"); + let num_shards = server_config.authority.num_shards; + + let mut servers = Vec::new(); + for shard in 0..num_shards { + servers.push(make_shard_server( + local_ip_addr, + server_config_path, + committee_config_path, + initial_accounts_config_path, + initial_balance, + buffer_size, + cross_shard_queue_size, + shard, + )) + } + servers +} + +fn main() { + env_logger::from_env(env_logger::Env::default().default_filter_or("info")).init(); + let matches = App::new("FastPay server") + .about("A byzantine fault tolerant payments sidechain with low-latency finality and high throughput") + .args_from_usage(" + --server= 'Path to the file containing the server configuration of this FastPay authority (including its secret key)' + ") + .subcommand(SubCommand::with_name("run") + .about("Runs a service for each shard of the FastPay authority") + .arg( + Arg::with_name("buffer_size") + .long("buffer_size") + .help("Maximum size of datagrams received and sent (bytes") + .default_value(transport::DEFAULT_MAX_DATAGRAM_SIZE), + ) + .arg( + Arg::with_name("cross_shard_queue_size") + .long("cross_shard_queue_size") + .help("Number of cross shards messages allowed before blocking the main server loop") + .default_value("1000"), + ) + .args_from_usage(" + --committee= 'Path to the file containing the public description of all authorities in this FastPay committee' + --initial_accounts= 'Path to the file describing the initial user accounts' + --initial_balance= 'Path to the file describing the initial balance of user accounts' + --shard=[INT] 'Runs a specific shard (from 0 to shards-1)' + ")) + .subcommand(SubCommand::with_name("generate") + .about("Generate a new server configuration and output its public description") + .arg( + Arg::with_name("protocol") + .long("protocol") + .help("Chooses a network protocol between Udp and Tcp") + .default_value("Udp"), + ) + .args_from_usage(" + --host=
'Sets the public name of the host' + --port= 'Sets the base port, i.e. the port on which the server listens for the first shard' + --shards= 'Number of shards for this authority'")) + .get_matches(); + + match matches.subcommand() { + ("run", Some(subm)) => { + // Reading our own config + let server_config_path = matches.value_of("server").unwrap(); + let committee_config_path = subm.value_of("committee").unwrap(); + let initial_accounts_config_path = subm.value_of("initial_accounts").unwrap(); + let initial_balance = Balance::from( + subm.value_of("initial_balance") + .unwrap() + .parse::() + .unwrap(), + ); + let buffer_size = subm + .value_of("buffer_size") + .unwrap() + .parse::() + .unwrap(); + let cross_shard_queue_size = subm + .value_of("cross_shard_queue_size") + .unwrap() + .parse::() + .unwrap(); + let specific_shard = if subm.is_present("shard") { + let shard = subm.value_of("shard").unwrap(); + Some(shard.parse::().unwrap()) + } else { + None + }; + + // Run the server + let servers = if let Some(shard) = specific_shard { + info!("Running shard number {}", shard); + let server = make_shard_server( + "0.0.0.0", // Allow local IP address to be different from the public one. + server_config_path, + committee_config_path, + initial_accounts_config_path, + initial_balance, + buffer_size, + cross_shard_queue_size, + shard, + ); + vec![server] + } else { + info!("Running all shards"); + make_servers( + "0.0.0.0", // Allow local IP address to be different from the public one. + server_config_path, + committee_config_path, + initial_accounts_config_path, + initial_balance, + buffer_size, + cross_shard_queue_size, + ) + }; + + let mut rt = Runtime::new().unwrap(); + let mut handles = Vec::new(); + for server in servers { + handles.push(async move { + let spawned_server = match server.spawn().await { + Ok(server) => server, + Err(err) => { + error!("Failed to start server: {}", err); + return; + } + }; + if let Err(err) = spawned_server.join().await { + error!("Server ended with an error: {}", err); + } + }); + } + rt.block_on(join_all(handles)); + } + ("generate", Some(subm)) => { + let network_protocol = subm.value_of("protocol").unwrap().parse().unwrap(); + let server_config_path = matches.value_of("server").unwrap(); + let (address, key) = get_key_pair(); + let authority = AuthorityConfig { + network_protocol, + address, + host: subm.value_of("host").unwrap().parse().unwrap(), + base_port: subm.value_of("port").unwrap().parse().unwrap(), + num_shards: subm.value_of("shards").unwrap().parse().unwrap(), + }; + let server = AuthorityServerConfig { authority, key }; + server + .write(server_config_path) + .expect("Unable to write server config file"); + info!("Wrote server config file"); + server.authority.print(); + } + _ => { + error!("Unknown command"); + } + } +} diff --git a/rust/fastpay/src/transport.rs b/rust/fastpay/src/transport.rs new file mode 100644 index 0000000000000..44ec3860e4d33 --- /dev/null +++ b/rust/fastpay/src/transport.rs @@ -0,0 +1,376 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use clap::arg_enum; +use futures::future; +use log::*; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::convert::TryInto; +use std::io; +use std::sync::Arc; +use tokio::net::TcpListener; +use tokio::net::{TcpStream, UdpSocket}; +use tokio::prelude::*; + +#[cfg(test)] +#[path = "unit_tests/transport_tests.rs"] +mod transport_tests; + +/// Suggested buffer size +pub const DEFAULT_MAX_DATAGRAM_SIZE: &'static str = "65507"; + +// Supported transport protocols. +arg_enum! { + #[derive(Clone, Copy, Debug, Serialize, Deserialize)] + pub enum NetworkProtocol { + Udp, + Tcp, + } +} + +/// How to send and obtain data packets over an "active socket". +pub trait DataStream: Send { + fn write_data<'a>( + &'a mut self, + buffer: &'a [u8], + ) -> future::BoxFuture<'a, Result<(), std::io::Error>>; + fn read_data(&mut self) -> future::BoxFuture, std::io::Error>>; +} + +/// A pool of (outgoing) data streams. +pub trait DataStreamPool: Send { + fn send_data_to<'a>( + &'a mut self, + buffer: &'a [u8], + address: &'a String, + ) -> future::BoxFuture<'a, Result<(), io::Error>>; +} + +/// The handler required to create a service. +pub trait MessageHandler { + fn handle_message<'a>(&'a mut self, buffer: &'a [u8]) + -> future::BoxFuture<'a, Option>>; +} + +/// The result of spawning a server is oneshot channel to kill it and a handle to track completion. +pub struct SpawnedServer { + complete: futures::channel::oneshot::Sender<()>, + handle: tokio::task::JoinHandle>, +} + +impl SpawnedServer { + pub async fn join(self) -> Result<(), std::io::Error> { + // Note that dropping `self.complete` would terminate the server. + self.handle.await??; + Ok(()) + } + + pub async fn kill(self) -> Result<(), std::io::Error> { + self.complete.send(()).unwrap(); + self.handle.await??; + Ok(()) + } +} + +impl NetworkProtocol { + /// Create a DataStream for this protocol. + pub async fn connect( + &self, + address: String, + max_data_size: usize, + ) -> Result, std::io::Error> { + let stream: Box = match self { + NetworkProtocol::Udp => Box::new(UdpDataStream::connect(address, max_data_size).await?), + NetworkProtocol::Tcp => Box::new(TcpDataStream::connect(address, max_data_size).await?), + }; + Ok(stream) + } + + /// Create a DataStreamPool for this protocol. + pub async fn make_outgoing_connection_pool( + &self, + ) -> Result, std::io::Error> { + let pool: Box = match self { + Self::Udp => Box::new(UdpDataStreamPool::new().await?), + Self::Tcp => Box::new(TcpDataStreamPool::new().await?), + }; + Ok(pool) + } + + /// Run a server for this protocol and the given message handler. + pub async fn spawn_server( + &self, + address: &String, + state: S, + buffer_size: usize, + ) -> Result + where + S: MessageHandler + Send + 'static, + { + let (complete, receiver) = futures::channel::oneshot::channel(); + let handle = match self { + Self::Udp => { + let socket = UdpSocket::bind(&address).await?; + tokio::spawn(Self::run_udp_server(socket, state, receiver, buffer_size)) + } + Self::Tcp => { + let listener = TcpListener::bind(address).await?; + tokio::spawn(Self::run_tcp_server(listener, state, receiver, buffer_size)) + } + }; + Ok(SpawnedServer { complete, handle }) + } +} + +/// An implementation of DataStream based on UDP. +struct UdpDataStream { + socket: UdpSocket, + address: String, + buffer: Vec, +} + +impl UdpDataStream { + async fn connect(address: String, max_data_size: usize) -> Result { + let socket = UdpSocket::bind(&"0.0.0.0:0").await?; + let buffer = vec![0u8; max_data_size]; + Ok(Self { + socket, + address, + buffer, + }) + } +} + +impl DataStream for UdpDataStream { + fn write_data<'a>( + &'a mut self, + buffer: &'a [u8], + ) -> future::BoxFuture<'a, Result<(), std::io::Error>> { + Box::pin(async move { + self.socket.send_to(buffer, &*self.address).await?; + Ok(()) + }) + } + + fn read_data(&mut self) -> future::BoxFuture, std::io::Error>> { + Box::pin(async move { + let size = self.socket.recv(&mut self.buffer).await?; + Ok(self.buffer[..size].into()) + }) + } +} + +/// An implementation of DataStreamPool based on UDP. +struct UdpDataStreamPool { + socket: UdpSocket, +} + +impl UdpDataStreamPool { + async fn new() -> Result { + let socket = UdpSocket::bind(&"0.0.0.0:0").await?; + Ok(Self { socket }) + } +} + +impl DataStreamPool for UdpDataStreamPool { + fn send_data_to<'a>( + &'a mut self, + buffer: &'a [u8], + address: &'a String, + ) -> future::BoxFuture<'a, Result<(), std::io::Error>> { + Box::pin(async move { + self.socket.send_to(buffer, address).await?; + Ok(()) + }) + } +} + +// Server implementation for UDP. +impl NetworkProtocol { + async fn run_udp_server( + mut socket: UdpSocket, + mut state: S, + mut exit_future: futures::channel::oneshot::Receiver<()>, + buffer_size: usize, + ) -> Result<(), std::io::Error> + where + S: MessageHandler + Send + 'static, + { + let mut buffer = vec![0; buffer_size]; + loop { + let (size, peer) = + match future::select(exit_future, Box::pin(socket.recv_from(&mut buffer))).await { + future::Either::Left(_) => break, + future::Either::Right((value, new_exit_future)) => { + exit_future = new_exit_future; + value? + } + }; + if let Some(reply) = state.handle_message(&buffer[..size]).await { + let status = socket.send_to(&reply[..], &peer).await; + if let Err(error) = status { + error!("Failed to send query response: {}", error); + } + } + } + Ok(()) + } +} + +/// An implementation of DataStream based on TCP. +struct TcpDataStream { + stream: TcpStream, + max_data_size: usize, +} + +impl TcpDataStream { + async fn connect(address: String, max_data_size: usize) -> Result { + let stream = TcpStream::connect(address).await?; + stream.set_send_buffer_size(max_data_size)?; + stream.set_recv_buffer_size(max_data_size)?; + Ok(Self { + stream, + max_data_size, + }) + } + + async fn tcp_write_data(stream: &mut S, buffer: &[u8]) -> Result<(), std::io::Error> + where + S: AsyncWrite + Unpin, + { + stream + .write_all(&u32::to_le_bytes( + buffer + .len() + .try_into() + .expect("length must not exceed u32::MAX"), + )) + .await?; + stream.write_all(buffer).await + } + + async fn tcp_read_data(stream: &mut S, max_size: usize) -> Result, std::io::Error> + where + S: AsyncRead + Unpin, + { + let mut size_buf = [0u8; 4]; + stream.read_exact(&mut size_buf).await?; + let size = u32::from_le_bytes(size_buf); + if size as usize > max_size { + return Err(io::Error::new( + io::ErrorKind::Other, + "Message size exceeds buffer size", + )); + } + let mut buf = vec![0u8; size as usize]; + stream.read_exact(&mut buf).await?; + Ok(buf) + } +} + +impl DataStream for TcpDataStream { + fn write_data<'a>( + &'a mut self, + buffer: &'a [u8], + ) -> future::BoxFuture<'a, Result<(), std::io::Error>> { + Box::pin(Self::tcp_write_data(&mut self.stream, buffer)) + } + + fn read_data(&mut self) -> future::BoxFuture, std::io::Error>> { + Box::pin(Self::tcp_read_data(&mut self.stream, self.max_data_size)) + } +} + +/// An implementation of DataStreamPool based on TCP. +struct TcpDataStreamPool { + streams: HashMap, +} + +impl TcpDataStreamPool { + async fn new() -> Result { + let streams = HashMap::new(); + Ok(Self { streams }) + } + + async fn get_stream(&mut self, address: &String) -> Result<&mut TcpStream, io::Error> { + if !self.streams.contains_key(address) { + match TcpStream::connect(address).await { + Ok(s) => { + self.streams.insert(address.clone(), s); + } + Err(error) => { + error!("Failed to open connection to {}: {}", address, error); + return Err(error); + } + }; + }; + Ok(self.streams.get_mut(address).unwrap()) + } +} + +impl DataStreamPool for TcpDataStreamPool { + fn send_data_to<'a>( + &'a mut self, + buffer: &'a [u8], + address: &'a String, + ) -> future::BoxFuture<'a, Result<(), std::io::Error>> { + Box::pin(async move { + let stream = self.get_stream(address).await?; + TcpDataStream::tcp_write_data(stream, buffer).await + }) + } +} + +// Server implementation for TCP. +impl NetworkProtocol { + async fn run_tcp_server( + mut listener: TcpListener, + state: S, + mut exit_future: futures::channel::oneshot::Receiver<()>, + buffer_size: usize, + ) -> Result<(), std::io::Error> + where + S: MessageHandler + Send + 'static, + { + let guarded_state = Arc::new(futures::lock::Mutex::new(state)); + loop { + let (mut socket, _) = + match future::select(exit_future, Box::pin(listener.accept())).await { + future::Either::Left(_) => break, + future::Either::Right((value, new_exit_future)) => { + exit_future = new_exit_future; + value? + } + }; + socket.set_send_buffer_size(buffer_size)?; + socket.set_recv_buffer_size(buffer_size)?; + let guarded_state = guarded_state.clone(); + tokio::spawn(async move { + loop { + let buffer = match TcpDataStream::tcp_read_data(&mut socket, buffer_size).await + { + Ok(buffer) => buffer, + Err(err) => { + // We expect an EOF error at the end. + if err.kind() != io::ErrorKind::UnexpectedEof { + error!("Error while reading TCP stream: {}", err); + } + break; + } + }; + + if let Some(reply) = + guarded_state.lock().await.handle_message(&buffer[..]).await + { + let status = TcpDataStream::tcp_write_data(&mut socket, &reply[..]).await; + if let Err(error) = status { + error!("Failed to send query response: {}", error); + } + }; + } + }); + } + Ok(()) + } +} diff --git a/rust/fastpay/src/unit_tests/transport_tests.rs b/rust/fastpay/src/unit_tests/transport_tests.rs new file mode 100644 index 0000000000000..e77170657e476 --- /dev/null +++ b/rust/fastpay/src/unit_tests/transport_tests.rs @@ -0,0 +1,93 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use net2; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; +use tokio::runtime::Runtime; +use tokio::time::timeout; + +async fn get_new_local_address() -> Result { + let builder = net2::TcpBuilder::new_v4()?; + builder.reuse_address(true)?; + builder.bind("0.0.0.0:0")?; + Ok(format!("{}", builder.local_addr()?)) +} + +struct TestService { + counter: Arc, +} + +impl TestService { + fn new(counter: Arc) -> Self { + TestService { counter } + } +} + +impl MessageHandler for TestService { + fn handle_message<'a>( + &'a mut self, + buffer: &'a [u8], + ) -> future::BoxFuture<'a, Option>> { + self.counter.fetch_add(buffer.len(), Ordering::Relaxed); + Box::pin(async move { Some(Vec::from(buffer)) }) + } +} + +async fn test_server(protocol: NetworkProtocol) -> Result<(usize, usize), std::io::Error> { + let address = get_new_local_address().await.unwrap(); + + let counter = Arc::new(AtomicUsize::new(0)); + let mut received = 0; + + let server = protocol + .spawn_server(&address, TestService::new(counter.clone()), 100) + .await?; + + let mut client = protocol.connect(address.clone(), 1000).await?; + client.write_data(b"abcdef").await?; + received += client.read_data().await?.len(); + client.write_data(b"abcd").await?; + received += client.read_data().await?.len(); + + // Use a second connection (here pooled). + let mut pool = protocol.make_outgoing_connection_pool().await?; + pool.send_data_to(b"abc", &address).await?; + + // Try to read data on the first connection (should fail). + received += timeout(Duration::from_millis(500), client.read_data()) + .await + .unwrap_or(Ok(Vec::new()))? + .len(); + + // Attempt to gracefully kill server. + server.kill().await?; + + timeout(Duration::from_millis(500), client.write_data(b"abcd")) + .await + .unwrap_or(Ok(()))?; + received += timeout(Duration::from_millis(500), client.read_data()) + .await + .unwrap_or(Ok(Vec::new()))? + .len(); + + Ok((counter.load(Ordering::Relaxed), received)) +} + +#[test] +fn udp_server() { + let mut rt = Runtime::new().unwrap(); + let (processed, received) = rt.block_on(test_server(NetworkProtocol::Udp)).unwrap(); + assert_eq!(processed, 13); + assert_eq!(received, 10); +} + +#[test] +fn tcp_server() { + let mut rt = Runtime::new().unwrap(); + let (processed, received) = rt.block_on(test_server(NetworkProtocol::Tcp)).unwrap(); + // Active TCP connections are allowed to finish before the server is gracefully killed. + assert_eq!(processed, 17); + assert_eq!(received, 14); +} diff --git a/rust/fastpay_core/Cargo.toml b/rust/fastpay_core/Cargo.toml new file mode 100644 index 0000000000000..4015586cfb2b1 --- /dev/null +++ b/rust/fastpay_core/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fastpay_core" +version = "0.1.0" +authors = ["Libra "] +publish = false +edition = "2018" + +[dependencies] +base64 = "0.12.0" +bincode = "1.2.1" +failure = "0.1.7" +futures = "0.3.4" +rand = "0.7.3" +serde = { version = "1.0.106", features = ["derive"] } +tokio = { version = "0.2.18", features = ["full"] } +ed25519-dalek = { version = "1.0.0-pre.3", features = ["batch"] } diff --git a/rust/fastpay_core/src/authority.rs b/rust/fastpay_core/src/authority.rs new file mode 100644 index 0000000000000..0ef7878ea388b --- /dev/null +++ b/rust/fastpay_core/src/authority.rs @@ -0,0 +1,379 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use crate::base_types::*; +use crate::committee::Committee; +use crate::error::FastPayError; +use crate::messages::*; +use std::collections::BTreeMap; +use std::convert::TryInto; + +#[cfg(test)] +#[path = "unit_tests/authority_tests.rs"] +mod authority_tests; + +#[derive(Eq, PartialEq, Debug)] +pub struct AccountOffchainState { + /// Balance of the FastPay account. + pub balance: Balance, + /// Sequence number tracking spending actions. + pub next_sequence_number: SequenceNumber, + /// Whether we have signed a transfer for this sequence number already. + pub pending_confirmation: Option, + /// All confirmed certificates for this sender. + pub confirmed_log: Vec, + /// All executed Primary synchronization orders for this recipient. + pub synchronization_log: Vec, + /// All confirmed certificates as a receiver. + pub received_log: Vec, +} + +pub struct AuthorityState { + /// The name of this autority. + pub name: AuthorityName, + /// Committee of this FastPay instance. + pub committee: Committee, + /// The signature key of the authority. + pub secret: SecretKey, + /// Offchain states of FastPay accounts. + pub accounts: BTreeMap, + /// The latest transaction index of the blockchain that the authority has seen. + pub last_transaction_index: VersionNumber, + /// The sharding ID of this authority shard. 0 if one shard. + pub shard_id: ShardId, + /// The number of shards. 1 if single shard. + pub number_of_shards: u32, +} + +/// Interface provided by each (shard of an) authority. +/// All commands return either the current account info or an error. +/// Repeating commands produces no changes and returns no error. +pub trait Authority { + /// Initiate a new transfer to a FastPay or Primary account. + fn handle_transfer_order( + &mut self, + order: TransferOrder, + ) -> Result; + + /// Confirm a transfer to a FastPay or Primary account. + fn handle_confirmation_order( + &mut self, + order: ConfirmationOrder, + ) -> Result<(AccountInfoResponse, Option), FastPayError>; + + /// Force synchronization to finalize transfers from Primary to FastPay. + fn handle_primary_synchronization_order( + &mut self, + order: PrimarySynchronizationOrder, + ) -> Result; + + /// Handle information requests for this account. + fn handle_account_info_request( + &self, + request: AccountInfoRequest, + ) -> Result; + + /// Handle cross updates from another shard of the same authority. + /// This relies on deliver-once semantics of a trusted channel between shards. + fn handle_cross_shard_recipient_commit( + &mut self, + certificate: CertifiedTransferOrder, + ) -> Result<(), FastPayError>; +} + +impl Authority for AuthorityState { + /// Initiate a new transfer. + fn handle_transfer_order( + &mut self, + order: TransferOrder, + ) -> Result { + // Check the sender's signature and retrieve the transfer data. + fp_ensure!( + self.in_shard(&order.transfer.sender), + FastPayError::WrongShard + ); + order.check_signature()?; + let transfer = &order.transfer; + let sender = transfer.sender; + fp_ensure!( + transfer.sequence_number <= SequenceNumber::max(), + FastPayError::InvalidSequenceNumber + ); + fp_ensure!( + transfer.amount > Amount::zero(), + FastPayError::IncorrectTransferAmount + ); + match self.accounts.get_mut(&sender) { + None => fp_bail!(FastPayError::UnknownSenderAccount), + Some(account) => { + if let Some(pending_confirmation) = &account.pending_confirmation { + fp_ensure!( + &pending_confirmation.value.transfer == transfer, + FastPayError::PreviousTransferMustBeConfirmedFirst { + pending_confirmation: pending_confirmation.value.clone() + } + ); + // This exact transfer order was already signed. Return the previous value. + return Ok(account.make_account_info(sender)); + } + fp_ensure!( + account.next_sequence_number == transfer.sequence_number, + FastPayError::UnexpectedSequenceNumber + ); + fp_ensure!( + account.balance >= transfer.amount.into(), + FastPayError::InsufficientFunding { + current_balance: account.balance + } + ); + let signed_order = SignedTransferOrder::new(order, self.name, &self.secret); + account.pending_confirmation = Some(signed_order.clone()); + Ok(account.make_account_info(sender)) + } + } + } + + /// Confirm a transfer. + fn handle_confirmation_order( + &mut self, + confirmation_order: ConfirmationOrder, + ) -> Result<(AccountInfoResponse, Option), FastPayError> { + let certificate = confirmation_order.transfer_certificate; + // Check the certificate and retrieve the transfer data. + fp_ensure!( + self.in_shard(&certificate.value.transfer.sender), + FastPayError::WrongShard + ); + certificate.check(&self.committee)?; + let transfer = certificate.value.transfer.clone(); + + // First we copy all relevant data from sender. + let mut sender_account = self + .accounts + .entry(transfer.sender) + .or_insert(AccountOffchainState::new()); + let mut sender_sequence_number = sender_account.next_sequence_number; + let mut sender_balance = sender_account.balance; + + // Check and update the copied state + if sender_sequence_number < transfer.sequence_number { + fp_bail!(FastPayError::MissingEalierConfirmations { + current_sequence_number: sender_sequence_number + }); + } + if sender_sequence_number > transfer.sequence_number { + // Transfer was already confirmed. + return Ok((sender_account.make_account_info(transfer.sender), None)); + } + sender_balance = sender_balance.sub(transfer.amount.into())?; + sender_sequence_number = sender_sequence_number.increment()?; + + // Commit sender state back to the database (Must never fail!) + sender_account.balance = sender_balance; + sender_account.next_sequence_number = sender_sequence_number; + sender_account.pending_confirmation = None; + sender_account.confirmed_log.push(certificate.clone()); + let info = sender_account.make_account_info(transfer.sender); + + // Update FastPay recipient state locally or issue a cross-shard update (Must never fail!) + let recipient = match transfer.recipient { + Address::FastPay(recipient) => recipient, + Address::Primary(_) => { + // Nothing else to do for Primary recipients. + return Ok((info, None)); + } + }; + // If the recipient is in the same shard, read and update the account. + if self.in_shard(&recipient) { + let recipient_account = self + .accounts + .entry(recipient) + .or_insert(AccountOffchainState::new()); + recipient_account.balance = recipient_account + .balance + .add(transfer.amount.into()) + .unwrap_or(Balance::max()); + recipient_account.received_log.push(certificate.clone()); + // Done updating recipient. + return Ok((info, None)); + } + // Otherwise, we need to send a cross-shard update. + let cross_shard = Some(CrossShardUpdate { + shard_id: self.which_shard(&recipient), + transfer_certificate: certificate, + }); + Ok((info, cross_shard)) + } + + // NOTE: Need to rely on deliver-once semantics from comms channel + fn handle_cross_shard_recipient_commit( + &mut self, + certificate: CertifiedTransferOrder, + ) -> Result<(), FastPayError> { + // TODO: check certificate again? + let transfer = &certificate.value.transfer; + + let recipient = match transfer.recipient { + Address::FastPay(recipient) => recipient, + Address::Primary(_) => { + fp_bail!(FastPayError::InvalidCrossShardUpdate); + } + }; + fp_ensure!(self.in_shard(&recipient), FastPayError::WrongShard); + let recipient_account = self + .accounts + .entry(recipient) + .or_insert(AccountOffchainState::new()); + recipient_account.balance = recipient_account + .balance + .add(transfer.amount.into()) + .unwrap_or(Balance::max()); + recipient_account.received_log.push(certificate); + Ok(()) + } + + /// Finalize a transfer from Primary. + fn handle_primary_synchronization_order( + &mut self, + order: PrimarySynchronizationOrder, + ) -> Result { + // Update recipient state; note that the blockchain client is trusted. + let recipient = order.recipient; + fp_ensure!(self.in_shard(&recipient), FastPayError::WrongShard); + + let recipient_account = self + .accounts + .entry(recipient) + .or_insert(AccountOffchainState::new()); + if order.transaction_index <= self.last_transaction_index { + // Ignore old transaction index. + return Ok(recipient_account.make_account_info(recipient)); + } + fp_ensure!( + order.transaction_index == self.last_transaction_index.increment()?, + FastPayError::UnexpectedTransactionIndex + ); + let recipient_balance = recipient_account.balance.add(order.amount.into())?; + let last_transaction_index = self.last_transaction_index.increment()?; + recipient_account.balance = recipient_balance; + recipient_account.synchronization_log.push(order); + self.last_transaction_index = last_transaction_index; + Ok(recipient_account.make_account_info(recipient)) + } + + fn handle_account_info_request( + &self, + request: AccountInfoRequest, + ) -> Result { + fp_ensure!(self.in_shard(&request.sender), FastPayError::WrongShard); + let account = self.account_state(&request.sender)?; + let mut response = account.make_account_info(request.sender); + if let Some(seq) = request.request_sequence_number { + if let Some(cert) = account.confirmed_log.get(usize::from(seq)) { + response.requested_certificate = Some(cert.clone()); + } else { + fp_bail!(FastPayError::CertificateNotfound) + } + } + if let Some(idx) = request.request_received_transfers_excluding_first_nth { + response.requested_received_transfers = account.received_log[idx..].to_vec(); + } + Ok(response) + } +} + +impl AccountOffchainState { + pub fn new() -> Self { + Self { + balance: Balance::zero(), + next_sequence_number: SequenceNumber::new(), + pending_confirmation: None, + confirmed_log: Vec::new(), + synchronization_log: Vec::new(), + received_log: Vec::new(), + } + } + + fn make_account_info(&self, sender: FastPayAddress) -> AccountInfoResponse { + AccountInfoResponse { + sender, + balance: self.balance, + next_sequence_number: self.next_sequence_number, + pending_confirmation: self.pending_confirmation.clone(), + requested_certificate: None, + requested_received_transfers: Vec::new(), + } + } + + #[cfg(test)] + pub fn new_with_balance(balance: Balance, received_log: Vec) -> Self { + Self { + balance, + next_sequence_number: SequenceNumber::new(), + pending_confirmation: None, + confirmed_log: Vec::new(), + synchronization_log: Vec::new(), + received_log, + } + } +} + +impl AuthorityState { + pub fn new(committee: Committee, name: AuthorityName, secret: SecretKey) -> Self { + AuthorityState { + committee, + name, + secret, + accounts: BTreeMap::new(), + last_transaction_index: VersionNumber::new(), + shard_id: 0, + number_of_shards: 1, + } + } + + pub fn new_shard( + committee: Committee, + name: AuthorityName, + secret: SecretKey, + shard_id: u32, + number_of_shards: u32, + ) -> Self { + AuthorityState { + committee, + name, + secret, + accounts: BTreeMap::new(), + last_transaction_index: VersionNumber::new(), + shard_id, + number_of_shards, + } + } + + pub fn in_shard(&self, address: &FastPayAddress) -> bool { + self.which_shard(address) == self.shard_id + } + + pub fn get_shard(num_shards: u32, address: &FastPayAddress) -> u32 { + const LAST_INTEGER_INDEX: usize = std::mem::size_of::() - 4; + u32::from_le_bytes(address.0[LAST_INTEGER_INDEX..].try_into().expect("4 bytes")) + % num_shards + } + + pub fn which_shard(&self, address: &FastPayAddress) -> u32 { + Self::get_shard(self.number_of_shards, address) + } + + fn account_state( + &self, + address: &FastPayAddress, + ) -> Result<&AccountOffchainState, FastPayError> { + self.accounts + .get(address) + .ok_or_else(|| FastPayError::UnknownSenderAccount) + } + + #[cfg(test)] + pub fn accounts_mut(&mut self) -> &mut BTreeMap { + &mut self.accounts + } +} diff --git a/rust/fastpay_core/src/base_types.rs b/rust/fastpay_core/src/base_types.rs new file mode 100644 index 0000000000000..da4c58ebfda50 --- /dev/null +++ b/rust/fastpay_core/src/base_types.rs @@ -0,0 +1,371 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use base64; +use ed25519_dalek as dalek; +use ed25519_dalek::Digest; +use rand::rngs::OsRng; +use serde::{Deserialize, Serialize}; +use std::convert::{TryFrom, TryInto}; + +use crate::error::FastPayError; + +#[cfg(test)] +#[path = "unit_tests/base_types_tests.rs"] +mod base_types_tests; + +#[derive( + Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Default, Debug, Serialize, Deserialize, +)] +pub struct Amount(u64); +#[derive( + Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Default, Debug, Serialize, Deserialize, +)] +pub struct Balance(i128); +#[derive( + Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Default, Debug, Serialize, Deserialize, +)] +pub struct SequenceNumber(u64); + +pub type ShardId = u32; +pub type VersionNumber = SequenceNumber; + +#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Hash, Default, Debug, Serialize, Deserialize)] +pub struct UserData(pub Option<[u8; 32]>); + +// Ensure Secrets are not copyable and movable to control where they are in memory +// TODO: Keep the native Dalek keypair type instead of bytes. +pub struct SecretKey(pub [u8; dalek::KEYPAIR_LENGTH]); + +#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Serialize, Deserialize)] +pub struct EdPublicKeyBytes(pub [u8; dalek::PUBLIC_KEY_LENGTH]); + +pub type PrimaryAddress = EdPublicKeyBytes; +pub type FastPayAddress = EdPublicKeyBytes; +pub type AuthorityName = EdPublicKeyBytes; + +pub fn get_key_pair() -> (FastPayAddress, SecretKey) { + let mut csprng = OsRng; + let keypair = dalek::Keypair::generate(&mut csprng); + ( + EdPublicKeyBytes(keypair.public.to_bytes()), + SecretKey(keypair.to_bytes()), + ) +} + +pub fn address_as_base64(key: &EdPublicKeyBytes, serializer: S) -> Result +where + S: serde::ser::Serializer, +{ + serializer.serialize_str(&encode_address(key)) +} + +pub fn address_from_base64<'de, D>(deserializer: D) -> Result +where + D: serde::de::Deserializer<'de>, +{ + let s = String::deserialize(deserializer)?; + let value = decode_address(&s).map_err(|err| serde::de::Error::custom(err.to_string()))?; + Ok(value) +} + +pub fn encode_address(key: &EdPublicKeyBytes) -> String { + base64::encode(&key.0[..]) +} + +pub fn decode_address(s: &String) -> Result { + let value = base64::decode(s)?; + let mut address = [0u8; dalek::PUBLIC_KEY_LENGTH]; + address.copy_from_slice(&value[..dalek::PUBLIC_KEY_LENGTH]); + Ok(EdPublicKeyBytes(address)) +} + +#[cfg(test)] +pub fn dbg_addr(name: u8) -> FastPayAddress { + let addr = [name; dalek::PUBLIC_KEY_LENGTH]; + EdPublicKeyBytes(addr) +} + +// TODO: Remove Eq, PartialEq, Ord, PartialOrd and Hash from signatures. +#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Serialize, Deserialize)] +pub struct Signature { + pub part1: [u8; dalek::SIGNATURE_LENGTH / 2], + pub part2: [u8; dalek::SIGNATURE_LENGTH / 2], +} + +// Zero the secret key when unallocating. +impl Drop for SecretKey { + fn drop(&mut self) { + for i in 0..dalek::KEYPAIR_LENGTH { + self.0[i] = 0; + } + } +} + +impl SecretKey { + pub fn copy(&self) -> SecretKey { + let mut sec_bytes = SecretKey { + 0: [0; dalek::KEYPAIR_LENGTH], + }; + sec_bytes.0.copy_from_slice(&(self.0)[..]); + sec_bytes + } +} + +impl Serialize for SecretKey { + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { + serializer.serialize_str(&base64::encode(&self.0[..])) + } +} + +impl<'de> Deserialize<'de> for SecretKey { + fn deserialize(deserializer: D) -> Result + where + D: serde::de::Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + let value = base64::decode(&s).map_err(|err| serde::de::Error::custom(err.to_string()))?; + let mut key = [0u8; dalek::KEYPAIR_LENGTH]; + key.copy_from_slice(&value[..dalek::KEYPAIR_LENGTH]); + Ok(SecretKey(key)) + } +} + +impl std::fmt::Debug for Signature { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { + let s = base64::encode(&self.to_array()[..]); + write!(f, "{}", s)?; + Ok(()) + } +} + +impl std::fmt::Debug for EdPublicKeyBytes { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { + let s = base64::encode(&self.0); + write!(f, "{}", s)?; + Ok(()) + } +} + +impl Amount { + pub fn zero() -> Self { + Amount(0) + } + + pub fn add(&self, other: Self) -> Result { + let val = self.0.checked_add(other.0); + match val { + None => Err(FastPayError::AmountOverflow), + Some(val) => Ok(Self(val)), + } + } + + pub fn sub(&self, other: Self) -> Result { + let val = self.0.checked_sub(other.0); + match val { + None => Err(FastPayError::AmountUnderflow), + Some(val) => Ok(Self(val)), + } + } +} + +impl Balance { + pub fn zero() -> Self { + Balance(0) + } + + pub fn max() -> Self { + Balance(std::i128::MAX) + } + + pub fn add(&self, other: Self) -> Result { + let val = self.0.checked_add(other.0); + match val { + None => Err(FastPayError::BalanceOverflow), + Some(val) => Ok(Self(val)), + } + } + + pub fn sub(&self, other: Self) -> Result { + let val = self.0.checked_sub(other.0); + match val { + None => Err(FastPayError::BalanceUnderflow), + Some(val) => Ok(Self(val)), + } + } +} + +impl From for u64 { + fn from(val: Amount) -> Self { + val.0 + } +} + +impl From for Balance { + fn from(val: Amount) -> Self { + Balance(val.0 as i128) + } +} + +impl TryFrom for Amount { + type Error = std::num::TryFromIntError; + + fn try_from(val: Balance) -> Result { + Ok(Amount(val.0.try_into()?)) + } +} + +impl SequenceNumber { + pub fn new() -> Self { + SequenceNumber(0) + } + + pub fn max() -> Self { + SequenceNumber(0x7fffffffffffffff) + } + + pub fn increment(&self) -> Result { + let val = self.0.checked_add(1); + match val { + None => Err(FastPayError::SequenceOverflow), + Some(val) => Ok(Self(val)), + } + } + + pub fn decrement(&self) -> Result { + let val = self.0.checked_sub(1); + match val { + None => Err(FastPayError::SequenceUnderflow), + Some(val) => Ok(Self(val)), + } + } +} + +impl From for u64 { + fn from(val: SequenceNumber) -> Self { + val.0 + } +} + +impl From for Amount { + fn from(value: u64) -> Self { + Amount(value) + } +} + +impl From for Balance { + fn from(value: i128) -> Self { + Balance(value) + } +} + +impl From for SequenceNumber { + fn from(value: u64) -> Self { + SequenceNumber(value) + } +} + +impl From for usize { + fn from(value: SequenceNumber) -> Self { + value.0 as usize + } +} + +pub trait Digestible { + fn digest(self: &Self) -> [u8; 32]; +} + +impl Digestible for [u8; 5] { + fn digest(self: &[u8; 5]) -> [u8; 32] { + let mut h = dalek::Sha512::new(); + let mut hash = [0u8; 64]; + let mut digest = [0u8; 32]; + h.input(&self); + hash.copy_from_slice(h.result().as_slice()); + digest.copy_from_slice(&hash[..32]); + digest + } +} + +impl Signature { + pub fn to_array(&self) -> [u8; 64] { + let mut sig: [u8; 64] = [0; 64]; + sig[0..32].clone_from_slice(&self.part1); + sig[32..64].clone_from_slice(&self.part2); + sig + } + + pub fn new(value: &T, secret: &SecretKey) -> Self + where + T: Digestible, + { + let message = value.digest(); + let key_pair = dalek::Keypair::from_bytes(&secret.0).unwrap(); + let signature = key_pair.sign(&message); + let sig_bytes = signature.to_bytes(); + + let mut part1 = [0; 32]; + let mut part2 = [0; 32]; + part1.clone_from_slice(&sig_bytes[0..32]); + part2.clone_from_slice(&sig_bytes[32..64]); + + Signature { part1, part2 } + } + + fn check_internal( + &self, + value: &T, + author: FastPayAddress, + ) -> Result<(), dalek::SignatureError> + where + T: Digestible, + { + let message = value.digest(); + let public_key = dalek::PublicKey::from_bytes(&author.0)?; + let sig = self.to_array(); + let dalex_sig = dalek::Signature::from_bytes(&sig)?; + public_key.verify(&message, &dalex_sig) + } + + pub fn check(&self, value: &T, author: FastPayAddress) -> Result<(), FastPayError> + where + T: Digestible, + { + self.check_internal(value, author) + .map_err(|error| FastPayError::InvalidSignature { + error: format!("{}", error), + }) + } + + fn verify_batch_internal<'a, T, I>(value: &'a T, votes: I) -> Result<(), dalek::SignatureError> + where + T: Digestible, + I: IntoIterator, + { + let msg: &[u8] = &value.digest(); + let mut messages: Vec<&[u8]> = Vec::new(); + let mut signatures: Vec = Vec::new(); + let mut public_keys: Vec = Vec::new(); + for (addr, sig) in votes.into_iter() { + messages.push(msg); + signatures.push(dalek::Signature::from_bytes(&sig.to_array())?); + public_keys.push(dalek::PublicKey::from_bytes(&addr.0)?); + } + dalek::verify_batch(&messages[..], &signatures[..], &public_keys[..]) + } + + pub fn verify_batch<'a, T, I>(value: &'a T, votes: I) -> Result<(), FastPayError> + where + T: Digestible, + I: IntoIterator, + { + Signature::verify_batch_internal(value, votes).map_err(|error| { + FastPayError::InvalidSignature { + error: format!("{}", error), + } + }) + } +} diff --git a/rust/fastpay_core/src/client.rs b/rust/fastpay_core/src/client.rs new file mode 100644 index 0000000000000..77009969f1304 --- /dev/null +++ b/rust/fastpay_core/src/client.rs @@ -0,0 +1,692 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use crate::base_types::*; +use crate::committee::Committee; +use crate::downloader::*; +use crate::error::FastPayError; +use crate::messages::*; + +use futures::{future, StreamExt}; +use rand::seq::SliceRandom; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::convert::TryFrom; + +#[cfg(test)] +#[path = "unit_tests/client_tests.rs"] +mod client_tests; + +pub type AsyncResult<'a, T, E> = future::BoxFuture<'a, Result>; + +pub trait AuthorityClient { + /// Initiate a new transfer to a FastPay or Primary account. + fn handle_transfer_order( + &mut self, + order: TransferOrder, + ) -> AsyncResult; + + /// Confirm a transfer to a FastPay or Primary account. + fn handle_confirmation_order( + &mut self, + order: ConfirmationOrder, + ) -> AsyncResult; + + /// Handle information requests for this account. + fn handle_account_info_request( + &mut self, + request: AccountInfoRequest, + ) -> AsyncResult; +} + +pub struct ClientState { + /// Our FastPay address. + address: FastPayAddress, + /// Our signature key. + secret: SecretKey, + /// Our FastPay committee. + committee: Committee, + /// How to talk to this committee. + authority_clients: HashMap, + /// Expected sequence number for the next certified transfer. + /// This is also the number of transfer certificates that we have created. + next_sequence_number: SequenceNumber, + /// Pending transfer. + pending_transfer: Option, + + // The remaining fields are used to minimize networking, and may not always be persisted locally. + /// Transfer certificates that we have created ("sent"). + /// Normally, `sent_certificates` should contain one certificate for each index in `0..next_sequence_number`. + sent_certificates: Vec, + /// Known received certificates, indexed by sender and sequence number. + /// TODO: API to search and download yet unknown `received_certificates`. + received_certificates: BTreeMap<(FastPayAddress, SequenceNumber), CertifiedTransferOrder>, + /// The known spendable balance (including a possible initial funding, excluding unknown sent + /// or received certificates). + balance: Balance, +} + +// Operations are considered successful when they successfully reach a quorum of authorities. +pub trait Client { + /// Send money to a FastPay account. + fn transfer_to_fastpay( + &mut self, + amount: Amount, + recipient: FastPayAddress, + user_data: UserData, + ) -> AsyncResult; + + /// Send money to a Primary account. + fn transfer_to_primary( + &mut self, + amount: Amount, + recipient: PrimaryAddress, + user_data: UserData, + ) -> AsyncResult; + + /// Receive money from FastPay. + fn receive_from_fastpay( + &mut self, + certificate: CertifiedTransferOrder, + ) -> AsyncResult<(), failure::Error>; + + /// Send money to a FastPay account. + /// Do not check balance. (This may block the client) + /// Do not confirm the transaction. + fn transfer_to_fastpay_unsafe_unconfirmed( + &mut self, + amount: Amount, + recipient: FastPayAddress, + user_data: UserData, + ) -> AsyncResult; + + /// Find how much money we can spend. + /// TODO: Currently, this value only reflects received transfers that were + /// locally processed by `receive_from_fastpay`. + fn get_spendable_amount(&mut self) -> AsyncResult; +} + +impl ClientState { + pub fn new( + address: FastPayAddress, + secret: SecretKey, + committee: Committee, + authority_clients: HashMap, + next_sequence_number: SequenceNumber, + sent_certificates: Vec, + received_certificates: Vec, + balance: Balance, + ) -> Self { + Self { + address, + secret, + committee, + authority_clients, + next_sequence_number, + pending_transfer: None, + sent_certificates, + received_certificates: received_certificates + .into_iter() + .map(|cert| (cert.key(), cert)) + .collect(), + balance, + } + } + + pub fn address(&self) -> FastPayAddress { + self.address + } + + pub fn next_sequence_number(&self) -> SequenceNumber { + self.next_sequence_number + } + + pub fn balance(&self) -> Balance { + self.balance + } + + pub fn pending_transfer(&self) -> &Option { + &self.pending_transfer + } + + pub fn sent_certificates(&self) -> &Vec { + &self.sent_certificates + } + + pub fn received_certificates(&self) -> impl Iterator { + self.received_certificates.values() + } +} + +#[derive(Clone)] +struct CertificateRequester { + committee: Committee, + authority_clients: Vec, + sender: FastPayAddress, +} + +impl CertificateRequester { + fn new(committee: Committee, authority_clients: Vec, sender: FastPayAddress) -> Self { + Self { + committee, + authority_clients, + sender, + } + } +} + +impl Requester for CertificateRequester +where + A: AuthorityClient + Send + Sync + 'static + Clone, +{ + type Key = SequenceNumber; + type Value = Result; + + /// Try to find a certificate for the given sender and sequence number. + fn query( + &mut self, + sequence_number: SequenceNumber, + ) -> AsyncResult { + Box::pin(async move { + let request = AccountInfoRequest { + sender: self.sender, + request_sequence_number: Some(sequence_number), + request_received_transfers_excluding_first_nth: None, + }; + // Sequentially try each authority in random order. + self.authority_clients.shuffle(&mut rand::thread_rng()); + for client in self.authority_clients.iter_mut() { + let result = client.handle_account_info_request(request.clone()).await; + if let Ok(AccountInfoResponse { + requested_certificate: Some(certificate), + .. + }) = &result + { + if certificate.check(&self.committee).is_ok() { + let transfer = &certificate.value.transfer; + if transfer.sender == self.sender + && transfer.sequence_number == sequence_number + { + return Ok(certificate.clone()); + } + } + } + } + Err(FastPayError::ErrorWhileRequestingCertificate) + }) + } +} + +/// Used for communicate_transfers +#[derive(Clone)] +enum CommunicateAction { + SendOrder(TransferOrder), + SynchronizeNextSequenceNumber(SequenceNumber), +} + +impl ClientState +where + A: AuthorityClient + Send + Sync + 'static + Clone, +{ + #[cfg(test)] + async fn request_certificate( + &mut self, + sender: FastPayAddress, + sequence_number: SequenceNumber, + ) -> Result { + CertificateRequester::new( + self.committee.clone(), + self.authority_clients.values().cloned().collect(), + sender, + ) + .query(sequence_number) + .await + } + + /// Find the highest sequence number that is known to a quorum of authorities. + /// NOTE: This is only reliable in the synchronous model, with a sufficient timeout value. + #[cfg(test)] + async fn get_strong_majority_sequence_number( + &mut self, + sender: FastPayAddress, + ) -> SequenceNumber { + let request = AccountInfoRequest { + sender, + request_sequence_number: None, + request_received_transfers_excluding_first_nth: None, + }; + let numbers: futures::stream::FuturesUnordered<_> = self + .authority_clients + .iter_mut() + .map(|(name, client)| { + let fut = client.handle_account_info_request(request.clone()); + let name = name.clone(); + async move { + match fut.await { + Ok(info) => Some((name, info.next_sequence_number)), + _ => None, + } + } + }) + .collect(); + self.committee.get_strong_majority_lower_bound( + numbers.filter_map(|x| async move { x }).collect().await, + ) + } + + /// Find the highest balance that is backed by a quorum of authorities. + /// NOTE: This is only reliable in the synchronous model, with a sufficient timeout value. + #[cfg(test)] + async fn get_strong_majority_balance(&mut self) -> Balance { + let request = AccountInfoRequest { + sender: self.address, + request_sequence_number: None, + request_received_transfers_excluding_first_nth: None, + }; + let numbers: futures::stream::FuturesUnordered<_> = self + .authority_clients + .iter_mut() + .map(|(name, client)| { + let fut = client.handle_account_info_request(request.clone()); + let name = name.clone(); + async move { + match fut.await { + Ok(info) => Some((name, info.balance)), + _ => None, + } + } + }) + .collect(); + self.committee.get_strong_majority_lower_bound( + numbers.filter_map(|x| async move { x }).collect().await, + ) + } + + /// Execute a sequence of actions in parallel for a quorum of authorities. + async fn communicate_with_quorum<'a, V, F>( + &'a mut self, + execute: F, + ) -> Result, failure::Error> + where + F: Fn(AuthorityName, &'a mut A) -> AsyncResult<'a, V, FastPayError> + Clone, + { + let committee = &self.committee; + let authority_clients = &mut self.authority_clients; + let mut responses: futures::stream::FuturesUnordered<_> = authority_clients + .iter_mut() + .map(|(name, client)| { + let name = name.clone(); + let execute = execute.clone(); + async move { (name.clone(), execute(name, client).await) } + }) + .collect(); + + let mut values = Vec::new(); + let mut value_score = 0; + let mut error_scores = HashMap::new(); + while let Some((name, result)) = responses.next().await { + match result { + Ok(value) => { + values.push(value); + value_score += committee.weight(&name); + if value_score >= committee.quorum_threshold() { + // Success! + return Ok(values); + } + } + Err(err) => { + let entry = error_scores.entry(err.clone()).or_insert(0); + *entry += committee.weight(&name); + if *entry >= committee.validity_threshold() { + // At least one honest node returned this error. + // No quorum can be reached, so return early. + bail!( + "Failed to communicate with a quorum of authorities: {}", + err + ); + } + } + } + } + + bail!("Failed to communicate with a quorum of authorities (multiple errors)"); + } + + /// Broadcast confirmation orders and optionally one more transfer order. + /// The corresponding sequence numbers should be consecutive and increasing. + async fn communicate_transfers( + &mut self, + sender: FastPayAddress, + known_certificates: Vec, + action: CommunicateAction, + ) -> Result, failure::Error> { + let target_sequence_number = match &action { + CommunicateAction::SendOrder(order) => order.transfer.sequence_number, + CommunicateAction::SynchronizeNextSequenceNumber(seq) => *seq, + }; + let requester = CertificateRequester::new( + self.committee.clone(), + self.authority_clients.values().cloned().collect(), + sender, + ); + let (task, mut handle) = Downloader::start( + requester, + known_certificates.into_iter().filter_map(|cert| { + if cert.value.transfer.sender == sender { + Some((cert.value.transfer.sequence_number, Ok(cert))) + } else { + None + } + }), + ); + let committee = self.committee.clone(); + let votes = self + .communicate_with_quorum(|name, client| { + let mut handle = handle.clone(); + let action = action.clone(); + let committee = &committee; + Box::pin(async move { + // Figure out which certificates this authority is missing. + let request = AccountInfoRequest { + sender, + request_sequence_number: None, + request_received_transfers_excluding_first_nth: None, + }; + let response = client.handle_account_info_request(request).await?; + let current_sequence_number = response.next_sequence_number; + // Download each missing certificate in reverse order using the downloader. + let mut missing_certificates = Vec::new(); + let mut number = target_sequence_number.decrement(); + while let Ok(value) = number { + if value < current_sequence_number { + break; + } + let certificate = handle + .query(value) + .await + .map_err(|_| FastPayError::ErrorWhileRequestingCertificate)??; + missing_certificates.push(certificate); + number = value.decrement(); + } + // Send all missing confirmation orders. + missing_certificates.reverse(); + for certificate in missing_certificates { + client + .handle_confirmation_order(ConfirmationOrder::new(certificate)) + .await?; + } + // Send the transfer order (if any) and return a vote. + if let CommunicateAction::SendOrder(order) = action { + let result = client.handle_transfer_order(order).await; + match result { + Ok(AccountInfoResponse { + pending_confirmation: Some(signed_order), + .. + }) => { + fp_ensure!( + signed_order.authority == name, + FastPayError::ErrorWhileProcessingTransferOrder + ); + signed_order.check(committee)?; + return Ok(Some(signed_order)); + } + Err(err) => return Err(err), + _ => return Err(FastPayError::ErrorWhileProcessingTransferOrder), + } + } + Ok(None) + }) + }) + .await?; + // Terminate downloader task and retrieve the content of the cache. + handle.stop().await?; + let mut certificates: Vec<_> = task.await.unwrap().filter_map(Result::ok).collect(); + if let CommunicateAction::SendOrder(order) = action { + let certificate = CertifiedTransferOrder { + value: order, + signatures: votes + .into_iter() + .filter_map(|vote| match vote { + Some(signed_order) => { + Some((signed_order.authority, signed_order.signature)) + } + None => None, + }) + .collect(), + }; + // Certificate is valid because + // * `communicate_with_quorum` ensured a sufficient "weight" of (non-error) answers were returned by authorities. + // * each answer is a vote signed by the expected authority. + certificates.push(certificate); + } + return Ok(certificates); + } + + /// Make sure we have all our certificates with sequence number + /// in the range 0..self.next_sequence_number + async fn download_sent_certificates( + &self, + ) -> Result, FastPayError> { + let mut requester = CertificateRequester::new( + self.committee.clone(), + self.authority_clients.values().cloned().collect(), + self.address, + ); + let known_sequence_numbers: BTreeSet<_> = self + .sent_certificates + .iter() + .map(|cert| cert.value.transfer.sequence_number) + .collect(); + let mut sent_certificates = self.sent_certificates.clone(); + let mut number = SequenceNumber::from(0); + while number < self.next_sequence_number { + if !known_sequence_numbers.contains(&number) { + let certificate = requester.query(number).await?; + sent_certificates.push(certificate); + } + number = number.increment().unwrap_or(SequenceNumber::max()); + } + sent_certificates.sort_by_key(|cert| cert.value.transfer.sequence_number); + Ok(sent_certificates) + } + + /// Send money to a FastPay or Primary recipient. + async fn transfer( + &mut self, + amount: Amount, + recipient: Address, + user_data: UserData, + ) -> Result { + // Trying to overspend may block the account. To prevent this, we compare with + // the balance as we know it. + let safe_amount = self.get_spendable_amount().await?; + ensure!( + amount <= safe_amount, + "Requested amount ({:?}) is not backed by sufficient funds ({:?})", + amount, + safe_amount + ); + let transfer = Transfer { + sender: self.address, + recipient, + amount, + sequence_number: self.next_sequence_number, + user_data, + }; + let order = TransferOrder::new(transfer, &self.secret); + let certificate = self + .execute_transfer(order, /* with_confirmation */ true) + .await?; + Ok(certificate) + } + + /// Update our view of sent certificates. Adjust the local balance and the next sequence number accordingly. + /// NOTE: This is only useful in the eventuality of missing local data. + /// We assume certificates to be valid and sent by us, and their sequence numbers to be unique. + fn update_sent_certificates( + &mut self, + sent_certificates: Vec, + ) -> Result<(), FastPayError> { + let mut new_balance = self.balance; + let mut new_next_sequence_number = self.next_sequence_number; + for new_cert in &sent_certificates { + new_balance = new_balance.sub(new_cert.value.transfer.amount.into())?; + if new_cert.value.transfer.sequence_number >= new_next_sequence_number { + new_next_sequence_number = new_cert + .value + .transfer + .sequence_number + .increment() + .unwrap_or(SequenceNumber::max()); + } + } + for old_cert in &self.sent_certificates { + new_balance = new_balance.add(old_cert.value.transfer.amount.into())?; + } + // Atomic update + self.sent_certificates = sent_certificates; + self.balance = new_balance; + self.next_sequence_number = new_next_sequence_number; + // Sanity check + assert_eq!( + self.sent_certificates.len(), + self.next_sequence_number.into() + ); + Ok(()) + } + + /// Execute (or retry) a transfer order. Update local balance. + async fn execute_transfer( + &mut self, + order: TransferOrder, + with_confirmation: bool, + ) -> Result { + ensure!( + self.pending_transfer == None || self.pending_transfer.as_ref() == Some(&order), + "Client state has a different pending transfer", + ); + ensure!( + order.transfer.sequence_number == self.next_sequence_number, + "Unexpected sequence number" + ); + self.pending_transfer = Some(order.clone()); + let new_sent_certificates = self + .communicate_transfers( + self.address, + self.sent_certificates.clone(), + CommunicateAction::SendOrder(order.clone()), + ) + .await?; + assert_eq!(new_sent_certificates.last().unwrap().value, order); + // Clear `pending_transfer` and update `sent_certificates`, + // `balance`, and `next_sequence_number`. (Note that if we were using persistent + // storage, we should ensure update atomicity in the eventuality of a crash.) + self.pending_transfer = None; + self.update_sent_certificates(new_sent_certificates)?; + // Confirm last transfer certificate if needed. + if with_confirmation { + self.communicate_transfers( + self.address, + self.sent_certificates.clone(), + CommunicateAction::SynchronizeNextSequenceNumber(self.next_sequence_number), + ) + .await?; + } + Ok(self.sent_certificates.last().unwrap().clone()) + } +} + +impl Client for ClientState +where + A: AuthorityClient + Send + Sync + Clone + 'static, +{ + fn transfer_to_fastpay( + &mut self, + amount: Amount, + recipient: FastPayAddress, + user_data: UserData, + ) -> AsyncResult { + Box::pin(self.transfer(amount, Address::FastPay(recipient), user_data)) + } + + fn transfer_to_primary( + &mut self, + amount: Amount, + recipient: PrimaryAddress, + user_data: UserData, + ) -> AsyncResult { + Box::pin(self.transfer(amount, Address::Primary(recipient), user_data)) + } + + fn get_spendable_amount(&mut self) -> AsyncResult { + Box::pin(async move { + if let Some(order) = self.pending_transfer.clone() { + // Finish executing the previous transfer. + self.execute_transfer(order, /* with_confirmation */ false) + .await?; + } + if self.sent_certificates.len() < self.next_sequence_number.into() { + // Recover missing sent certificates. + let new_sent_certificates = self.download_sent_certificates().await?; + self.update_sent_certificates(new_sent_certificates)?; + } + let amount = if self.balance < Balance::zero() { + Amount::zero() + } else { + Amount::try_from(self.balance).unwrap_or(std::u64::MAX.into()) + }; + Ok(amount) + }) + } + + fn receive_from_fastpay( + &mut self, + certificate: CertifiedTransferOrder, + ) -> AsyncResult<(), failure::Error> { + Box::pin(async move { + certificate.check(&self.committee)?; + let transfer = &certificate.value.transfer; + ensure!( + transfer.recipient == Address::FastPay(self.address), + "Transfer should be received by us." + ); + self.communicate_transfers( + transfer.sender, + vec![certificate.clone()], + CommunicateAction::SynchronizeNextSequenceNumber( + certificate.value.transfer.sequence_number.increment()?, + ), + ) + .await?; + // Everything worked: update the local balance. + let transfer = &certificate.value.transfer; + let key = transfer.key(); + if !self.received_certificates.contains_key(&key) { + self.balance = self.balance.add(transfer.amount.into()).unwrap(); + self.received_certificates.insert(key, certificate); + } + Ok(()) + }) + } + + fn transfer_to_fastpay_unsafe_unconfirmed( + &mut self, + amount: Amount, + recipient: FastPayAddress, + user_data: UserData, + ) -> AsyncResult { + Box::pin(async move { + let transfer = Transfer { + sender: self.address, + recipient: Address::FastPay(recipient), + amount, + sequence_number: self.next_sequence_number, + user_data, + }; + let order = TransferOrder::new(transfer, &self.secret); + let new_certificate = self + .execute_transfer(order, /* with_confirmation */ false) + .await?; + Ok(new_certificate) + }) + } +} diff --git a/rust/fastpay_core/src/committee.rs b/rust/fastpay_core/src/committee.rs new file mode 100644 index 0000000000000..1a5121d838f55 --- /dev/null +++ b/rust/fastpay_core/src/committee.rs @@ -0,0 +1,54 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::base_types::*; +use std::collections::BTreeMap; + +#[derive(Eq, PartialEq, Clone, Hash, Debug)] +pub struct Committee { + pub voting_rights: BTreeMap, + pub total_votes: usize, +} + +impl Committee { + pub fn new(voting_rights: BTreeMap) -> Self { + let total_votes = voting_rights.iter().fold(0, |sum, (_, votes)| sum + *votes); + Committee { + voting_rights, + total_votes, + } + } + + pub fn weight(&self, author: &AuthorityName) -> usize { + *self.voting_rights.get(author).unwrap_or(&0) + } + + pub fn quorum_threshold(&self) -> usize { + // If N = 3f + 1 + k (0 <= k < 3) + // then (2 N + 3) / 3 = 2f + 1 + (2k + 2)/3 = 2f + 1 + k = N - f + 2 * self.total_votes / 3 + 1 + } + + pub fn validity_threshold(&self) -> usize { + // If N = 3f + 1 + k (0 <= k < 3) + // then (N + 2) / 3 = f + 1 + k/3 = f + 1 + (self.total_votes + 2) / 3 + } + + /// Find the highest value than is supported by a quorum of authorities. + pub fn get_strong_majority_lower_bound(&self, mut values: Vec<(AuthorityName, V)>) -> V + where + V: Default + std::cmp::Ord, + { + values.sort_by(|(_, x), (_, y)| V::cmp(y, x)); + // Browse values by decreasing order, while tracking how many votes they have. + let mut score = 0; + for (name, value) in values { + score += self.weight(&name); + if score >= self.quorum_threshold() { + return value; + } + } + return V::default(); + } +} diff --git a/rust/fastpay_core/src/downloader.rs b/rust/fastpay_core/src/downloader.rs new file mode 100644 index 0000000000000..0d4e72402dd6f --- /dev/null +++ b/rust/fastpay_core/src/downloader.rs @@ -0,0 +1,167 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use futures::channel::{mpsc, oneshot}; +use futures::{future, SinkExt, StreamExt}; +use std::collections::BTreeMap; +use tokio; + +#[cfg(test)] +#[path = "unit_tests/downloader_tests.rs"] +mod downloader_tests; + +/// An asynchronous downloader that ensures that the value for each key is requested at most once. +pub struct Downloader { + /// User-provided logics to fetch data. + requester: R, + /// Status of previous downloads, indexed by key. + downloads: BTreeMap>, + /// Command stream of the main handler. + command_receiver: mpsc::UnboundedReceiver>, + /// How to send commands to the main handler. + command_sender: mpsc::UnboundedSender>, +} + +/// The underlying data-fetching mechanism to be provided by the user. +pub trait Requester { + type Key: std::cmp::Ord + Send + Sync + Clone + 'static; + type Value: std::fmt::Debug + Send + Clone + 'static; + + /// Request the value corresponding to the given key. + fn query(&mut self, key: Self::Key) -> future::BoxFuture; +} + +/// Channel for using code to send requests and stop the downloader task. +#[derive(Clone)] +pub struct DownloadHandle(mpsc::UnboundedSender>); + +/// A command send to the downloader task. +enum DownloadCommand { + /// A user requests a value. + Request(K, oneshot::Sender), + /// A value has been downloaded. + Publish(K, V), + /// Shut down the main handler. + Quit, +} + +/// The status of a download job. +enum DownloadStatus { + /// A value is available. + Ready(V), + /// Download is in progress. Subscribers are waiting for the result. + WaitingList(Vec>), +} + +impl DownloadHandle { + /// Allow to make new download queries and wait for the result. + pub async fn query(&mut self, key: K) -> Result { + let (callback, receiver) = oneshot::channel(); + self.0.send(DownloadCommand::Request(key, callback)).await?; + let value = receiver.await?; + Ok(value) + } + + /// Shut down the main handler. + pub async fn stop(&mut self) -> Result<(), failure::Error> { + self.0.send(DownloadCommand::Quit).await?; + Ok(()) + } +} + +impl Downloader { + /// Recover the content of the downloading cache. + fn finalize(self) -> impl Iterator { + self.downloads.into_iter().filter_map(|(_, v)| match v { + DownloadStatus::Ready(value) => Some(value), + _ => None, + }) + } +} + +impl Downloader +where + R: Requester + Send + Clone + 'static, + K: std::cmp::Ord + Send + Sync + Clone + 'static, + V: std::fmt::Debug + Send + Clone + 'static, +{ + /// Create a downloader as a wrapper around the given `requester`. + /// Fill the initial cache with some known values. + pub fn start( + requester: R, + known_values: I, + ) -> ( + tokio::task::JoinHandle>, + DownloadHandle, + ) + where + I: IntoIterator, + { + let (command_sender, command_receiver) = mpsc::unbounded(); + let mut downloads = BTreeMap::new(); + for (key, value) in known_values { + downloads.insert(key, DownloadStatus::Ready(value)); + } + let mut downloader = Self { + requester, + downloads, + command_receiver, + command_sender: command_sender.clone(), + }; + // Spawn a task for the main handler. + let task = tokio::spawn(async move { + downloader.run().await; + downloader.finalize() + }); + (task, DownloadHandle(command_sender)) + } + + /// Main handler. + async fn run(&mut self) { + loop { + match self.command_receiver.next().await { + Some(DownloadCommand::Request(key, callback)) => { + // Deconstruct self to help the borrow checker below. + let requester_ref = &self.requester; + let command_sender_ref = &self.command_sender; + let downloads_ref_mut = &mut self.downloads; + // Recover current download status or create a new one. + let entry = downloads_ref_mut.entry(key.clone()).or_insert_with(|| { + let mut requester = requester_ref.clone(); + let mut command_sender = command_sender_ref.clone(); + tokio::spawn(async move { + let result = requester.query(key.clone()).await; + command_sender + .send(DownloadCommand::Publish(key, result)) + .await + .unwrap_or(()) + }); + DownloadStatus::WaitingList(Vec::new()) + }); + // Process Request: either subscribe or return the result now. + match entry { + DownloadStatus::WaitingList(list) => { + list.push(callback); + } + DownloadStatus::Ready(result) => { + callback.send(result.clone()).unwrap_or(()); + } + } + } + Some(DownloadCommand::Publish(key, result)) => { + // Handle newly found result. + let status = std::mem::replace( + self.downloads.get_mut(&key).expect("Key should be present"), + DownloadStatus::Ready(result.clone()), + ); + if let DownloadStatus::WaitingList(subscribers) = status { + for callback in subscribers { + callback.send(result.clone()).unwrap_or(()); + } + } + } + _ => return, + } + } + } +} diff --git a/rust/fastpay_core/src/error.rs b/rust/fastpay_core/src/error.rs new file mode 100644 index 0000000000000..235ca21de868b --- /dev/null +++ b/rust/fastpay_core/src/error.rs @@ -0,0 +1,99 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use crate::base_types::*; +use crate::messages::*; +use crate::serde::{Deserialize, Serialize}; + +#[macro_export] +macro_rules! fp_bail { + ($e:expr) => { + return Err($e); + }; +} + +#[macro_export(local_inner_macros)] +macro_rules! fp_ensure { + ($cond:expr, $e:expr) => { + if !($cond) { + fp_bail!($e); + } + }; +} + +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Fail, Hash)] +/// Custom error type for FastPay. +pub enum FastPayError { + // Signature verification + #[fail(display = "Signature is not valid: {}", error)] + InvalidSignature { error: String }, + #[fail(display = "Value was not signed by a known authority")] + UnknownSigner, + // Certificate verification + #[fail(display = "Signatures in a certificate must form a quorum")] + CertificateRequiresQuorum, + // Transfer processing + #[fail(display = "Transfers must have positive amount")] + IncorrectTransferAmount, + #[fail( + display = "The given sequence number must match the next expected sequence number of the account" + )] + UnexpectedSequenceNumber, + #[fail( + display = "The transferred amount must be not exceed the current account balance: {:?}", + current_balance + )] + InsufficientFunding { current_balance: Balance }, + #[fail( + display = "Cannot initiate transfer while a transfer order is still pending confirmation: {:?}", + pending_confirmation + )] + PreviousTransferMustBeConfirmedFirst { pending_confirmation: TransferOrder }, + #[fail(display = "Transfer order was processed but no signature was produced by authority")] + ErrorWhileProcessingTransferOrder, + #[fail( + display = "An invalid answer was returned by the authority while requesting a certificate" + )] + ErrorWhileRequestingCertificate, + #[fail( + display = "Cannot confirm a transfer while previous transfer orders are still pending confirmation: {:?}", + current_sequence_number + )] + MissingEalierConfirmations { + current_sequence_number: VersionNumber, + }, + // Synchronization validation + #[fail(display = "Transaction index must increase by one")] + UnexpectedTransactionIndex, + // Account access + #[fail(display = "No certificate for this account and sequence number")] + CertificateNotfound, + #[fail(display = "Unknown sender's account")] + UnknownSenderAccount, + #[fail(display = "Signatures in a certificate must be from different authorities.")] + CertificateAuthorityReuse, + #[fail(display = "Sequence numbers above the maximal value are not usable for transfers.")] + InvalidSequenceNumber, + #[fail(display = "Sequence number overflow.")] + SequenceOverflow, + #[fail(display = "Sequence number underflow.")] + SequenceUnderflow, + #[fail(display = "Amount overflow.")] + AmountOverflow, + #[fail(display = "Amount underflow.")] + AmountUnderflow, + #[fail(display = "Account balance overflow.")] + BalanceOverflow, + #[fail(display = "Account balance underflow.")] + BalanceUnderflow, + #[fail(display = "Wrong shard used.")] + WrongShard, + #[fail(display = "Invalid cross shard update.")] + InvalidCrossShardUpdate, + #[fail(display = "Cannot deserialize.")] + InvalidDecoding, + #[fail(display = "Unexpected message.")] + UnexpectedMessage, + #[fail(display = "Network error while querying service: {:?}.", error)] + ClientIOError { error: String }, +} diff --git a/rust/fastpay_core/src/fastpay_smart_contract.rs b/rust/fastpay_core/src/fastpay_smart_contract.rs new file mode 100644 index 0000000000000..34cee8e0a2192 --- /dev/null +++ b/rust/fastpay_core/src/fastpay_smart_contract.rs @@ -0,0 +1,114 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::base_types::*; +use super::committee::Committee; +use super::messages::*; +use std::collections::BTreeMap; + +#[cfg(test)] +#[path = "unit_tests/fastpay_smart_contract_tests.rs"] +mod fastpay_smart_contract_tests; + +#[derive(Eq, PartialEq, Clone, Hash, Debug)] +pub struct AccountOnchainState { + /// Prevent spending actions from this account to Primary to be redeemed more than once. + /// It is the responsability of the owner of the account to redeem the previous action + /// before initiating a new one. Otherwise, money can be lost. + last_redeemed: Option, +} + +#[derive(Eq, PartialEq, Clone, Debug)] +pub struct FastPaySmartContractState { + /// Committee of this FastPay instance. + committee: Committee, + /// Onchain states of FastPay smart contract. + pub accounts: BTreeMap, + /// Primary coins in the smart contract. + total_balance: Amount, + /// The latest transaction index included in the blockchain. + pub last_transaction_index: VersionNumber, + /// Transactions included in the blockchain. + pub blockchain: Vec, +} + +pub trait FastPaySmartContract { + /// Initiate a transfer from Primary to FastPay. + fn handle_funding_transaction( + &mut self, + transaction: FundingTransaction, + ) -> Result<(), failure::Error>; + + /// Finalize a transfer from FastPay to Primary. + fn handle_redeem_transaction( + &mut self, + transaction: RedeemTransaction, + ) -> Result<(), failure::Error>; +} + +impl FastPaySmartContract for FastPaySmartContractState { + /// Initiate a transfer to FastPay. + fn handle_funding_transaction( + &mut self, + transaction: FundingTransaction, + ) -> Result<(), failure::Error> { + // TODO: Authentication by Primary sender + let amount = transaction.primary_coins; + ensure!( + amount > Amount::zero(), + "Transfers must have positive amount", + ); + // TODO: Make sure that under overflow/underflow we are consistent. + self.last_transaction_index = self.last_transaction_index.increment()?; + self.blockchain.push(transaction); + self.total_balance = self.total_balance.add(amount)?; + Ok(()) + } + + /// Finalize a transfer from FastPay. + fn handle_redeem_transaction( + &mut self, + transaction: RedeemTransaction, + ) -> Result<(), failure::Error> { + transaction.transfer_certificate.check(&self.committee)?; + let order = transaction.transfer_certificate.value; + let transfer = &order.transfer; + ensure!( + self.total_balance >= transfer.amount, + "The balance on the blockchain cannot be negative", + ); + let account = self + .accounts + .entry(transfer.sender) + .or_insert(AccountOnchainState::new()); + ensure!( + account.last_redeemed < Some(transfer.sequence_number), + "Transfer certificates to Primary must have increasing sequence numbers.", + ); + account.last_redeemed = Some(transfer.sequence_number); + self.total_balance = self.total_balance.sub(transfer.amount)?; + // Transfer Primary coins to order.recipient + + Ok(()) + } +} + +impl AccountOnchainState { + fn new() -> Self { + Self { + last_redeemed: None, + } + } +} + +impl FastPaySmartContractState { + pub fn new(committee: Committee) -> Self { + FastPaySmartContractState { + committee, + total_balance: Amount::zero(), + last_transaction_index: VersionNumber::new(), + blockchain: Vec::new(), + accounts: BTreeMap::new(), + } + } +} diff --git a/rust/fastpay_core/src/lib.rs b/rust/fastpay_core/src/lib.rs new file mode 100644 index 0000000000000..d728918cb32d7 --- /dev/null +++ b/rust/fastpay_core/src/lib.rs @@ -0,0 +1,24 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +#![deny(warnings)] + +#[macro_use] +extern crate failure; +extern crate base64; +extern crate bincode; +extern crate ed25519_dalek; +extern crate futures; +extern crate serde; + +#[macro_use] +pub mod error; + +pub mod authority; +pub mod base_types; +pub mod client; +pub mod committee; +pub mod downloader; +pub mod fastpay_smart_contract; +pub mod messages; +pub mod serialize; diff --git a/rust/fastpay_core/src/messages.rs b/rust/fastpay_core/src/messages.rs new file mode 100644 index 0000000000000..9e6b1836bc866 --- /dev/null +++ b/rust/fastpay_core/src/messages.rs @@ -0,0 +1,332 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::base_types::*; +use super::committee::Committee; +use super::error::*; + +use ed25519_dalek::{Digest, Sha512}; + +#[cfg(test)] +#[path = "unit_tests/messages_tests.rs"] +mod messages_tests; + +use serde::{Deserialize, Serialize}; +use std::collections::HashSet; +use std::hash::{Hash, Hasher}; + +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] +pub struct FundingTransaction { + pub recipient: FastPayAddress, + pub primary_coins: Amount, + // TODO: Authenticated by Primary sender. +} + +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] +pub struct PrimarySynchronizationOrder { + pub recipient: FastPayAddress, + pub amount: Amount, + pub transaction_index: VersionNumber, +} + +#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, Serialize, Deserialize)] +pub enum Address { + Primary(PrimaryAddress), + FastPay(FastPayAddress), +} + +#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)] +pub struct Transfer { + pub sender: FastPayAddress, + pub recipient: Address, + pub amount: Amount, + pub sequence_number: SequenceNumber, + pub user_data: UserData, +} + +#[derive(Eq, Clone, Debug, Serialize, Deserialize)] +pub struct TransferOrder { + pub transfer: Transfer, + pub signature: Signature, +} + +#[derive(Eq, Clone, Debug, Serialize, Deserialize)] +pub struct SignedTransferOrder { + pub value: TransferOrder, + pub authority: AuthorityName, + pub signature: Signature, +} + +#[derive(Eq, Clone, Debug, Serialize, Deserialize)] +pub struct CertifiedTransferOrder { + pub value: TransferOrder, + pub signatures: Vec<(AuthorityName, Signature)>, +} + +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] +pub struct RedeemTransaction { + pub transfer_certificate: CertifiedTransferOrder, +} + +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] +pub struct ConfirmationOrder { + pub transfer_certificate: CertifiedTransferOrder, +} + +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] +pub struct AccountInfoRequest { + pub sender: FastPayAddress, + pub request_sequence_number: Option, + pub request_received_transfers_excluding_first_nth: Option, +} + +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] +pub struct AccountInfoResponse { + pub sender: FastPayAddress, + pub balance: Balance, + pub next_sequence_number: SequenceNumber, + pub pending_confirmation: Option, + pub requested_certificate: Option, + pub requested_received_transfers: Vec, +} + +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] +pub struct CrossShardUpdate { + pub shard_id: ShardId, + pub transfer_certificate: CertifiedTransferOrder, +} + +impl Hash for TransferOrder { + fn hash(&self, state: &mut H) { + self.transfer.hash(state); + } +} + +impl PartialEq for TransferOrder { + fn eq(&self, other: &Self) -> bool { + self.transfer == other.transfer + } +} + +impl Hash for SignedTransferOrder { + fn hash(&self, state: &mut H) { + self.value.hash(state); + self.authority.hash(state); + } +} + +impl PartialEq for SignedTransferOrder { + fn eq(&self, other: &Self) -> bool { + self.value == other.value && self.authority == other.authority + } +} + +impl Hash for CertifiedTransferOrder { + fn hash(&self, state: &mut H) { + self.value.hash(state); + self.signatures.len().hash(state); + for (name, _) in self.signatures.iter() { + name.hash(state); + } + } +} + +impl PartialEq for CertifiedTransferOrder { + fn eq(&self, other: &Self) -> bool { + self.value == other.value + && self.signatures.len() == other.signatures.len() + && self + .signatures + .iter() + .map(|(name, _)| name) + .eq(other.signatures.iter().map(|(name, _)| name)) + } +} + +impl Transfer { + pub fn key(&self) -> (FastPayAddress, SequenceNumber) { + (self.sender, self.sequence_number) + } +} + +impl TransferOrder { + pub fn new(transfer: Transfer, secret: &SecretKey) -> Self { + let signature = Signature::new(&transfer, secret); + Self { + transfer, + signature, + } + } + + pub fn check_signature(&self) -> Result<(), FastPayError> { + self.signature.check(&self.transfer, self.transfer.sender) + } +} + +impl Digestible for Transfer { + fn digest(self: &Transfer) -> [u8; 32] { + let mut h: Sha512 = Sha512::new(); + let mut hash: [u8; 64] = [0u8; 64]; + let mut digest: [u8; 32] = [0u8; 32]; + + h.input(&self.sender.0); + match self.recipient { + Address::Primary(addr) => { + h.input([0x03]); + h.input(&addr.0); + } + Address::FastPay(addr) => { + h.input([0x04]); + h.input(&addr.0); + } + } + h.input(u64::from(self.amount).to_le_bytes()); + h.input(u64::from(self.sequence_number).to_le_bytes()); + match self.user_data.0 { + None => h.input([0x00]), + Some(data) => { + h.input([0x01]); + h.input(data); + } + } + hash.copy_from_slice(h.result().as_slice()); + digest.copy_from_slice(&hash[..32]); + digest + } +} + +impl Digestible for TransferOrder { + fn digest(self: &TransferOrder) -> [u8; 32] { + self.transfer.digest() + } +} + +impl SignedTransferOrder { + /// Use signing key to create a signed object. + pub fn new(value: TransferOrder, authority: AuthorityName, secret: &SecretKey) -> Self { + let signature = Signature::new(&value, secret); + Self { + value, + authority, + signature, + } + } + + /// Verify the signature and return the non-zero voting right of the authority. + pub fn check(&self, committee: &Committee) -> Result { + self.value.check_signature()?; + let weight = committee.weight(&self.authority); + fp_ensure!(weight > 0, FastPayError::UnknownSigner); + self.signature.check(&self.value, self.authority)?; + Ok(weight) + } +} + +pub struct SignatureAggregator<'a> { + committee: &'a Committee, + weight: usize, + used_authorities: HashSet, + partial: CertifiedTransferOrder, +} + +impl<'a> SignatureAggregator<'a> { + /// Start aggregating signatures for the given value into a certificate. + pub fn try_new(value: TransferOrder, committee: &'a Committee) -> Result { + value.check_signature()?; + Ok(Self::new_unsafe(value, committee)) + } + + /// Same as try_new but we don't check the order. + pub fn new_unsafe(value: TransferOrder, committee: &'a Committee) -> Self { + Self { + committee, + weight: 0, + used_authorities: HashSet::new(), + partial: CertifiedTransferOrder { + value, + signatures: Vec::new(), + }, + } + } + + /// Try to append a signature to a (partial) certificate. Returns Some(certificate) if a quorum was reached. + /// The resulting final certificate is guaranteed to be valid in the sense of `check` below. + /// Returns an error if the signed value cannot be aggregated. + pub fn append( + &mut self, + authority: AuthorityName, + signature: Signature, + ) -> Result, FastPayError> { + signature.check(&self.partial.value, authority)?; + // Check that each authority only appears once. + fp_ensure!( + !self.used_authorities.contains(&authority), + FastPayError::CertificateAuthorityReuse + ); + self.used_authorities.insert(authority.clone()); + // Update weight. + let voting_rights = self.committee.weight(&authority); + fp_ensure!(voting_rights > 0, FastPayError::UnknownSigner); + self.weight += voting_rights; + // Update certificate. + self.partial.signatures.push((authority, signature)); + + if self.weight >= self.committee.quorum_threshold() { + Ok(Some(self.partial.clone())) + } else { + Ok(None) + } + } +} + +impl CertifiedTransferOrder { + pub fn key(&self) -> (FastPayAddress, SequenceNumber) { + let transfer = &self.value.transfer; + transfer.key() + } + + /// Verify the certificate. + pub fn check(&self, committee: &Committee) -> Result<(), FastPayError> { + // Check the quorum. + let mut weight = 0; + let mut used_authorities = HashSet::new(); + for (authority, _) in self.signatures.iter() { + // Check that each authority only appears once. + fp_ensure!( + !used_authorities.contains(authority), + FastPayError::CertificateAuthorityReuse + ); + used_authorities.insert(authority.clone()); + // Update weight. + let voting_rights = committee.weight(authority); + fp_ensure!(voting_rights > 0, FastPayError::UnknownSigner); + weight += voting_rights; + } + fp_ensure!( + weight >= committee.quorum_threshold(), + FastPayError::CertificateRequiresQuorum + ); + // All what is left is checking signatures! + let inner_sig = (self.value.transfer.sender, self.value.signature); + Signature::verify_batch( + &self.value, + std::iter::once(&inner_sig).chain(&self.signatures), + ) + } +} + +impl RedeemTransaction { + pub fn new(transfer_certificate: CertifiedTransferOrder) -> Self { + Self { + transfer_certificate, + } + } +} + +impl ConfirmationOrder { + pub fn new(transfer_certificate: CertifiedTransferOrder) -> Self { + Self { + transfer_certificate, + } + } +} diff --git a/rust/fastpay_core/src/serialize.rs b/rust/fastpay_core/src/serialize.rs new file mode 100644 index 0000000000000..44d52180adc29 --- /dev/null +++ b/rust/fastpay_core/src/serialize.rs @@ -0,0 +1,121 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::messages::*; +use crate::error::*; + +use bincode; +use serde::{Deserialize, Serialize}; + +#[cfg(test)] +#[path = "unit_tests/serialize_tests.rs"] +mod serialize_tests; + +#[derive(Serialize, Deserialize)] +pub enum SerializedMessage { + Order(TransferOrder), + Vote(SignedTransferOrder), + Cert(CertifiedTransferOrder), + CrossShard(CertifiedTransferOrder), + Error(FastPayError), + InfoReq(AccountInfoRequest), + InfoResp(AccountInfoResponse), +} + +// This helper structure is only here to avoid cloning while serializing commands. +// Here we must replicate the definition of SerializedMessage exactly +// so that the variant tags match. +#[derive(Serialize)] +enum ShallowSerializedMessage<'a> { + Order(&'a TransferOrder), + Vote(&'a SignedTransferOrder), + Cert(&'a CertifiedTransferOrder), + CrossShard(&'a CertifiedTransferOrder), + Error(&'a FastPayError), + InfoReq(&'a AccountInfoRequest), + InfoResp(&'a AccountInfoResponse), +} + +fn serialize_into(writer: W, msg: &T) -> Result<(), failure::Error> +where + W: std::io::Write, + T: Serialize, +{ + bincode::serialize_into(writer, msg).map_err(|err| format_err!("{}", err)) +} + +fn serialize(msg: &T) -> Vec +where + T: Serialize, +{ + let mut buf = Vec::new(); + bincode::serialize_into(&mut buf, msg) + .expect("Serializing to a resizable buffer should not fail."); + buf +} + +pub fn serialize_message(msg: &SerializedMessage) -> Vec { + serialize(msg) +} + +pub fn serialize_transfer_order(value: &TransferOrder) -> Vec { + serialize(&ShallowSerializedMessage::Order(value)) +} + +pub fn serialize_transfer_order_into( + writer: W, + value: &TransferOrder, +) -> Result<(), failure::Error> +where + W: std::io::Write, +{ + serialize_into(writer, &ShallowSerializedMessage::Order(value)) +} + +pub fn serialize_error(value: &FastPayError) -> Vec { + serialize(&ShallowSerializedMessage::Error(value)) +} + +pub fn serialize_cert(value: &CertifiedTransferOrder) -> Vec { + serialize(&ShallowSerializedMessage::Cert(value)) +} + +pub fn serialize_cert_into( + writer: W, + value: &CertifiedTransferOrder, +) -> Result<(), failure::Error> +where + W: std::io::Write, +{ + serialize_into(writer, &ShallowSerializedMessage::Cert(value)) +} + +pub fn serialize_info_request(value: &AccountInfoRequest) -> Vec { + serialize(&ShallowSerializedMessage::InfoReq(value)) +} + +pub fn serialize_info_response(value: &AccountInfoResponse) -> Vec { + serialize(&ShallowSerializedMessage::InfoResp(value)) +} + +pub fn serialize_cross_shard(value: &CertifiedTransferOrder) -> Vec { + serialize(&ShallowSerializedMessage::CrossShard(value)) +} + +pub fn serialize_vote(value: &SignedTransferOrder) -> Vec { + serialize(&ShallowSerializedMessage::Vote(value)) +} + +pub fn serialize_vote_into(writer: W, value: &SignedTransferOrder) -> Result<(), failure::Error> +where + W: std::io::Write, +{ + serialize_into(writer, &ShallowSerializedMessage::Vote(value)) +} + +pub fn deserialize_message(reader: R) -> Result +where + R: std::io::Read, +{ + bincode::deserialize_from(reader).map_err(|err| format_err!("{}", err)) +} diff --git a/rust/fastpay_core/src/unit_tests/authority_tests.rs b/rust/fastpay_core/src/unit_tests/authority_tests.rs new file mode 100644 index 0000000000000..8cc7e23cec895 --- /dev/null +++ b/rust/fastpay_core/src/unit_tests/authority_tests.rs @@ -0,0 +1,516 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +#[test] +fn test_handle_transfer_order_bad_signature() { + let (sender, sender_key) = get_key_pair(); + let recipient = Address::FastPay(dbg_addr(2)); + let mut authority_state = init_state_with_account(sender, Balance::from(5)); + let transfer_order = init_transfer_order(sender, &sender_key, recipient, Amount::from(5)); + let (_unknown_address, unknown_key) = get_key_pair(); + let mut bad_signature_transfer_order = transfer_order.clone(); + bad_signature_transfer_order.signature = Signature::new(&transfer_order.transfer, &unknown_key); + assert!(authority_state + .handle_transfer_order(bad_signature_transfer_order) + .is_err()); + assert!(authority_state + .accounts + .get(&sender) + .unwrap() + .pending_confirmation + .is_none()); +} + +#[test] +fn test_handle_transfer_order_zero_amount() { + let (sender, sender_key) = get_key_pair(); + let recipient = Address::FastPay(dbg_addr(2)); + let mut authority_state = init_state_with_account(sender, Balance::from(5)); + let transfer_order = init_transfer_order(sender, &sender_key, recipient, Amount::from(5)); + + // test transfer non-positive amount + let mut zero_amount_transfer = transfer_order.transfer.clone(); + zero_amount_transfer.amount = Amount::zero(); + let zero_amount_transfer_order = TransferOrder::new(zero_amount_transfer, &sender_key); + assert!(authority_state + .handle_transfer_order(zero_amount_transfer_order) + .is_err()); + assert!(authority_state + .accounts + .get(&sender) + .unwrap() + .pending_confirmation + .is_none()); +} + +#[test] +fn test_handle_transfer_order_unknown_sender() { + let (sender, sender_key) = get_key_pair(); + let recipient = Address::FastPay(dbg_addr(2)); + let mut authority_state = init_state_with_account(sender, Balance::from(5)); + let transfer_order = init_transfer_order(sender, &sender_key, recipient, Amount::from(5)); + let (unknown_address, unknown_key) = get_key_pair(); + + let mut unknown_sender_transfer = transfer_order.transfer.clone(); + unknown_sender_transfer.sender = unknown_address; + let unknown_sender_transfer_order = TransferOrder::new(unknown_sender_transfer, &unknown_key); + assert!(authority_state + .handle_transfer_order(unknown_sender_transfer_order) + .is_err()); + assert!(authority_state + .accounts + .get(&sender) + .unwrap() + .pending_confirmation + .is_none()); +} + +#[test] +fn test_handle_transfer_order_bad_sequence_number() { + let (sender, sender_key) = get_key_pair(); + let recipient = Address::FastPay(dbg_addr(2)); + let authority_state = init_state_with_account(sender, Balance::from(5)); + let transfer_order = init_transfer_order(sender, &sender_key, recipient, Amount::from(5)); + + let mut sequence_number_state = authority_state; + let sequence_number_state_sender_account = + sequence_number_state.accounts.get_mut(&sender).unwrap(); + sequence_number_state_sender_account.next_sequence_number = + sequence_number_state_sender_account + .next_sequence_number + .increment() + .unwrap(); + assert!(sequence_number_state + .handle_transfer_order(transfer_order.clone()) + .is_err()); + assert!(sequence_number_state + .accounts + .get(&sender) + .unwrap() + .pending_confirmation + .is_none()); +} + +#[test] +fn test_handle_transfer_order_exceed_balance() { + let (sender, sender_key) = get_key_pair(); + let recipient = Address::FastPay(dbg_addr(2)); + let mut authority_state = init_state_with_account(sender, Balance::from(5)); + let transfer_order = init_transfer_order(sender, &sender_key, recipient, Amount::from(1000)); + assert!(authority_state + .handle_transfer_order(transfer_order) + .is_err()); + assert!(authority_state + .accounts + .get(&sender) + .unwrap() + .pending_confirmation + .is_none()); +} + +#[test] +fn test_handle_transfer_order_ok() { + let (sender, sender_key) = get_key_pair(); + let recipient = Address::FastPay(dbg_addr(2)); + let mut authority_state = init_state_with_account(sender, Balance::from(5)); + let transfer_order = init_transfer_order(sender, &sender_key, recipient, Amount::from(5)); + + let account_info = authority_state + .handle_transfer_order(transfer_order.clone()) + .unwrap(); + let pending_confirmation = authority_state + .accounts + .get(&sender) + .unwrap() + .pending_confirmation + .clone() + .unwrap(); + assert_eq!( + account_info.pending_confirmation.unwrap(), + pending_confirmation + ); +} + +#[test] +fn test_handle_transfer_order_double_spend() { + let (sender, sender_key) = get_key_pair(); + let recipient = Address::FastPay(dbg_addr(2)); + let mut authority_state = init_state_with_account(sender, Balance::from(5)); + let transfer_order = init_transfer_order(sender, &sender_key, recipient, Amount::from(5)); + + let signed_order = authority_state + .handle_transfer_order(transfer_order.clone()) + .unwrap(); + let double_spend_signed_order = authority_state + .handle_transfer_order(transfer_order.clone()) + .unwrap(); + assert_eq!(signed_order, double_spend_signed_order); +} + +#[test] +fn test_handle_confirmation_order_unknown_sender() { + let recipient = dbg_addr(2); + let (sender, sender_key) = get_key_pair(); + let mut authority_state = init_state(); + let certified_transfer_order = init_certified_transfer_order( + sender, + &sender_key, + Address::FastPay(recipient), + Amount::from(5), + &authority_state, + ); + + assert!(authority_state + .handle_confirmation_order(ConfirmationOrder::new(certified_transfer_order.clone())) + .is_ok()); + assert!(authority_state.accounts.get(&recipient).is_some()); +} + +#[test] +fn test_handle_confirmation_order_bad_sequence_number() { + let (sender, sender_key) = get_key_pair(); + let recipient = dbg_addr(2); + let mut authority_state = init_state_with_account(sender, Balance::from(5)); + let sender_account = authority_state.accounts.get_mut(&sender).unwrap(); + sender_account.next_sequence_number = sender_account.next_sequence_number.increment().unwrap(); + // let old_account = sender_account; + + let old_balance; + let old_seq_num; + { + let old_account = authority_state.accounts.get_mut(&sender).unwrap(); + old_balance = old_account.balance; + old_seq_num = old_account.next_sequence_number; + } + + let certified_transfer_order = init_certified_transfer_order( + sender, + &sender_key, + Address::FastPay(recipient), + Amount::from(5), + &authority_state, + ); + // Replays are ignored. + assert!(authority_state + .handle_confirmation_order(ConfirmationOrder::new(certified_transfer_order.clone())) + .is_ok()); + let new_account = authority_state.accounts.get_mut(&sender).unwrap(); + assert_eq!(old_balance, new_account.balance); + assert_eq!(old_seq_num, new_account.next_sequence_number); + assert_eq!(new_account.confirmed_log, Vec::new()); + assert!(authority_state.accounts.get(&recipient).is_none()); +} + +#[test] +fn test_handle_confirmation_order_exceed_balance() { + let (sender, sender_key) = get_key_pair(); + let recipient = dbg_addr(2); + let mut authority_state = init_state_with_account(sender, Balance::from(5)); + + let certified_transfer_order = init_certified_transfer_order( + sender, + &sender_key, + Address::FastPay(recipient), + Amount::from(1000), + &authority_state, + ); + assert!(authority_state + .handle_confirmation_order(ConfirmationOrder::new(certified_transfer_order.clone())) + .is_ok()); + let new_account = authority_state.accounts.get(&sender).unwrap(); + assert_eq!(Balance::from(-995), new_account.balance); + assert_eq!(SequenceNumber::from(1), new_account.next_sequence_number); + assert_eq!(new_account.confirmed_log.len(), 1); + assert!(authority_state.accounts.get(&recipient).is_some()); +} + +#[test] +fn test_handle_confirmation_order_receiver_balance_overflow() { + let (sender, sender_key) = get_key_pair(); + let (recipient, _) = get_key_pair(); + let mut authority_state = init_state_with_accounts(vec![ + (sender, Balance::from(1)), + (recipient, Balance::max()), + ]); + + let certified_transfer_order = init_certified_transfer_order( + sender, + &sender_key, + Address::FastPay(recipient), + Amount::from(1), + &authority_state, + ); + assert!(authority_state + .handle_confirmation_order(ConfirmationOrder::new(certified_transfer_order.clone())) + .is_ok()); + let new_sender_account = authority_state.accounts.get(&sender).unwrap(); + assert_eq!(Balance::from(0), new_sender_account.balance); + assert_eq!( + SequenceNumber::from(1), + new_sender_account.next_sequence_number + ); + assert_eq!(new_sender_account.confirmed_log.len(), 1); + let new_recipient_account = authority_state.accounts.get(&recipient).unwrap(); + assert_eq!(Balance::max(), new_recipient_account.balance); +} + +#[test] +fn test_handle_confirmation_order_receiver_equal_sender() { + let (address, key) = get_key_pair(); + let mut authority_state = init_state_with_account(address, Balance::from(1)); + + let certified_transfer_order = init_certified_transfer_order( + address, + &key, + Address::FastPay(address), + Amount::from(10), + &authority_state, + ); + assert!(authority_state + .handle_confirmation_order(ConfirmationOrder::new(certified_transfer_order.clone())) + .is_ok()); + let account = authority_state.accounts.get(&address).unwrap(); + assert_eq!(Balance::from(1), account.balance); + assert_eq!(SequenceNumber::from(1), account.next_sequence_number); + assert_eq!(account.confirmed_log.len(), 1); +} + +#[test] +fn test_handle_cross_shard_recipient_commit() { + let (sender, sender_key) = get_key_pair(); + let (recipient, _) = get_key_pair(); + // Sender has no account on this shard. + let mut authority_state = init_state_with_account(recipient, Balance::from(1)); + let certified_transfer_order = init_certified_transfer_order( + sender, + &sender_key, + Address::FastPay(recipient), + Amount::from(10), + &authority_state, + ); + assert!(authority_state + .handle_cross_shard_recipient_commit(certified_transfer_order.clone()) + .is_ok()); + let account = authority_state.accounts.get(&recipient).unwrap(); + assert_eq!(Balance::from(11), account.balance); + assert_eq!(SequenceNumber::from(0), account.next_sequence_number); + assert_eq!(account.confirmed_log.len(), 0); +} + +#[test] +fn test_handle_confirmation_order_ok() { + let (sender, sender_key) = get_key_pair(); + let recipient = dbg_addr(2); + let mut authority_state = init_state_with_account(sender, Balance::from(5)); + let certified_transfer_order = init_certified_transfer_order( + sender, + &sender_key, + Address::FastPay(recipient), + Amount::from(5), + &authority_state, + ); + + let old_account = authority_state.accounts.get_mut(&sender).unwrap(); + let mut next_sequence_number = old_account.next_sequence_number; + next_sequence_number = next_sequence_number.increment().unwrap(); + let mut remaining_balance = old_account.balance; + remaining_balance = remaining_balance + .sub(certified_transfer_order.value.transfer.amount.into()) + .unwrap(); + + let (info, _) = authority_state + .handle_confirmation_order(ConfirmationOrder::new(certified_transfer_order.clone())) + .unwrap(); + assert_eq!(sender, info.sender); + assert_eq!(remaining_balance, info.balance.into()); + assert_eq!(next_sequence_number, info.next_sequence_number); + assert_eq!(None, info.pending_confirmation); + assert_eq!( + authority_state.accounts.get(&sender).unwrap().confirmed_log, + vec![certified_transfer_order.clone()] + ); + + let recipient_account = authority_state.accounts.get(&recipient).unwrap(); + assert_eq!( + recipient_account.balance, + certified_transfer_order.value.transfer.amount.into() + ); + + let info_request = AccountInfoRequest { + sender: recipient, + request_sequence_number: None, + request_received_transfers_excluding_first_nth: Some(0), + }; + let response = authority_state + .handle_account_info_request(info_request) + .unwrap(); + assert_eq!(response.requested_received_transfers.len(), 1); + assert_eq!( + response.requested_received_transfers[0] + .value + .transfer + .amount, + Amount::from(5) + ); +} + +#[test] +fn test_handle_primary_synchronization_order_update() { + let mut state = init_state(); + let mut updated_transaction_index = state.last_transaction_index; + let address = dbg_addr(1); + let order = init_primary_synchronization_order(address); + + assert!(state + .handle_primary_synchronization_order(order.clone()) + .is_ok()); + updated_transaction_index = updated_transaction_index.increment().unwrap(); + assert_eq!(state.last_transaction_index, updated_transaction_index); + let account = state.accounts.get(&address).unwrap(); + assert_eq!(account.balance, order.amount.into()); + assert_eq!(state.accounts.len(), 1); +} + +#[test] +fn test_handle_primary_synchronization_order_double_spend() { + let mut state = init_state(); + let mut updated_transaction_index = state.last_transaction_index; + let address = dbg_addr(1); + let order = init_primary_synchronization_order(address); + + assert!(state + .handle_primary_synchronization_order(order.clone()) + .is_ok()); + updated_transaction_index = updated_transaction_index.increment().unwrap(); + // Replays are ignored. + assert!(state + .handle_primary_synchronization_order(order.clone()) + .is_ok()); + assert_eq!(state.last_transaction_index, updated_transaction_index); + let account = state.accounts.get(&address).unwrap(); + assert_eq!(account.balance, order.amount.into()); + assert_eq!(state.accounts.len(), 1); +} + +#[test] +fn test_account_state_ok() { + let sender = dbg_addr(1); + let authority_state = init_state_with_account(sender, Balance::from(5)); + assert_eq!( + authority_state.accounts.get(&sender).unwrap(), + authority_state.account_state(&sender).unwrap() + ); +} + +#[test] +fn test_account_state_unknown_account() { + let sender = dbg_addr(1); + let unknown_address = dbg_addr(99); + let authority_state = init_state_with_account(sender, Balance::from(5)); + assert!(authority_state.account_state(&unknown_address).is_err()); +} + +#[test] +fn test_get_shards() { + let num_shards = 16u32; + let mut found = vec![false; num_shards as usize]; + let mut left = num_shards; + loop { + let (address, _) = get_key_pair(); + let shard = AuthorityState::get_shard(num_shards, &address) as usize; + println!("found {}", shard); + if !found[shard] { + found[shard] = true; + left -= 1; + if left == 0 { + break; + } + } + } +} + +// helpers + +#[cfg(test)] +fn init_state() -> AuthorityState { + let (authority_address, authority_key) = get_key_pair(); + let mut authorities = BTreeMap::new(); + authorities.insert( + /* address */ authority_address, + /* voting right */ 1, + ); + let committee = Committee::new(authorities); + AuthorityState::new(committee, authority_address, authority_key) +} + +#[cfg(test)] +fn init_state_with_accounts>( + balances: I, +) -> AuthorityState { + let mut state = init_state(); + for (address, balance) in balances { + let account = state + .accounts + .entry(address) + .or_insert(AccountOffchainState::new()); + account.balance = balance; + } + state +} + +#[cfg(test)] +fn init_state_with_account(address: FastPayAddress, balance: Balance) -> AuthorityState { + init_state_with_accounts(std::iter::once((address, balance))) +} + +#[cfg(test)] +fn init_transfer_order( + sender: FastPayAddress, + secret: &SecretKey, + recipient: Address, + amount: Amount, +) -> TransferOrder { + let transfer = Transfer { + sender: sender, + recipient: recipient, + amount, + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + TransferOrder::new(transfer, &secret) +} + +#[cfg(test)] +fn init_certified_transfer_order( + sender: FastPayAddress, + secret: &SecretKey, + recipient: Address, + amount: Amount, + authority_state: &AuthorityState, +) -> CertifiedTransferOrder { + let transfer_order = init_transfer_order(sender, secret, recipient, amount); + let vote = SignedTransferOrder::new( + transfer_order.clone(), + authority_state.name, + &authority_state.secret, + ); + let mut builder = + SignatureAggregator::try_new(transfer_order, &authority_state.committee).unwrap(); + builder + .append(vote.authority, vote.signature) + .unwrap() + .unwrap() +} + +#[cfg(test)] +fn init_primary_synchronization_order(recipient: FastPayAddress) -> PrimarySynchronizationOrder { + let mut transaction_index = VersionNumber::new(); + transaction_index = transaction_index.increment().unwrap(); + PrimarySynchronizationOrder { + recipient: recipient, + amount: Amount::from(5), + transaction_index: transaction_index, + } +} diff --git a/rust/fastpay_core/src/unit_tests/base_types_tests.rs b/rust/fastpay_core/src/unit_tests/base_types_tests.rs new file mode 100644 index 0000000000000..cce8883428779 --- /dev/null +++ b/rust/fastpay_core/src/unit_tests/base_types_tests.rs @@ -0,0 +1,21 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +#[test] +fn test_fake_signatures() { + let (addr1, sec1) = get_key_pair(); + let (addr2, _sec2) = get_key_pair(); + + let s = Signature::new(b"hello", &sec1); + assert!(s.check(b"hello", addr1).is_ok()); + assert!(s.check(b"hello", addr2).is_err()); + assert!(s.check(b"hellx", addr1).is_err()); +} + +#[test] +fn test_max_sequence_number() { + let max = SequenceNumber::max(); + assert_eq!(max.0 * 2 + 1, std::u64::MAX); +} diff --git a/rust/fastpay_core/src/unit_tests/client_tests.rs b/rust/fastpay_core/src/unit_tests/client_tests.rs new file mode 100644 index 0000000000000..c709908f00e42 --- /dev/null +++ b/rust/fastpay_core/src/unit_tests/client_tests.rs @@ -0,0 +1,420 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::authority::{AccountOffchainState, Authority, AuthorityState}; +use crate::base_types::Amount; +use futures::lock::Mutex; +use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; +use tokio::runtime::Runtime; + +#[derive(Clone)] +struct LocalAuthorityClient(Arc>); + +impl AuthorityClient for LocalAuthorityClient { + fn handle_transfer_order( + &mut self, + order: TransferOrder, + ) -> AsyncResult { + let state = self.0.clone(); + Box::pin(async move { state.lock().await.handle_transfer_order(order) }) + } + + fn handle_confirmation_order( + &mut self, + order: ConfirmationOrder, + ) -> AsyncResult { + let state = self.0.clone(); + Box::pin(async move { + state + .lock() + .await + .handle_confirmation_order(order) + .and_then(|(info, _)| Ok(info)) + }) + } + + fn handle_account_info_request( + &mut self, + request: AccountInfoRequest, + ) -> AsyncResult { + let state = self.0.clone(); + Box::pin(async move { state.lock().await.handle_account_info_request(request) }) + } +} + +impl LocalAuthorityClient { + fn new(state: AuthorityState) -> Self { + Self(Arc::new(Mutex::new(state))) + } +} + +#[cfg(test)] +fn init_local_authorities( + count: usize, +) -> (HashMap, Committee) { + let mut key_pairs = Vec::new(); + let mut voting_rights = BTreeMap::new(); + for _ in 0..count { + let key_pair = get_key_pair(); + voting_rights.insert(key_pair.0, 1); + key_pairs.push(key_pair); + } + let committee = Committee::new(voting_rights); + + let mut clients = HashMap::new(); + for (address, secret) in key_pairs { + let state = AuthorityState::new(committee.clone(), address, secret); + clients.insert(address, LocalAuthorityClient::new(state)); + } + (clients, committee) +} + +#[cfg(test)] +fn init_local_authorities_bad_1( + count: usize, +) -> (HashMap, Committee) { + let mut key_pairs = Vec::new(); + let mut voting_rights = BTreeMap::new(); + for i in 0..count { + let key_pair = get_key_pair(); + voting_rights.insert(key_pair.0, 1); + if i + 1 < (count + 2) / 3 { + // init 1 authority with a bad keypair + key_pairs.push(get_key_pair()); + } else { + key_pairs.push(key_pair); + } + } + let committee = Committee::new(voting_rights); + + let mut clients = HashMap::new(); + for (address, secret) in key_pairs { + let state = AuthorityState::new(committee.clone(), address, secret); + clients.insert(address, LocalAuthorityClient::new(state)); + } + (clients, committee) +} + +#[cfg(test)] +fn make_client( + authority_clients: HashMap, + committee: Committee, +) -> ClientState { + let (address, secret) = get_key_pair(); + ClientState::new( + address, + secret, + committee, + authority_clients, + SequenceNumber::new(), + Vec::new(), + Vec::new(), + Balance::from(0), + ) +} + +#[cfg(test)] +fn fund_account>( + clients: &mut HashMap, + address: FastPayAddress, + balances: I, +) { + let mut balances = balances.into_iter().map(Balance::from); + for (_, client) in clients.iter_mut() { + client.0.as_ref().try_lock().unwrap().accounts_mut().insert( + address, + AccountOffchainState::new_with_balance( + balances.next().unwrap_or(Balance::zero()), + /* no receive log to justify the balances */ Vec::new(), + ), + ); + } +} + +#[cfg(test)] +fn init_local_client_state(balances: Vec) -> ClientState { + let (mut authority_clients, committee) = init_local_authorities(balances.len()); + let client = make_client(authority_clients.clone(), committee.clone()); + fund_account(&mut authority_clients, client.address, balances); + client +} + +#[cfg(test)] +fn init_local_client_state_with_bad_authority( + balances: Vec, +) -> ClientState { + let (mut authority_clients, committee) = init_local_authorities_bad_1(balances.len()); + let client = make_client(authority_clients.clone(), committee); + fund_account(&mut authority_clients, client.address, balances); + client +} + +#[test] +fn test_get_strong_majority_balance() { + let mut rt = Runtime::new().unwrap(); + rt.block_on(async { + let mut client = init_local_client_state(vec![3, 4, 4, 4]); + assert_eq!(client.get_strong_majority_balance().await, Balance::from(4)); + + let mut client = init_local_client_state(vec![0, 3, 4, 4]); + assert_eq!(client.get_strong_majority_balance().await, Balance::from(3)); + + let mut client = init_local_client_state(vec![0, 3, 4]); + assert_eq!(client.get_strong_majority_balance().await, Balance::from(0)); + }); +} + +#[test] +fn test_initiating_valid_transfer() { + let mut rt = Runtime::new().unwrap(); + let (recipient, _) = get_key_pair(); + + let mut sender = init_local_client_state(vec![2, 4, 4, 4]); + sender.balance = Balance::from(4); + let certificate = rt + .block_on(sender.transfer_to_fastpay( + Amount::from(3), + recipient, + UserData(Some(b"hello...........hello...........".clone())), + )) + .unwrap(); + assert_eq!(sender.next_sequence_number, SequenceNumber::from(1)); + assert_eq!(sender.pending_transfer, None); + assert_eq!( + rt.block_on(sender.get_strong_majority_balance()), + Balance::from(1) + ); + assert_eq!( + rt.block_on(sender.request_certificate(sender.address, SequenceNumber::from(0))) + .unwrap(), + certificate + ); +} + +#[test] +fn test_initiating_valid_transfer_despite_bad_authority() { + let mut rt = Runtime::new().unwrap(); + let (recipient, _) = get_key_pair(); + + let mut sender = init_local_client_state_with_bad_authority(vec![4, 4, 4, 4]); + sender.balance = Balance::from(4); + let certificate = rt + .block_on(sender.transfer_to_fastpay( + Amount::from(3), + recipient, + UserData(Some(b"hello...........hello...........".clone())), + )) + .unwrap(); + assert_eq!(sender.next_sequence_number, SequenceNumber::from(1)); + assert_eq!(sender.pending_transfer, None); + assert_eq!( + rt.block_on(sender.get_strong_majority_balance()), + Balance::from(1) + ); + assert_eq!( + rt.block_on(sender.request_certificate(sender.address, SequenceNumber::from(0))) + .unwrap(), + certificate + ); +} + +#[test] +fn test_initiating_transfer_low_funds() { + let mut rt = Runtime::new().unwrap(); + let (recipient, _) = get_key_pair(); + + let mut sender = init_local_client_state(vec![2, 2, 4, 4]); + sender.balance = Balance::from(2); + assert!(rt + .block_on(sender.transfer_to_fastpay(Amount::from(3), recipient, UserData::default())) + .is_err()); + // Trying to overspend does not block an account. + assert_eq!(sender.next_sequence_number, SequenceNumber::from(0)); + assert_eq!(sender.pending_transfer, None); + assert_eq!( + rt.block_on(sender.get_strong_majority_balance()), + Balance::from(2) + ); +} + +#[test] +fn test_bidirectional_transfer() { + let mut rt = Runtime::new().unwrap(); + let (mut authority_clients, committee) = init_local_authorities(4); + let mut client1 = make_client(authority_clients.clone(), committee.clone()); + let mut client2 = make_client(authority_clients.clone(), committee); + fund_account(&mut authority_clients, client1.address, vec![2, 3, 4, 4]); + // Update client1's local balance accordingly. + client1.balance = rt.block_on(client1.get_strong_majority_balance()); + assert_eq!(client1.balance, Balance::from(3)); + + let certificate = rt + .block_on(client1.transfer_to_fastpay( + Amount::from(3), + client2.address, + UserData::default(), + )) + .unwrap(); + + assert_eq!(client1.next_sequence_number, SequenceNumber::from(1)); + assert_eq!(client1.pending_transfer, None); + assert_eq!( + rt.block_on(client1.get_strong_majority_balance()), + Balance::from(0) + ); + assert_eq!(client1.balance, Balance::from(0)); + assert_eq!( + rt.block_on(client1.get_strong_majority_sequence_number(client1.address)), + SequenceNumber::from(1) + ); + + assert_eq!( + rt.block_on(client1.request_certificate(client1.address, SequenceNumber::from(0))) + .unwrap(), + certificate + ); + // Our sender already confirmed. + assert_eq!( + rt.block_on(client2.get_strong_majority_balance()), + Balance::from(3) + ); + assert_eq!(client2.balance, Balance::from(0)); + // Try to confirm again. + rt.block_on(client2.receive_from_fastpay(certificate)) + .unwrap(); + assert_eq!( + rt.block_on(client2.get_strong_majority_balance()), + Balance::from(3) + ); + assert_eq!(client2.balance, Balance::from(3)); + + // Send back some money. + assert_eq!(client2.next_sequence_number, SequenceNumber::from(0)); + rt.block_on(client2.transfer_to_fastpay(Amount::from(1), client1.address, UserData::default())) + .unwrap(); + assert_eq!(client2.next_sequence_number, SequenceNumber::from(1)); + assert_eq!(client2.pending_transfer, None); + assert_eq!( + rt.block_on(client2.get_strong_majority_balance()), + Balance::from(2) + ); + assert_eq!( + rt.block_on(client2.get_strong_majority_sequence_number(client2.address)), + SequenceNumber::from(1) + ); + assert_eq!( + rt.block_on(client1.get_strong_majority_balance()), + Balance::from(1) + ); +} + +#[test] +fn test_receiving_unconfirmed_transfer() { + let mut rt = Runtime::new().unwrap(); + let (mut authority_clients, committee) = init_local_authorities(4); + let mut client1 = make_client(authority_clients.clone(), committee.clone()); + let mut client2 = make_client(authority_clients.clone(), committee); + fund_account(&mut authority_clients, client1.address, vec![2, 3, 4, 4]); + // not updating client1.balance + + let certificate = rt + .block_on(client1.transfer_to_fastpay_unsafe_unconfirmed( + Amount::from(2), + client2.address, + UserData::default(), + )) + .unwrap(); + // Transfer was executed locally, creating negative balance. + assert_eq!(client1.balance, Balance::from(-2)); + assert_eq!(client1.next_sequence_number, SequenceNumber::from(1)); + assert_eq!(client1.pending_transfer, None); + // ..but not confirmed remotely, hence an unchanged balance and sequence number. + assert_eq!( + rt.block_on(client1.get_strong_majority_balance()), + Balance::from(3) + ); + assert_eq!( + rt.block_on(client1.get_strong_majority_sequence_number(client1.address)), + SequenceNumber::from(0) + ); + // Let the receiver confirm in last resort. + rt.block_on(client2.receive_from_fastpay(certificate)) + .unwrap(); + assert_eq!( + rt.block_on(client2.get_strong_majority_balance()), + Balance::from(2) + ); +} + +#[test] +fn test_receiving_unconfirmed_transfer_with_lagging_sender_balances() { + let mut rt = Runtime::new().unwrap(); + let (mut authority_clients, committee) = init_local_authorities(4); + let mut client0 = make_client(authority_clients.clone(), committee.clone()); + let mut client1 = make_client(authority_clients.clone(), committee.clone()); + let mut client2 = make_client(authority_clients.clone(), committee); + fund_account(&mut authority_clients, client0.address, vec![2, 3, 4, 4]); + // not updating client balances + + // transferring funds from client0 to client1. + // confirming to a quorum of node only at the end. + rt.block_on(async { + client0 + .transfer_to_fastpay_unsafe_unconfirmed( + Amount::from(1), + client1.address, + UserData::default(), + ) + .await + .unwrap(); + client0 + .transfer_to_fastpay_unsafe_unconfirmed( + Amount::from(1), + client1.address, + UserData::default(), + ) + .await + .unwrap(); + client0 + .communicate_transfers( + client0.address, + client0.sent_certificates.clone(), + CommunicateAction::SynchronizeNextSequenceNumber(client0.next_sequence_number), + ) + .await + .unwrap(); + }); + // transferring funds from client1 to client2 without confirmation + let certificate = rt + .block_on(client1.transfer_to_fastpay_unsafe_unconfirmed( + Amount::from(2), + client2.address, + UserData::default(), + )) + .unwrap(); + // Transfers were executed locally, possibly creating negative balances. + assert_eq!(client0.balance, Balance::from(-2)); + assert_eq!(client0.next_sequence_number, SequenceNumber::from(2)); + assert_eq!(client0.pending_transfer, None); + assert_eq!(client1.balance, Balance::from(-2)); + assert_eq!(client1.next_sequence_number, SequenceNumber::from(1)); + assert_eq!(client1.pending_transfer, None); + // Last one was not confirmed remotely, hence an unchanged (remote) balance and sequence number. + assert_eq!( + rt.block_on(client1.get_strong_majority_balance()), + Balance::from(2) + ); + assert_eq!( + rt.block_on(client1.get_strong_majority_sequence_number(client1.address)), + SequenceNumber::from(0) + ); + // Let the receiver confirm in last resort. + rt.block_on(client2.receive_from_fastpay(certificate)) + .unwrap(); + assert_eq!( + rt.block_on(client2.get_strong_majority_balance()), + Balance::from(2) + ); +} diff --git a/rust/fastpay_core/src/unit_tests/downloader_tests.rs b/rust/fastpay_core/src/unit_tests/downloader_tests.rs new file mode 100644 index 0000000000000..970893669518d --- /dev/null +++ b/rust/fastpay_core/src/unit_tests/downloader_tests.rs @@ -0,0 +1,44 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use futures::future; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::Arc; +use tokio::runtime::Runtime; + +#[derive(Clone)] +struct LocalRequester(Arc); + +impl LocalRequester { + fn new() -> Self { + Self(Arc::new(AtomicU32::new(0))) + } +} + +impl Requester for LocalRequester { + type Key = &'static str; + type Value = u32; + + fn query(&mut self, _key: Self::Key) -> future::BoxFuture { + Box::pin(future::ready(self.0.fetch_add(1, Ordering::Relaxed))) + } +} + +#[test] +fn test_local_downloader() { + let mut rt = Runtime::new().unwrap(); + rt.block_on(async move { + let requester = LocalRequester::new(); + let (task, mut handle) = Downloader::start(requester, vec![("a", 10), ("d", 11)]); + assert_eq!(handle.query("b").await.unwrap(), 0); + assert_eq!(handle.query("a").await.unwrap(), 10); + assert_eq!(handle.query("d").await.unwrap(), 11); + assert_eq!(handle.query("c").await.unwrap(), 1); + assert_eq!(handle.query("b").await.unwrap(), 0); + handle.stop().await.unwrap(); + let values: Vec<_> = task.await.unwrap().collect(); + // Cached values are returned ordered by keys. + assert_eq!(values, vec![10, 0, 1, 11]); + }); +} diff --git a/rust/fastpay_core/src/unit_tests/fastpay_smart_contract_tests.rs b/rust/fastpay_core/src/unit_tests/fastpay_smart_contract_tests.rs new file mode 100644 index 0000000000000..14cfb575b788f --- /dev/null +++ b/rust/fastpay_core/src/unit_tests/fastpay_smart_contract_tests.rs @@ -0,0 +1,180 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +// handle_funding_transaction +#[test] +fn test_handle_funding_transaction_zero_amount() { + let (mut contract_state, _name, _secret) = init_contract(); + let mut funding_transaction = init_funding_transaction(); + funding_transaction.primary_coins = Amount::zero(); + + assert!(contract_state + .handle_funding_transaction(funding_transaction) + .is_err()); + assert_eq!(contract_state.total_balance, Amount::zero()); + assert_eq!(contract_state.last_transaction_index, VersionNumber::new()); + assert!(contract_state.blockchain.is_empty()); + assert!(contract_state.accounts.is_empty()); +} + +#[test] +fn test_handle_funding_transaction_ok() { + let (mut contract_state, _name, _secret) = init_contract(); + let funding_transaction = init_funding_transaction(); + + assert!(contract_state + .handle_funding_transaction(funding_transaction.clone()) + .is_ok()); + assert_eq!( + contract_state.total_balance, + funding_transaction.primary_coins + ); + let mut updated_last_transaction_index = VersionNumber::new(); + updated_last_transaction_index = updated_last_transaction_index.increment().unwrap(); + assert_eq!( + contract_state.last_transaction_index, + updated_last_transaction_index + ); + assert_eq!(contract_state.blockchain.len(), 1); + assert_eq!(contract_state.blockchain[0], funding_transaction); + assert!(contract_state.accounts.is_empty()); +} + +// handle_redeem_transaction + +#[test] +fn test_handle_redeem_transaction_ok() { + let (mut contract_state, name, secret) = init_contract(); + let redeem_transaction = + init_redeem_transaction(contract_state.committee.clone(), name, secret); + let funding_transaction = init_funding_transaction(); + assert!(contract_state + .handle_funding_transaction(funding_transaction) + .is_ok()); + let mut old_total_balance = contract_state.total_balance; + + assert!(contract_state + .handle_redeem_transaction(redeem_transaction.clone()) + .is_ok()); + let sender = redeem_transaction + .transfer_certificate + .value + .transfer + .sender; + let amount = redeem_transaction + .transfer_certificate + .value + .transfer + .amount; + let account = contract_state.accounts.get(&sender).unwrap(); + let sequence_number = redeem_transaction + .transfer_certificate + .value + .transfer + .sequence_number; + assert_eq!(account.last_redeemed, Some(sequence_number)); + old_total_balance = old_total_balance.sub(amount).unwrap(); + assert_eq!(contract_state.total_balance, old_total_balance); +} + +#[test] +fn test_handle_redeem_transaction_negative_balance() { + let (mut contract_state, name, secret) = init_contract(); + let mut redeem_transaction = + init_redeem_transaction(contract_state.committee.clone(), name, secret); + let funding_transaction = init_funding_transaction(); + let too_much_money = Amount::from(1000); + assert!(contract_state + .handle_funding_transaction(funding_transaction) + .is_ok()); + let old_balance = contract_state.total_balance; + + redeem_transaction + .transfer_certificate + .value + .transfer + .amount = redeem_transaction + .transfer_certificate + .value + .transfer + .amount + .add(too_much_money) + .unwrap(); + assert!(contract_state + .handle_redeem_transaction(redeem_transaction.clone()) + .is_err()); + assert_eq!(old_balance, contract_state.total_balance); + assert!(contract_state.accounts.is_empty()); +} + +#[test] +fn test_handle_redeem_transaction_double_spend() { + let (mut contract_state, name, secret) = init_contract(); + let redeem_transaction = + init_redeem_transaction(contract_state.committee.clone(), name, secret); + let funding_transaction = init_funding_transaction(); + assert!(contract_state + .handle_funding_transaction(funding_transaction) + .is_ok()); + assert!(contract_state + .handle_redeem_transaction(redeem_transaction.clone()) + .is_ok()); + let old_balance = contract_state.total_balance; + + assert!(contract_state + .handle_redeem_transaction(redeem_transaction.clone()) + .is_err()); + assert_eq!(old_balance, contract_state.total_balance); +} + +// helpers +#[cfg(test)] +fn init_contract() -> (FastPaySmartContractState, AuthorityName, SecretKey) { + let (authority_address, authority_key) = get_key_pair(); + let mut authorities = BTreeMap::new(); + authorities.insert( + /* address */ authority_address, + /* voting right */ 1, + ); + let committee = Committee::new(authorities); + ( + FastPaySmartContractState::new(committee), + authority_address, + authority_key, + ) +} + +fn init_funding_transaction() -> FundingTransaction { + FundingTransaction { + recipient: dbg_addr(1), + primary_coins: Amount::from(5), + } +} + +#[cfg(test)] +fn init_redeem_transaction( + committee: Committee, + name: AuthorityName, + secret: SecretKey, +) -> RedeemTransaction { + let (sender_address, sender_key) = get_key_pair(); + let primary_transfer = Transfer { + sender: sender_address, + recipient: Address::Primary(dbg_addr(2)), + amount: Amount::from(3), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let order = TransferOrder::new(primary_transfer, &sender_key); + let vote = SignedTransferOrder::new(order.clone(), name, &secret); + let mut builder = SignatureAggregator::try_new(order, &committee).unwrap(); + let certificate = builder + .append(vote.authority, vote.signature) + .unwrap() + .unwrap(); + RedeemTransaction { + transfer_certificate: certificate, + } +} diff --git a/rust/fastpay_core/src/unit_tests/messages_tests.rs b/rust/fastpay_core/src/unit_tests/messages_tests.rs new file mode 100644 index 0000000000000..7f7a184e5cda8 --- /dev/null +++ b/rust/fastpay_core/src/unit_tests/messages_tests.rs @@ -0,0 +1,84 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use std::collections::BTreeMap; + +#[test] +fn test_signed_values() { + let mut authorities = BTreeMap::new(); + let (a1, sec1) = get_key_pair(); + let (a2, sec2) = get_key_pair(); + let (a3, sec3) = get_key_pair(); + + authorities.insert(/* address */ a1, /* voting right */ 1); + authorities.insert(/* address */ a2, /* voting right */ 0); + let committee = Committee::new(authorities); + + let transfer = Transfer { + sender: a1, + recipient: Address::FastPay(a2), + amount: Amount::from(1), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let order = TransferOrder::new(transfer.clone(), &sec1); + let bad_order = TransferOrder::new(transfer, &sec2); + + let v = SignedTransferOrder::new(order.clone(), a1, &sec1); + assert!(v.check(&committee).is_ok()); + + let v = SignedTransferOrder::new(order.clone(), a2, &sec2); + assert!(v.check(&committee).is_err()); + + let v = SignedTransferOrder::new(order, a3, &sec3); + assert!(v.check(&committee).is_err()); + + let v = SignedTransferOrder::new(bad_order, a1, &sec1); + assert!(v.check(&committee).is_err()); +} + +#[test] +fn test_certificates() { + let (a1, sec1) = get_key_pair(); + let (a2, sec2) = get_key_pair(); + let (a3, sec3) = get_key_pair(); + + let mut authorities = BTreeMap::new(); + authorities.insert(/* address */ a1, /* voting right */ 1); + authorities.insert(/* address */ a2, /* voting right */ 1); + let committee = Committee::new(authorities); + + let transfer = Transfer { + sender: a1, + recipient: Address::FastPay(a2), + amount: Amount::from(1), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let order = TransferOrder::new(transfer.clone(), &sec1); + let bad_order = TransferOrder::new(transfer, &sec2); + + let v1 = SignedTransferOrder::new(order.clone(), a1, &sec1); + let v2 = SignedTransferOrder::new(order.clone(), a2, &sec2); + let v3 = SignedTransferOrder::new(order.clone(), a3, &sec3); + + let mut builder = SignatureAggregator::try_new(order.clone(), &committee).unwrap(); + assert!(builder + .append(v1.authority, v1.signature) + .unwrap() + .is_none()); + let mut c = builder.append(v2.authority, v2.signature).unwrap().unwrap(); + assert!(c.check(&committee).is_ok()); + c.signatures.pop(); + assert!(c.check(&committee).is_err()); + + let mut builder = SignatureAggregator::try_new(order.clone(), &committee).unwrap(); + assert!(builder + .append(v1.authority, v1.signature) + .unwrap() + .is_none()); + assert!(builder.append(v3.authority, v3.signature).is_err()); + + assert!(SignatureAggregator::try_new(bad_order.clone(), &committee).is_err()); +} diff --git a/rust/fastpay_core/src/unit_tests/serialize_tests.rs b/rust/fastpay_core/src/unit_tests/serialize_tests.rs new file mode 100644 index 0000000000000..dc8692439ac71 --- /dev/null +++ b/rust/fastpay_core/src/unit_tests/serialize_tests.rs @@ -0,0 +1,338 @@ +// Copyright (c) Facebook Inc. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::base_types::*; +use std::time::Instant; + +#[test] +fn test_error() { + let err = FastPayError::UnknownSigner; + let buf = serialize_error(&err); + let result = deserialize_message(buf.as_slice()); + assert!(result.is_ok()); + if let SerializedMessage::Error(o) = result.unwrap() { + assert!(o == err); + } else { + assert!(false) + } +} + +#[test] +fn test_info_request() { + let req1 = AccountInfoRequest { + sender: dbg_addr(0x20), + request_sequence_number: None, + request_received_transfers_excluding_first_nth: None, + }; + let req2 = AccountInfoRequest { + sender: dbg_addr(0x20), + request_sequence_number: Some(SequenceNumber::from(129)), + request_received_transfers_excluding_first_nth: None, + }; + + let buf1 = serialize_info_request(&req1); + let buf2 = serialize_info_request(&req2); + + let result1 = deserialize_message(buf1.as_slice()); + let result2 = deserialize_message(buf2.as_slice()); + assert!(result1.is_ok()); + assert!(result2.is_ok()); + + if let SerializedMessage::InfoReq(o) = result1.unwrap() { + assert!(o == req1); + } else { + assert!(false) + } + if let SerializedMessage::InfoReq(o) = result2.unwrap() { + assert!(o == req2); + } else { + assert!(false) + } +} + +#[test] +fn test_order() { + let (sender_name, sender_key) = get_key_pair(); + + let transfer = Transfer { + sender: sender_name, + recipient: Address::Primary(dbg_addr(0x20)), + amount: Amount::from(5), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let transfer_order = TransferOrder::new(transfer, &sender_key); + + let buf = serialize_transfer_order(&transfer_order); + let result = deserialize_message(buf.as_slice()); + assert!(result.is_ok()); + if let SerializedMessage::Order(o) = result.unwrap() { + assert!(o == transfer_order); + } else { + assert!(false) + } + + let (sender_name, sender_key) = get_key_pair(); + let transfer2 = Transfer { + sender: sender_name, + recipient: Address::FastPay(dbg_addr(0x20)), + amount: Amount::from(5), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let transfer_order2 = TransferOrder::new(transfer2, &sender_key); + + let buf = serialize_transfer_order(&transfer_order2); + let result = deserialize_message(buf.as_slice()); + assert!(result.is_ok()); + if let SerializedMessage::Order(o) = result.unwrap() { + assert!(o == transfer_order2); + } else { + assert!(false) + } +} + +#[test] +fn test_vote() { + let (sender_name, sender_key) = get_key_pair(); + let transfer = Transfer { + sender: sender_name, + recipient: Address::Primary(dbg_addr(0x20)), + amount: Amount::from(5), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let order = TransferOrder::new(transfer, &sender_key); + + let (authority_name, authority_key) = get_key_pair(); + let vote = SignedTransferOrder::new(order, authority_name, &authority_key); + + let buf = serialize_vote(&vote); + let result = deserialize_message(buf.as_slice()); + assert!(result.is_ok()); + if let SerializedMessage::Vote(o) = result.unwrap() { + assert!(o == vote); + } else { + assert!(false) + } +} + +#[test] +fn test_cert() { + let (sender_name, sender_key) = get_key_pair(); + let transfer = Transfer { + sender: sender_name, + recipient: Address::Primary(dbg_addr(0x20)), + amount: Amount::from(5), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let order = TransferOrder::new(transfer, &sender_key); + let mut cert = CertifiedTransferOrder { + value: order, + signatures: Vec::new(), + }; + + for _ in 0..3 { + let (authority_name, authority_key) = get_key_pair(); + let sig = Signature::new(&cert.value, &authority_key); + + cert.signatures.push((authority_name, sig)); + } + + let buf = serialize_cert(&cert); + let result = deserialize_message(buf.as_slice()); + assert!(result.is_ok()); + if let SerializedMessage::Cert(o) = result.unwrap() { + assert!(o == cert); + } else { + assert!(false) + } +} + +#[test] +fn test_info_response() { + let (sender_name, sender_key) = get_key_pair(); + let transfer = Transfer { + sender: sender_name, + recipient: Address::Primary(dbg_addr(0x20)), + amount: Amount::from(5), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let order = TransferOrder::new(transfer, &sender_key); + + let (auth_name, auth_key) = get_key_pair(); + let vote = SignedTransferOrder::new(order.clone(), auth_name, &auth_key); + + let mut cert = CertifiedTransferOrder { + value: order.clone(), + signatures: Vec::new(), + }; + + for _ in 0..3 { + let (authority_name, authority_key) = get_key_pair(); + let sig = Signature::new(&cert.value, &authority_key); + + cert.signatures.push((authority_name, sig)); + } + + let resp1 = AccountInfoResponse { + sender: dbg_addr(0x20), + balance: Balance::from(50), + next_sequence_number: SequenceNumber::new(), + pending_confirmation: None, + requested_certificate: None, + requested_received_transfers: Vec::new(), + }; + let resp2 = AccountInfoResponse { + sender: dbg_addr(0x20), + balance: Balance::from(50), + next_sequence_number: SequenceNumber::new(), + pending_confirmation: Some(vote.clone()), + requested_certificate: None, + requested_received_transfers: Vec::new(), + }; + let resp3 = AccountInfoResponse { + sender: dbg_addr(0x20), + balance: Balance::from(50), + next_sequence_number: SequenceNumber::new(), + pending_confirmation: None, + requested_certificate: Some(cert.clone()), + requested_received_transfers: Vec::new(), + }; + let resp4 = AccountInfoResponse { + sender: dbg_addr(0x20), + balance: Balance::from(50), + next_sequence_number: SequenceNumber::new(), + pending_confirmation: Some(vote), + requested_certificate: Some(cert), + requested_received_transfers: Vec::new(), + }; + + for resp in [resp1, resp2, resp3, resp4].iter() { + let buf = serialize_info_response(&resp); + let result = deserialize_message(buf.as_slice()); + assert!(result.is_ok()); + if let SerializedMessage::InfoResp(o) = result.unwrap() { + assert!(o == *resp); + } else { + assert!(false) + } + } +} + +#[test] +fn test_time_order() { + let (sender_name, sender_key) = get_key_pair(); + let transfer = Transfer { + sender: sender_name, + recipient: Address::Primary(dbg_addr(0x20)), + amount: Amount::from(5), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + + let mut buf = Vec::new(); + let now = Instant::now(); + for _ in 0..100 { + let transfer_order = TransferOrder::new(transfer.clone(), &sender_key); + serialize_transfer_order_into(&mut buf, &transfer_order).unwrap(); + } + println!("Write Order: {} microsec", now.elapsed().as_micros() / 100); + + let mut buf2 = buf.as_slice(); + let now = Instant::now(); + for _ in 0..100 { + if let SerializedMessage::Order(order) = deserialize_message(&mut buf2).unwrap() { + order.check_signature().unwrap(); + } + } + assert!(deserialize_message(&mut buf2).is_err()); + println!( + "Read & Check Order: {} microsec", + now.elapsed().as_micros() / 100 + ); +} + +#[test] +fn test_time_vote() { + let (sender_name, sender_key) = get_key_pair(); + let transfer = Transfer { + sender: sender_name, + recipient: Address::Primary(dbg_addr(0x20)), + amount: Amount::from(5), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let order = TransferOrder::new(transfer, &sender_key); + + let (authority_name, authority_key) = get_key_pair(); + + let mut buf = Vec::new(); + let now = Instant::now(); + for _ in 0..100 { + let vote = SignedTransferOrder::new(order.clone(), authority_name, &authority_key); + serialize_vote_into(&mut buf, &vote).unwrap(); + } + println!("Write Vote: {} microsec", now.elapsed().as_micros() / 100); + + let mut buf2 = buf.as_slice(); + let now = Instant::now(); + for _ in 0..100 { + if let SerializedMessage::Vote(vote) = deserialize_message(&mut buf2).unwrap() { + vote.signature.check(&vote.value, vote.authority).unwrap(); + } + } + assert!(deserialize_message(&mut buf2).is_err()); + println!( + "Read & Quickcheck Vote: {} microsec", + now.elapsed().as_micros() / 100 + ); +} + +#[test] +fn test_time_cert() { + let count = 100; + let (sender_name, sender_key) = get_key_pair(); + let transfer = Transfer { + sender: sender_name, + recipient: Address::Primary(dbg_addr(0)), + amount: Amount::from(5), + sequence_number: SequenceNumber::new(), + user_data: UserData::default(), + }; + let order = TransferOrder::new(transfer, &sender_key); + let mut cert = CertifiedTransferOrder { + value: order, + signatures: Vec::new(), + }; + + for _ in 0..7 { + let (authority_name, authority_key) = get_key_pair(); + let sig = Signature::new(&cert.value, &authority_key); + cert.signatures.push((authority_name, sig)); + } + + let mut buf = Vec::new(); + let now = Instant::now(); + + for _ in 0..count { + serialize_cert_into(&mut buf, &cert).unwrap(); + } + println!("Write Cert: {} microsec", now.elapsed().as_micros() / count); + + let now = Instant::now(); + let mut buf2 = buf.as_slice(); + for _ in 0..count { + if let SerializedMessage::Cert(cert) = deserialize_message(&mut buf2).unwrap() { + Signature::verify_batch(&cert.value, &cert.signatures).unwrap(); + } + } + assert!(deserialize_message(buf2).is_err()); + println!( + "Read & Quickcheck Cert: {} microsec", + now.elapsed().as_micros() / count + ); +} diff --git a/rust/rust-toolchain b/rust/rust-toolchain new file mode 100644 index 0000000000000..2bf5ad0447d33 --- /dev/null +++ b/rust/rust-toolchain @@ -0,0 +1 @@ +stable diff --git a/scripts/aggregated_parsed_logs/aggregated_latency_log.txt b/scripts/aggregated_parsed_logs/aggregated_latency_log.txt new file mode 100644 index 0000000000000..44ab431561141 --- /dev/null +++ b/scripts/aggregated_parsed_logs/aggregated_latency_log.txt @@ -0,0 +1 @@ +{'transfer': {'U.S. West Coast': [[[2, 193], [2, 193], [2, 194], [2, 188], [2, 185], [2, 190], [2, 186], [2, 186], [2, 184], [2, 193], [2, 189], [2, 191], [2, 190], [2, 192], [2, 193], [2, 193], [2, 186], [2, 187], [2, 194], [2, 194], [2, 188], [2, 184], [2, 194], [2, 192], [2, 190], [2, 189], [2, 187], [2, 192], [2, 192], [2, 183], [2, 190], [2, 192], [2, 193], [2, 193], [2, 195], [2, 185], [2, 194], [2, 188], [2, 188], [2, 188], [2, 190], [2, 192], [2, 190], [2, 192], [2, 194], [2, 191], [2, 189], [2, 184], [2, 192], [2, 187]], [[8, 193], [8, 194], [8, 196], [8, 192], [8, 194], [8, 195], [8, 194], [8, 194], [8, 186], [8, 195], [8, 193], [8, 194], [8, 194], [8, 194], [8, 197], [8, 194], [8, 193], [8, 194], [8, 185], [8, 192], [8, 193], [8, 193], [8, 194], [8, 187], [8, 192], [8, 193], [8, 189], [8, 189], [8, 195], [8, 194], [8, 187], [8, 191], [8, 193], [8, 200], [8, 192], [8, 187], [8, 281], [8, 186], [8, 194], [8, 192], [8, 187], [8, 194], [8, 192], [8, 186], [8, 187], [8, 193], [8, 193], [8, 191], [8, 406], [8, 187]], [[7, 193], [7, 193], [7, 192], [7, 192], [7, 187], [7, 186], [7, 186], [7, 194], [7, 194], [7, 192], [7, 195], [7, 194], [7, 187], [7, 194], [7, 193], [7, 195], [7, 194], [7, 191], [7, 184], [7, 195], [7, 187], [7, 212], [7, 193], [7, 195], [7, 230], [7, 195], [7, 195], [7, 197], [7, 195], [7, 193], [7, 194], [7, 190], [7, 193], [7, 187], [7, 195], [7, 189], [7, 192], [7, 195], [7, 192], [7, 356], [7, 196], [7, 193], [7, 188], [7, 189], [7, 188], [7, 194], [7, 195], [7, 192], [7, 187], [7, 194]], [[1, 193], [1, 189], [1, 188], [1, 193], [1, 187], [1, 188], [1, 187], [1, 191], [1, 186], [1, 191], [1, 189], [1, 189], [1, 193], [1, 184], [1, 192], [1, 188], [1, 184], [1, 194], [1, 183], [1, 191], [1, 184], [1, 184], [1, 189], [1, 188], [1, 185], [1, 188], [1, 191], [1, 187], [1, 192], [1, 184], [1, 190], [1, 190], [1, 187], [1, 186], [1, 183], [1, 187], [1, 189], [1, 187], [1, 191], [1, 182], [1, 190], [1, 185], [1, 182], [1, 185], [1, 193], [1, 184], [1, 183], [1, 189], [1, 188], [1, 192]], [[4, 189], [4, 196], [4, 195], [4, 194], [4, 193], [4, 190], [4, 192], [4, 196], [4, 191], [4, 200], [4, 195], [4, 196], [4, 193], [4, 186], [4, 193], [4, 187], [4, 194], [4, 191], [4, 190], [4, 186], [4, 187], [4, 195], [4, 195], [4, 194], [4, 198], [4, 194], [4, 195], [4, 194], [4, 194], [4, 192], [4, 192], [4, 193], [4, 186], [4, 195], [4, 193], [4, 188], [4, 192], [4, 191], [4, 192], [4, 192], [4, 195], [4, 190], [4, 193], [4, 215], [4, 194], [4, 189], [4, 194], [4, 187], [4, 192], [4, 187]], [[6, 186], [6, 188], [6, 187], [6, 193], [6, 193], [6, 193], [6, 188], [6, 195], [6, 191], [6, 187], [6, 189], [6, 196], [6, 195], [6, 188], [6, 194], [6, 192], [6, 191], [6, 186], [6, 189], [6, 187], [6, 192], [6, 194], [6, 190], [6, 192], [6, 191], [6, 192], [6, 194], [6, 190], [6, 194], [6, 187], [6, 194], [6, 196], [6, 191], [6, 193], [6, 191], [6, 194], [6, 186], [6, 186], [6, 194], [6, 192], [6, 194], [6, 193], [6, 195], [6, 194], [6, 194], [6, 189], [6, 195], [6, 187], [6, 193], [6, 194]], [[5, 185], [5, 188], [5, 190], [5, 186], [5, 192], [5, 188], [5, 186], [5, 192], [5, 186], [5, 184], [5, 191], [5, 186], [5, 352], [5, 622], [5, 188], [5, 187], [5, 194], [5, 193], [5, 188], [5, 190], [5, 191], [5, 194], [5, 249], [5, 188], [5, 193], [5, 192], [5, 194], [5, 192], [5, 194], [5, 192], [5, 192], [5, 193], [5, 186], [5, 187], [5, 186], [5, 192], [5, 193], [5, 194], [5, 195], [5, 193], [5, 193], [5, 194], [5, 193], [5, 187], [5, 193], [5, 192], [5, 189], [5, 187], [5, 193], [5, 186]], [[3, 270], [3, 182], [3, 183], [3, 189], [3, 195], [3, 192], [3, 191], [3, 187], [3, 187], [3, 187], [3, 195], [3, 194], [3, 190], [3, 193], [3, 191], [3, 185], [3, 183], [3, 187], [3, 191], [3, 190], [3, 190], [3, 188], [3, 188], [3, 191], [3, 189], [3, 192], [3, 188], [3, 194], [3, 192], [3, 193], [3, 191], [3, 188], [3, 195], [3, 186], [3, 192], [3, 192], [3, 191], [3, 188], [3, 194], [3, 186], [3, 205], [3, 193], [3, 192], [3, 198], [3, 193], [3, 186], [3, 191], [3, 191], [3, 190], [3, 193]], [[10, 193], [10, 192], [10, 195], [10, 194], [10, 195], [10, 193], [10, 193], [10, 188], [10, 195], [10, 196], [10, 194], [10, 194], [10, 194], [10, 193], [10, 187], [10, 189], [10, 193], [10, 205], [10, 194], [10, 194], [10, 193], [10, 193], [10, 194], [10, 194], [10, 192], [10, 193], [10, 194], [10, 192], [10, 194], [10, 193], [10, 194], [10, 193], [10, 195], [10, 193], [10, 194], [10, 193], [10, 190], [10, 194], [10, 192], [10, 194], [10, 194], [10, 188], [10, 192], [10, 194], [10, 188], [10, 196], [10, 193], [10, 194], [10, 192], [10, 195]], [[9, 187], [9, 195], [9, 200], [9, 196], [9, 192], [9, 194], [9, 193], [9, 195], [9, 187], [9, 187], [9, 193], [9, 196], [9, 201], [9, 195], [9, 195], [9, 196], [9, 187], [9, 196], [9, 195], [9, 195], [9, 196], [9, 191], [9, 191], [9, 187], [9, 187], [9, 190], [9, 196], [9, 206], [9, 244], [9, 208], [9, 202], [9, 193], [9, 192], [9, 195], [9, 199], [9, 194], [9, 195], [9, 192], [9, 218], [9, 195], [9, 193], [9, 194], [9, 195], [9, 195], [9, 187], [9, 189], [9, 190], [9, 194], [9, 188], [9, 192]]], 'U.K.': [[[1, 48], [1, 44], [1, 47], [1, 36], [1, 42], [1, 44], [1, 44], [1, 40], [1, 39], [1, 41], [1, 43], [1, 37], [1, 37], [1, 47], [1, 43], [1, 42], [1, 42], [1, 44], [1, 37], [1, 43], [1, 46], [1, 43], [1, 37], [1, 46], [1, 45], [1, 43], [1, 43], [1, 41], [1, 35], [1, 39], [1, 43], [1, 43], [1, 48], [1, 40], [1, 43], [1, 55], [1, 39], [1, 40], [1, 37], [1, 36], [1, 37], [1, 182], [1, 37], [1, 189], [1, 42], [1, 37], [1, 168], [1, 56], [1, 116], [1, 134]], [[3, 39], [3, 38], [3, 49], [3, 38], [3, 42], [3, 37], [3, 48], [3, 47], [3, 45], [3, 43], [3, 48], [3, 81], [3, 41], [3, 37], [3, 38], [3, 48], [3, 51], [3, 49], [3, 61], [3, 47], [3, 47], [3, 47], [3, 36], [3, 44], [3, 47], [3, 38], [3, 41], [3, 41], [3, 48], [3, 73], [3, 48], [3, 50], [3, 47], [3, 42], [3, 43], [3, 44], [3, 39], [3, 41], [3, 46], [3, 41], [3, 41], [3, 41], [3, 42], [3, 41], [3, 48], [3, 42], [3, 47], [3, 49], [3, 43], [3, 44]], [[5, 40], [5, 41], [5, 47], [5, 42], [5, 45], [5, 44], [5, 41], [5, 47], [5, 38], [5, 41], [5, 44], [5, 41], [5, 50], [5, 47], [5, 38], [5, 48], [5, 42], [5, 46], [5, 40], [5, 47], [5, 48], [5, 48], [5, 53], [5, 89], [5, 41], [5, 53], [5, 42], [5, 64], [5, 48], [5, 54], [5, 48], [5, 42], [5, 41], [5, 42], [5, 49], [5, 47], [5, 47], [5, 44], [5, 41], [5, 47], [5, 47], [5, 41], [5, 44], [5, 48], [5, 48], [5, 56], [5, 47], [5, 38], [5, 45], [5, 48]], [[10, 43], [10, 52], [10, 55], [10, 52], [10, 57], [10, 49], [10, 49], [10, 56], [10, 51], [10, 58], [10, 89], [10, 249], [10, 49], [10, 44], [10, 44], [10, 47], [10, 52], [10, 48], [10, 54], [10, 48], [10, 49], [10, 52], [10, 49], [10, 40], [10, 60], [10, 45], [10, 59], [10, 44], [10, 43], [10, 48], [10, 50], [10, 49], [10, 43], [10, 59], [10, 50], [10, 42], [10, 49], [10, 69], [10, 55], [10, 48], [10, 48], [10, 49], [10, 43], [10, 49], [10, 47], [10, 57], [10, 49], [10, 43], [10, 44], [10, 45]], [[7, 47], [7, 48], [7, 41], [7, 41], [7, 45], [7, 47], [7, 41], [7, 47], [7, 42], [7, 47], [7, 42], [7, 41], [7, 41], [7, 44], [7, 43], [7, 47], [7, 41], [7, 48], [7, 48], [7, 42], [7, 48], [7, 47], [7, 40], [7, 44], [7, 48], [7, 47], [7, 46], [7, 47], [7, 42], [7, 41], [7, 47], [7, 50], [7, 54], [7, 42], [7, 49], [7, 52], [7, 41], [7, 42], [7, 47], [7, 47], [7, 43], [7, 48], [7, 49], [7, 42], [7, 47], [7, 41], [7, 40], [7, 38], [7, 41], [7, 48]], [[2, 60], [2, 46], [2, 59], [2, 44], [2, 43], [2, 47], [2, 47], [2, 43], [2, 42], [2, 47], [2, 41], [2, 58], [2, 43], [2, 53], [2, 36], [2, 37], [2, 38], [2, 42], [2, 47], [2, 37], [2, 40], [2, 47], [2, 49], [2, 44], [2, 41], [2, 37], [2, 41], [2, 41], [2, 42], [2, 42], [2, 35], [2, 53], [2, 37], [2, 38], [2, 43], [2, 41], [2, 38], [2, 38], [2, 44], [2, 44], [2, 43], [2, 45], [2, 36], [2, 43], [2, 36], [2, 48], [2, 43], [2, 36], [2, 43], [2, 44]], [[4, 44], [4, 48], [4, 47], [4, 44], [4, 48], [4, 48], [4, 47], [4, 48], [4, 47], [4, 47], [4, 40], [4, 38], [4, 62], [4, 48], [4, 41], [4, 44], [4, 48], [4, 48], [4, 48], [4, 48], [4, 47], [4, 63], [4, 42], [4, 44], [4, 47], [4, 41], [4, 44], [4, 38], [4, 58], [4, 42], [4, 42], [4, 44], [4, 48], [4, 36], [4, 38], [4, 43], [4, 42], [4, 44], [4, 41], [4, 37], [4, 42], [4, 44], [4, 44], [4, 39], [4, 38], [4, 42], [4, 43], [4, 47], [4, 38], [4, 45]], [[8, 48], [8, 48], [8, 42], [8, 49], [8, 48], [8, 61], [8, 42], [8, 245], [8, 253], [8, 264], [8, 53], [8, 48], [8, 47], [8, 49], [8, 48], [8, 47], [8, 45], [8, 42], [8, 43], [8, 44], [8, 42], [8, 52], [8, 42], [8, 48], [8, 44], [8, 57], [8, 42], [8, 48], [8, 43], [8, 44], [8, 42], [8, 43], [8, 41], [8, 49], [8, 44], [8, 38], [8, 49], [8, 46], [8, 41], [8, 54], [8, 47], [8, 48], [8, 48], [8, 49], [8, 49], [8, 41], [8, 44], [8, 47], [8, 42], [8, 48]], [[6, 49], [6, 41], [6, 48], [6, 38], [6, 45], [6, 45], [6, 48], [6, 48], [6, 47], [6, 41], [6, 42], [6, 47], [6, 46], [6, 48], [6, 42], [6, 45], [6, 50], [6, 46], [6, 52], [6, 45], [6, 48], [6, 49], [6, 43], [6, 47], [6, 48], [6, 44], [6, 49], [6, 48], [6, 43], [6, 47], [6, 42], [6, 46], [6, 37], [6, 54], [6, 42], [6, 79], [6, 43], [6, 45], [6, 41], [6, 44], [6, 46], [6, 41], [6, 48], [6, 45], [6, 44], [6, 49], [6, 42], [6, 62], [6, 48], [6, 47]], [[9, 48], [9, 42], [9, 56], [9, 43], [9, 47], [9, 43], [9, 48], [9, 47], [9, 47], [9, 41], [9, 111], [9, 42], [9, 49], [9, 48], [9, 43], [9, 44], [9, 49], [9, 47], [9, 48], [9, 48], [9, 48], [9, 48], [9, 48], [9, 47], [9, 41], [9, 44], [9, 47], [9, 50], [9, 48], [9, 52], [9, 48], [9, 43], [9, 48], [9, 42], [9, 41], [9, 48], [9, 48], [9, 47], [9, 46], [9, 1033], [9, 48], [9, 48], [9, 49], [9, 48], [9, 44], [9, 48], [9, 41], [9, 41], [9, 42], [9, 39]]]}, 'confirmation': {'U.S. West Coast': [[[2, 185], [2, 187], [2, 187], [2, 185], [2, 189], [2, 183], [2, 185], [2, 187], [2, 184], [2, 186], [2, 188], [2, 182], [2, 185], [2, 189], [2, 189], [2, 185], [2, 184], [2, 186], [2, 187], [2, 187], [2, 186], [2, 187], [2, 185], [2, 186], [2, 188], [2, 184], [2, 186], [2, 188], [2, 186], [2, 186], [2, 187], [2, 187], [2, 190], [2, 183], [2, 187], [2, 188], [2, 188], [2, 189], [2, 184], [2, 182], [2, 187], [2, 186], [2, 187], [2, 184], [2, 182], [2, 188], [2, 183], [2, 187], [2, 186], [2, 186]], [[8, 187], [8, 188], [8, 188], [8, 187], [8, 186], [8, 187], [8, 188], [8, 187], [8, 187], [8, 188], [8, 188], [8, 188], [8, 187], [8, 188], [8, 188], [8, 188], [8, 187], [8, 187], [8, 188], [8, 186], [8, 187], [8, 186], [8, 186], [8, 188], [8, 187], [8, 187], [8, 190], [8, 186], [8, 188], [8, 188], [8, 187], [8, 186], [8, 188], [8, 188], [8, 188], [8, 190], [8, 190], [8, 189], [8, 187], [8, 187], [8, 187], [8, 187], [8, 186], [8, 188], [8, 187], [8, 187], [8, 188], [8, 186], [8, 188], [8, 186]], [[7, 189], [7, 187], [7, 186], [7, 188], [7, 187], [7, 185], [7, 188], [7, 188], [7, 191], [7, 188], [7, 189], [7, 189], [7, 189], [7, 191], [7, 188], [7, 186], [7, 185], [7, 188], [7, 188], [7, 188], [7, 188], [7, 189], [7, 188], [7, 190], [7, 187], [7, 189], [7, 189], [7, 191], [7, 188], [7, 189], [7, 189], [7, 185], [7, 187], [7, 191], [7, 190], [7, 191], [7, 187], [7, 186], [7, 187], [7, 191], [7, 190], [7, 189], [7, 187], [7, 188], [7, 187], [7, 188], [7, 187], [7, 189], [7, 191], [7, 188]], [[1, 188], [1, 188], [1, 186], [1, 185], [1, 186], [1, 187], [1, 185], [1, 188], [1, 184], [1, 182], [1, 182], [1, 186], [1, 185], [1, 182], [1, 184], [1, 185], [1, 182], [1, 185], [1, 186], [1, 187], [1, 187], [1, 183], [1, 182], [1, 184], [1, 184], [1, 181], [1, 186], [1, 183], [1, 186], [1, 185], [1, 185], [1, 184], [1, 183], [1, 187], [1, 183], [1, 186], [1, 186], [1, 186], [1, 183], [1, 180], [1, 183], [1, 186], [1, 185], [1, 184], [1, 183], [1, 183], [1, 184], [1, 183], [1, 185], [1, 189]], [[4, 188], [4, 189], [4, 187], [4, 186], [4, 188], [4, 186], [4, 187], [4, 184], [4, 186], [4, 188], [4, 187], [4, 188], [4, 187], [4, 185], [4, 188], [4, 188], [4, 186], [4, 186], [4, 186], [4, 187], [4, 186], [4, 186], [4, 185], [4, 188], [4, 187], [4, 189], [4, 185], [4, 185], [4, 189], [4, 188], [4, 189], [4, 188], [4, 190], [4, 187], [4, 187], [4, 187], [4, 187], [4, 189], [4, 190], [4, 188], [4, 185], [4, 189], [4, 186], [4, 185], [4, 189], [4, 186], [4, 187], [4, 186], [4, 186], [4, 186]], [[6, 187], [6, 186], [6, 186], [6, 190], [6, 187], [6, 187], [6, 187], [6, 186], [6, 184], [6, 186], [6, 186], [6, 186], [6, 192], [6, 189], [6, 187], [6, 187], [6, 190], [6, 186], [6, 187], [6, 188], [6, 187], [6, 189], [6, 188], [6, 192], [6, 186], [6, 189], [6, 187], [6, 184], [6, 189], [6, 185], [6, 186], [6, 189], [6, 188], [6, 190], [6, 189], [6, 186], [6, 188], [6, 190], [6, 187], [6, 190], [6, 185], [6, 188], [6, 189], [6, 188], [6, 187], [6, 190], [6, 187], [6, 186], [6, 187], [6, 187]], [[5, 186], [5, 186], [5, 186], [5, 185], [5, 186], [5, 186], [5, 185], [5, 187], [5, 187], [5, 187], [5, 187], [5, 187], [5, 334], [5, 298], [5, 187], [5, 185], [5, 186], [5, 190], [5, 187], [5, 187], [5, 187], [5, 186], [5, 213], [5, 188], [5, 186], [5, 186], [5, 188], [5, 186], [5, 185], [5, 183], [5, 186], [5, 186], [5, 186], [5, 185], [5, 187], [5, 186], [5, 184], [5, 186], [5, 187], [5, 189], [5, 188], [5, 187], [5, 188], [5, 194], [5, 187], [5, 186], [5, 185], [5, 186], [5, 186], [5, 186]], [[3, 186], [3, 185], [3, 188], [3, 185], [3, 185], [3, 187], [3, 186], [3, 186], [3, 184], [3, 187], [3, 189], [3, 182], [3, 190], [3, 187], [3, 186], [3, 189], [3, 187], [3, 188], [3, 186], [3, 182], [3, 185], [3, 197], [3, 186], [3, 183], [3, 188], [3, 183], [3, 189], [3, 186], [3, 187], [3, 187], [3, 184], [3, 184], [3, 186], [3, 184], [3, 188], [3, 186], [3, 184], [3, 187], [3, 184], [3, 188], [3, 189], [3, 188], [3, 191], [3, 186], [3, 185], [3, 188], [3, 185], [3, 184], [3, 185], [3, 187]], [[10, 188], [10, 187], [10, 191], [10, 190], [10, 188], [10, 187], [10, 188], [10, 187], [10, 188], [10, 188], [10, 188], [10, 187], [10, 187], [10, 185], [10, 186], [10, 188], [10, 187], [10, 202], [10, 188], [10, 187], [10, 187], [10, 189], [10, 188], [10, 186], [10, 186], [10, 187], [10, 187], [10, 186], [10, 188], [10, 186], [10, 186], [10, 190], [10, 188], [10, 188], [10, 187], [10, 188], [10, 187], [10, 191], [10, 188], [10, 187], [10, 188], [10, 186], [10, 187], [10, 188], [10, 186], [10, 188], [10, 189], [10, 188], [10, 187], [10, 188]], [[9, 190], [9, 187], [9, 190], [9, 188], [9, 191], [9, 189], [9, 188], [9, 190], [9, 188], [9, 188], [9, 190], [9, 191], [9, 225], [9, 187], [9, 191], [9, 188], [9, 190], [9, 188], [9, 188], [9, 189], [9, 188], [9, 188], [9, 190], [9, 188], [9, 188], [9, 186], [9, 189], [9, 188], [9, 190], [9, 189], [9, 192], [9, 196], [9, 189], [9, 187], [9, 189], [9, 194], [9, 191], [9, 191], [9, 188], [9, 190], [9, 194], [9, 188], [9, 190], [9, 197], [9, 191], [9, 187], [9, 191], [9, 190], [9, 189], [9, 188]]], 'U.K.': [[[1, 42], [1, 41], [1, 38], [1, 37], [1, 39], [1, 36], [1, 37], [1, 37], [1, 41], [1, 42], [1, 36], [1, 41], [1, 38], [1, 37], [1, 36], [1, 39], [1, 40], [1, 38], [1, 41], [1, 41], [1, 38], [1, 36], [1, 36], [1, 36], [1, 44], [1, 39], [1, 36], [1, 41], [1, 40], [1, 36], [1, 37], [1, 37], [1, 41], [1, 36], [1, 40], [1, 44], [1, 37], [1, 42], [1, 35], [1, 309], [1, 36], [1, 43], [1, 40], [1, 37], [1, 37], [1, 37], [1, 36], [1, 41], [1, 37], [1, 36]], [[3, 42], [3, 42], [3, 40], [3, 42], [3, 41], [3, 41], [3, 40], [3, 38], [3, 37], [3, 40], [3, 42], [3, 42], [3, 41], [3, 39], [3, 37], [3, 38], [3, 57], [3, 41], [3, 41], [3, 36], [3, 37], [3, 41], [3, 41], [3, 38], [3, 41], [3, 41], [3, 40], [3, 48], [3, 40], [3, 62], [3, 41], [3, 45], [3, 41], [3, 38], [3, 41], [3, 39], [3, 40], [3, 41], [3, 37], [3, 37], [3, 41], [3, 40], [3, 36], [3, 42], [3, 42], [3, 41], [3, 41], [3, 41], [3, 38], [3, 42]], [[5, 41], [5, 39], [5, 42], [5, 42], [5, 42], [5, 43], [5, 40], [5, 42], [5, 41], [5, 42], [5, 43], [5, 36], [5, 42], [5, 38], [5, 38], [5, 41], [5, 42], [5, 42], [5, 38], [5, 42], [5, 42], [5, 41], [5, 41], [5, 51], [5, 41], [5, 40], [5, 41], [5, 43], [5, 42], [5, 48], [5, 41], [5, 42], [5, 41], [5, 42], [5, 41], [5, 41], [5, 43], [5, 40], [5, 41], [5, 41], [5, 40], [5, 42], [5, 42], [5, 41], [5, 41], [5, 65], [5, 55], [5, 42], [5, 45], [5, 37]], [[10, 45], [10, 43], [10, 54], [10, 41], [10, 53], [10, 45], [10, 50], [10, 85], [10, 42], [10, 45], [10, 179], [10, 176], [10, 53], [10, 50], [10, 44], [10, 44], [10, 49], [10, 43], [10, 51], [10, 42], [10, 51], [10, 43], [10, 49], [10, 44], [10, 58], [10, 51], [10, 42], [10, 43], [10, 40], [10, 44], [10, 43], [10, 43], [10, 43], [10, 45], [10, 43], [10, 42], [10, 43], [10, 46], [10, 42], [10, 43], [10, 45], [10, 42], [10, 42], [10, 48], [10, 41], [10, 42], [10, 42], [10, 40], [10, 42], [10, 38]], [[7, 41], [7, 40], [7, 43], [7, 37], [7, 37], [7, 41], [7, 41], [7, 41], [7, 38], [7, 38], [7, 42], [7, 43], [7, 41], [7, 41], [7, 40], [7, 41], [7, 42], [7, 42], [7, 41], [7, 41], [7, 41], [7, 41], [7, 42], [7, 41], [7, 46], [7, 41], [7, 38], [7, 47], [7, 43], [7, 41], [7, 40], [7, 41], [7, 46], [7, 54], [7, 43], [7, 48], [7, 42], [7, 49], [7, 42], [7, 41], [7, 41], [7, 40], [7, 42], [7, 42], [7, 40], [7, 42], [7, 42], [7, 43], [7, 42], [7, 42]], [[2, 37], [2, 38], [2, 69], [2, 41], [2, 42], [2, 38], [2, 43], [2, 38], [2, 40], [2, 40], [2, 42], [2, 41], [2, 41], [2, 36], [2, 37], [2, 36], [2, 38], [2, 36], [2, 38], [2, 39], [2, 36], [2, 38], [2, 43], [2, 41], [2, 40], [2, 37], [2, 40], [2, 41], [2, 41], [2, 37], [2, 41], [2, 39], [2, 41], [2, 37], [2, 41], [2, 38], [2, 36], [2, 37], [2, 35], [2, 37], [2, 37], [2, 42], [2, 56], [2, 37], [2, 37], [2, 37], [2, 40], [2, 40], [2, 36], [2, 36]], [[4, 42], [4, 41], [4, 41], [4, 41], [4, 41], [4, 40], [4, 39], [4, 38], [4, 36], [4, 40], [4, 43], [4, 37], [4, 39], [4, 41], [4, 41], [4, 41], [4, 38], [4, 40], [4, 42], [4, 41], [4, 42], [4, 42], [4, 41], [4, 42], [4, 41], [4, 41], [4, 41], [4, 38], [4, 43], [4, 40], [4, 38], [4, 41], [4, 40], [4, 41], [4, 41], [4, 41], [4, 41], [4, 41], [4, 41], [4, 41], [4, 38], [4, 43], [4, 41], [4, 42], [4, 38], [4, 38], [4, 41], [4, 41], [4, 40], [4, 42]], [[8, 43], [8, 41], [8, 41], [8, 41], [8, 41], [8, 41], [8, 40], [8, 42], [8, 40], [8, 42], [8, 40], [8, 42], [8, 52], [8, 42], [8, 42], [8, 43], [8, 43], [8, 42], [8, 42], [8, 41], [8, 42], [8, 41], [8, 41], [8, 43], [8, 45], [8, 40], [8, 42], [8, 42], [8, 42], [8, 50], [8, 42], [8, 38], [8, 42], [8, 42], [8, 42], [8, 44], [8, 42], [8, 43], [8, 41], [8, 41], [8, 42], [8, 43], [8, 42], [8, 48], [8, 43], [8, 42], [8, 41], [8, 39], [8, 41], [8, 42]], [[6, 41], [6, 38], [6, 41], [6, 41], [6, 42], [6, 42], [6, 41], [6, 42], [6, 41], [6, 40], [6, 42], [6, 44], [6, 42], [6, 38], [6, 42], [6, 39], [6, 42], [6, 42], [6, 45], [6, 43], [6, 42], [6, 41], [6, 41], [6, 42], [6, 43], [6, 41], [6, 41], [6, 44], [6, 41], [6, 42], [6, 41], [6, 38], [6, 41], [6, 62], [6, 42], [6, 52], [6, 41], [6, 48], [6, 42], [6, 41], [6, 41], [6, 43], [6, 42], [6, 40], [6, 42], [6, 41], [6, 42], [6, 44], [6, 38], [6, 41]], [[9, 42], [9, 43], [9, 42], [9, 43], [9, 43], [9, 41], [9, 42], [9, 41], [9, 41], [9, 42], [9, 42], [9, 41], [9, 42], [9, 42], [9, 42], [9, 41], [9, 41], [9, 42], [9, 37], [9, 39], [9, 42], [9, 42], [9, 41], [9, 42], [9, 43], [9, 42], [9, 41], [9, 43], [9, 42], [9, 44], [9, 43], [9, 42], [9, 42], [9, 40], [9, 41], [9, 42], [9, 42], [9, 45], [9, 42], [9, 41], [9, 42], [9, 42], [9, 42], [9, 42], [9, 42], [9, 42], [9, 43], [9, 42], [9, 42], [9, 41]]]}} \ No newline at end of file diff --git a/scripts/aggregated_parsed_logs/taskset - x-1000000-z-4-aggregated_tps_log.txt b/scripts/aggregated_parsed_logs/taskset - x-1000000-z-4-aggregated_tps_log.txt new file mode 100644 index 0000000000000..6f21385d301cf --- /dev/null +++ b/scripts/aggregated_parsed_logs/taskset - x-1000000-z-4-aggregated_tps_log.txt @@ -0,0 +1 @@ +{'transfer': {'1000': [[['15', '127423'], ['15', '126933'], ['15', '128519'], ['15', '127949'], ['15', '132314'], ['15', '127893'], ['15', '129393'], ['15', '137074'], ['15', '128612']], [['25', '142513'], ['25', '143938'], ['25', '127046'], ['25', '155675'], ['25', '177535'], ['25', '149271'], ['25', '158009'], ['25', '111432'], ['25', '156171']], [['35', '129401'], ['35', '125398'], ['35', '126200'], ['35', '138067'], ['35', '139436'], ['35', '132639'], ['35', '124085'], ['35', '129210'], ['35', '118965']], [['45', '150313'], ['45', '158061'], ['45', '146933'], ['45', '142106'], ['45', '152819'], ['45', '156512'], ['45', '159856'], ['45', '141211'], ['45', '123912']], [['55', '128686'], ['55', '158401'], ['55', '123695'], ['55', '122041'], ['55', '156836'], ['55', '116087'], ['55', '142497'], ['55', '119595'], ['55', '138459']], [['65', '122532'], ['65', '129685'], ['65', '111145'], ['65', '137007'], ['65', '123731'], ['65', '129419'], ['65', '145706'], ['65', '143845'], ['65', '143715']], [['75', '164910'], ['75', '133064'], ['75', '152578'], ['75', '144672'], ['75', '136163'], ['75', '134216'], ['75', '133471'], ['75', '146688'], ['75', '119938']], [['85', '139926'], ['85', '132158'], ['85', '138100'], ['85', '126758'], ['85', '138522'], ['85', '147410'], ['85', '162246'], ['85', '131059'], ['85', '137641']]], '10000': [[['15', '138539'], ['15', '121060'], ['15', '128768'], ['15', '127977'], ['15', '127111'], ['15', '137004'], ['15', '128990'], ['15', '128744'], ['15', '134540']], [['25', '150570'], ['25', '176328'], ['25', '107033'], ['25', '112196'], ['25', '151711'], ['25', '109510'], ['25', '112296'], ['25', '122548'], ['25', '133176']], [['35', '121817'], ['35', '136745'], ['35', '120141'], ['35', '122683'], ['35', '128646'], ['35', '110764'], ['35', '123953'], ['35', '122003'], ['35', '127542']], [['45', '128039'], ['45', '137629'], ['45', '147820'], ['45', '137631'], ['45', '130488'], ['45', '107312'], ['45', '130076'], ['45', '115227'], ['45', '112987']], [['55', '123821'], ['55', '128777'], ['55', '117779'], ['55', '113535'], ['55', '127912'], ['55', '143927'], ['55', '121849'], ['55', '126014'], ['55', '111486']], [['65', '124508'], ['65', '157310'], ['65', '144813'], ['65', '139351'], ['65', '136224'], ['65', '129859'], ['65', '134087'], ['65', '135171'], ['65', '140361']], [['75', '128862'], ['75', '163254'], ['75', '176027'], ['75', '129240'], ['75', '150944'], ['75', '116648'], ['75', '134787'], ['75', '135217'], ['75', '151680']], [['85', '157662'], ['85', '128334'], ['85', '161501'], ['85', '161466'], ['85', '152025'], ['85', '159578'], ['85', '144267'], ['85', '146242'], ['85', '144967']]]}, 'confirmation': {'1000': [[['15', '73830'], ['15', '73808'], ['15', '73857'], ['15', '73627'], ['15', '73762'], ['15', '73963'], ['15', '73846'], ['15', '74021'], ['15', '74023']], [['25', '117960'], ['25', '113501'], ['25', '115622'], ['25', '113370'], ['25', '116521'], ['25', '111450'], ['25', '116344'], ['25', '103493'], ['25', '117179']], [['35', '143224'], ['35', '140969'], ['35', '140984'], ['35', '143484'], ['35', '144153'], ['35', '137735'], ['35', '142986'], ['35', '144295'], ['35', '140487']], [['45', '136786'], ['45', '145852'], ['45', '151392'], ['45', '137701'], ['45', '156859'], ['45', '149545'], ['45', '158138'], ['45', '153143'], ['45', '152070']], [['55', '120588'], ['55', '129038'], ['55', '124219'], ['55', '121050'], ['55', '111993'], ['55', '108924'], ['55', '109489'], ['55', '121720'], ['55', '121501']], [['65', '127841'], ['65', '135716'], ['65', '111723'], ['65', '147203'], ['65', '134939'], ['65', '121505'], ['65', '145737'], ['65', '145299'], ['65', '142128']], [['75', '174107'], ['75', '163044'], ['75', '157785'], ['75', '153926'], ['75', '164851'], ['75', '170178'], ['75', '147918'], ['75', '167784'], ['75', '138998']], [['85', '158050'], ['85', '143106'], ['85', '156837'], ['85', '142918'], ['85', '145706'], ['85', '166954'], ['85', '160856'], ['85', '146790'], ['85', '158525']]], '10000': [[['15', '73326'], ['15', '71427'], ['15', '73815'], ['15', '71276'], ['15', '73987'], ['15', '73860'], ['15', '73929'], ['15', '73643'], ['15', '73898']], [['25', '115387'], ['25', '116678'], ['25', '114414'], ['25', '102619'], ['25', '116831'], ['25', '115614'], ['25', '116976'], ['25', '110696'], ['25', '116895']], [['35', '137431'], ['35', '141741'], ['35', '143182'], ['35', '144327'], ['35', '142452'], ['35', '141453'], ['35', '143097'], ['35', '137406'], ['35', '145087']], [['45', '151439'], ['45', '110170'], ['45', '141833'], ['45', '145501'], ['45', '146927'], ['45', '141655'], ['45', '144802'], ['45', '133336'], ['45', '147866']], [['55', '104233'], ['55', '116230'], ['55', '117475'], ['55', '111898'], ['55', '113710'], ['55', '113249'], ['55', '113205'], ['55', '89852'], ['55', '116198']], [['65', '136292'], ['65', '110167'], ['65', '104390'], ['65', '103539'], ['65', '109206'], ['65', '101049'], ['65', '103535'], ['65', '103627'], ['65', '103003']], [['75', '132953'], ['75', '119497'], ['75', '121864'], ['75', '139958'], ['75', '156968'], ['75', '122833'], ['75', '125466'], ['75', '144843'], ['75', '136211']], [['85', '118734'], ['85', '134698'], ['85', '116040'], ['85', '116037'], ['85', '119722'], ['85', '115392'], ['85', '140303'], ['85', '131319'], ['85', '122622']]]}} \ No newline at end of file diff --git a/scripts/aggregated_parsed_logs/x-1000000-z-4-aggregated_tps_log.txt b/scripts/aggregated_parsed_logs/x-1000000-z-4-aggregated_tps_log.txt new file mode 100644 index 0000000000000..bf178a51fe715 --- /dev/null +++ b/scripts/aggregated_parsed_logs/x-1000000-z-4-aggregated_tps_log.txt @@ -0,0 +1 @@ +{'transfer': {'50000': [[['15', '123333'], ['15', '132304'], ['15', '129400'], ['15', '127966'], ['15', '121601'], ['15', '133350'], ['15', '133128'], ['15', '131574'], ['15', '121790']], [['25', '110366'], ['25', '110082'], ['25', '116045'], ['25', '105166'], ['25', '107527'], ['25', '116227'], ['25', '100449'], ['25', '112600'], ['25', '107547']], [['35', '120267'], ['35', '125787'], ['35', '112727'], ['35', '127653'], ['35', '112239'], ['35', '121013'], ['35', '126953'], ['35', '128408'], ['35', '117296']], [['45', '129083'], ['45', '127813'], ['45', '138873'], ['45', '162410'], ['45', '134924'], ['45', '136207'], ['45', '139255'], ['45', '123004'], ['45', '120144']], [['55', '127155'], ['55', '144538'], ['55', '123319'], ['55', '172735'], ['55', '142087'], ['55', '151489'], ['55', '134689'], ['55', '143430'], ['55', '130568']], [['65', '131587'], ['65', '142826'], ['65', '135972'], ['65', '129461'], ['65', '152891'], ['65', '146284'], ['65', '132158'], ['65', '126141'], ['65', '125063']], [['75', '138552'], ['75', '140899'], ['75', '152614'], ['75', '142402'], ['75', '130760'], ['75', '152958'], ['75', '142515'], ['75', '113319'], ['75', '157615']], [['85', '158510'], ['85', '123749'], ['85', '145682'], ['85', '143107'], ['85', '122725'], ['85', '136627'], ['85', '133818'], ['85', '138262'], ['85', '140533']]], '10000': [[['15', '127503'], ['15', '134808'], ['15', '130388'], ['15', '129535'], ['15', '134231'], ['15', '132055'], ['15', '134904'], ['15', '128708'], ['15', '134679']], [['25', '97369'], ['25', '106300'], ['25', '106195'], ['25', '110963'], ['25', '110538'], ['25', '129421'], ['25', '130200'], ['25', '102830'], ['25', '114941']], [['35', '121743'], ['35', '123189'], ['35', '112333'], ['35', '115334'], ['35', '126645'], ['35', '118642'], ['35', '115695'], ['35', '120490'], ['35', '114995']], [['45', '123894'], ['45', '138933'], ['45', '130115'], ['45', '139220'], ['45', '139767'], ['45', '124346'], ['45', '126429'], ['45', '137044'], ['45', '135012']], [['55', '159130'], ['55', '126430'], ['55', '135373'], ['55', '148603'], ['55', '140693'], ['55', '148975'], ['55', '140123'], ['55', '141898'], ['55', '138285']], [['65', '135258'], ['65', '132731'], ['65', '129135'], ['65', '158397'], ['65', '136552'], ['65', '139911'], ['65', '161454'], ['65', '153559'], ['65', '131342']], [['75', '162172'], ['75', '158899'], ['75', '163344'], ['75', '138709'], ['75', '143061'], ['75', '133465'], ['75', '152380'], ['75', '135991'], ['75', '136670']], [['85', '140777'], ['85', '150607'], ['85', '145533'], ['85', '163681'], ['85', '142758'], ['85', '138976'], ['85', '144370'], ['85', '136038'], ['85', '156747']]], '1000': [[['15', '121477'], ['15', '123977'], ['15', '134670'], ['15', '127737'], ['15', '126398'], ['15', '135459'], ['15', '123564'], ['15', '126949'], ['15', '124793']], [['25', '116660'], ['25', '157036'], ['25', '104770'], ['25', '129634'], ['25', '115823'], ['25', '119379'], ['25', '117025'], ['25', '109636'], ['25', '131246']], [['35', '132726'], ['35', '134421'], ['35', '138943'], ['35', '128829'], ['35', '134813'], ['35', '141558'], ['35', '153123'], ['35', '147940'], ['35', '140606']], [['45', '134683'], ['45', '141230'], ['45', '138183'], ['45', '132284'], ['45', '139018'], ['45', '159163'], ['45', '163459'], ['45', '146715'], ['45', '129424']], [['55', '132890'], ['55', '146719'], ['55', '138053'], ['55', '158863'], ['55', '144426'], ['55', '142878'], ['55', '136916'], ['55', '143833'], ['55', '134891']], [['65', '150554'], ['65', '136171'], ['65', '159463'], ['65', '141568'], ['65', '141654'], ['65', '141177'], ['65', '167668'], ['65', '169845'], ['65', '141408']], [['75', '137623'], ['75', '136701'], ['75', '141059'], ['75', '146146'], ['75', '136652'], ['75', '148837'], ['75', '142773'], ['75', '144371'], ['75', '149219']], [['85', '144303'], ['85', '145997'], ['85', '146385'], ['85', '136963'], ['85', '158157'], ['85', '166430'], ['85', '169689'], ['85', '146971'], ['85', '146291']]], '100': [[['15', '131905'], ['15', '126765'], ['15', '128286'], ['15', '116261'], ['15', '130104'], ['15', '123524'], ['15', '122686'], ['15', '123748'], ['15', '125009']], [['25', '129949'], ['25', '129859'], ['25', '128182'], ['25', '134607'], ['25', '131847'], ['25', '121167'], ['25', '127010'], ['25', '124348'], ['25', '127899']], [['35', '130253'], ['35', '126675'], ['35', '131758'], ['35', '129400'], ['35', '123030'], ['35', '145996'], ['35', '129411'], ['35', '141744'], ['35', '125009']], [['45', '132718'], ['45', '151245'], ['45', '135207'], ['45', '136683'], ['45', '131132'], ['45', '151701'], ['45', '131630'], ['45', '139073'], ['45', '127818']], [['55', '145921'], ['55', '149061'], ['55', '138012'], ['55', '135186'], ['55', '131518'], ['55', '124650'], ['55', '133526'], ['55', '129974'], ['55', '139338']], [['65', '131009'], ['65', '142217'], ['65', '132854'], ['65', '131006'], ['65', '138264'], ['65', '134593'], ['65', '144321'], ['65', '132425'], ['65', '142543']], [['75', '126141'], ['75', '127122'], ['75', '137207'], ['75', '141496'], ['75', '132381'], ['75', '133330'], ['75', '135915'], ['75', '128347'], ['75', '119932']], [['85', '152853'], ['85', '133575'], ['85', '128797'], ['85', '132262'], ['85', '130105'], ['85', '134666'], ['85', '124478'], ['85', '136764'], ['85', '140557']]]}, 'confirmation': {'50000': [[['15', '68123'], ['15', '67645'], ['15', '67924'], ['15', '68740'], ['15', '66762'], ['15', '67541'], ['15', '68850'], ['15', '67694'], ['15', '66954']], [['25', '98721'], ['25', '100187'], ['25', '100806'], ['25', '99023'], ['25', '99903'], ['25', '100826'], ['25', '100882'], ['25', '98666'], ['25', '100163']], [['35', '116584'], ['35', '112495'], ['35', '117840'], ['35', '116136'], ['35', '114666'], ['35', '118248'], ['35', '114894'], ['35', '112715'], ['35', '109774']], [['45', '134174'], ['45', '136283'], ['45', '137281'], ['45', '128624'], ['45', '130301'], ['45', '137816'], ['45', '131151'], ['45', '135151'], ['45', '134575']], [['55', '153336'], ['55', '134443'], ['55', '148270'], ['55', '129553'], ['55', '146660'], ['55', '140498'], ['55', '145818'], ['55', '149574'], ['55', '146672']], [['65', '153359'], ['65', '155420'], ['65', '145401'], ['65', '150808'], ['65', '132139'], ['65', '152162'], ['65', '146845'], ['65', '139280'], ['65', '148685']], [['75', '157450'], ['75', '138084'], ['75', '151113'], ['75', '158421'], ['75', '157488'], ['75', '142196'], ['75', '138287'], ['75', '149363'], ['75', '149591']], [['85', '159405'], ['85', '155347'], ['85', '152580'], ['85', '130824'], ['85', '151516'], ['85', '160023'], ['85', '129752'], ['85', '135061'], ['85', '157236']]], '10000': [[['15', '66772'], ['15', '68788'], ['15', '68716'], ['15', '68156'], ['15', '68118'], ['15', '67789'], ['15', '68042'], ['15', '68456'], ['15', '68684']], [['25', '101883'], ['25', '100160'], ['25', '98645'], ['25', '101438'], ['25', '102720'], ['25', '102951'], ['25', '95777'], ['25', '97619'], ['25', '99216']], [['35', '114093'], ['35', '115395'], ['35', '116739'], ['35', '113705'], ['35', '115111'], ['35', '115292'], ['35', '109965'], ['35', '113959'], ['35', '118048']], [['45', '131928'], ['45', '133666'], ['45', '134968'], ['45', '131014'], ['45', '136584'], ['45', '133037'], ['45', '136357'], ['45', '129500'], ['45', '133922']], [['55', '147159'], ['55', '149813'], ['55', '145506'], ['55', '149064'], ['55', '142068'], ['55', '147265'], ['55', '152297'], ['55', '151668'], ['55', '151695']], [['65', '152237'], ['65', '147767'], ['65', '148085'], ['65', '142239'], ['65', '145795'], ['65', '154774'], ['65', '149036'], ['65', '143158'], ['65', '153352']], [['75', '149283'], ['75', '151349'], ['75', '156673'], ['75', '155761'], ['75', '154985'], ['75', '151649'], ['75', '145098'], ['75', '135722'], ['75', '151353']], [['85', '155123'], ['85', '144595'], ['85', '158046'], ['85', '156916'], ['85', '149113'], ['85', '150882'], ['85', '151393'], ['85', '144814'], ['85', '150174']]], '1000': [[['15', '68444'], ['15', '68643'], ['15', '67318'], ['15', '68157'], ['15', '68001'], ['15', '68578'], ['15', '68751'], ['15', '67896'], ['15', '68658']], [['25', '101291'], ['25', '101895'], ['25', '100248'], ['25', '98005'], ['25', '100403'], ['25', '98803'], ['25', '100069'], ['25', '100958'], ['25', '100798']], [['35', '116075'], ['35', '112452'], ['35', '114653'], ['35', '119301'], ['35', '116445'], ['35', '110622'], ['35', '113186'], ['35', '116391'], ['35', '116960']], [['45', '134135'], ['45', '136857'], ['45', '134676'], ['45', '134497'], ['45', '136656'], ['45', '133510'], ['45', '137057'], ['45', '136377'], ['45', '138208']], [['55', '148620'], ['55', '149248'], ['55', '151010'], ['55', '147893'], ['55', '142967'], ['55', '149143'], ['55', '149822'], ['55', '150036'], ['55', '150943']], [['65', '150654'], ['65', '152604'], ['65', '152553'], ['65', '152487'], ['65', '152854'], ['65', '152041'], ['65', '155138'], ['65', '148072'], ['65', '150958']], [['75', '155818'], ['75', '150775'], ['75', '155053'], ['75', '151949'], ['75', '153992'], ['75', '152511'], ['75', '155219'], ['75', '155429'], ['75', '150688']], [['85', '153945'], ['85', '154222'], ['85', '155329'], ['85', '152750'], ['85', '154762'], ['85', '152013'], ['85', '155141'], ['85', '157051'], ['85', '153282']]], '100': [[['15', '67453'], ['15', '68135'], ['15', '68661'], ['15', '67709'], ['15', '68714'], ['15', '67758'], ['15', '68107'], ['15', '68075'], ['15', '67989']], [['25', '97583'], ['25', '98756'], ['25', '91339'], ['25', '95535'], ['25', '98035'], ['25', '96003'], ['25', '93136'], ['25', '97907'], ['25', '101157']], [['35', '109294'], ['35', '109617'], ['35', '110137'], ['35', '108736'], ['35', '107314'], ['35', '107901'], ['35', '111126'], ['35', '105061'], ['35', '111408']], [['45', '133410'], ['45', '134464'], ['45', '132468'], ['45', '133282'], ['45', '132803'], ['45', '135121'], ['45', '133333'], ['45', '131280'], ['45', '133094']], [['55', '121234'], ['55', '119818'], ['55', '121617'], ['55', '121584'], ['55', '121090'], ['55', '120829'], ['55', '120708'], ['55', '118321'], ['55', '119331']], [['65', '124395'], ['65', '123676'], ['65', '124026'], ['65', '124459'], ['65', '121799'], ['65', '124480'], ['65', '125387'], ['65', '123063'], ['65', '123293']], [['75', '120877'], ['75', '122738'], ['75', '122213'], ['75', '123037'], ['75', '123405'], ['75', '122292'], ['75', '125632'], ['75', '121083'], ['75', '120060']], [['85', '121533'], ['85', '123372'], ['85', '121624'], ['85', '122149'], ['85', '120765'], ['85', '123412'], ['85', '120865'], ['85', '120903'], ['85', '120096']]]}} \ No newline at end of file diff --git a/scripts/aggregated_parsed_logs/x-z-1000-4-aggregated_tps_log.txt b/scripts/aggregated_parsed_logs/x-z-1000-4-aggregated_tps_log.txt new file mode 100644 index 0000000000000..666607b4091de --- /dev/null +++ b/scripts/aggregated_parsed_logs/x-z-1000-4-aggregated_tps_log.txt @@ -0,0 +1 @@ +{'transfer': {1000000: [[['15', '127564'], ['15', '133390'], ['15', '129612'], ['15', '125705'], ['15', '128878'], ['15', '126557'], ['15', '126707'], ['15', '127581'], ['15', '133663']], [['25', '138900'], ['25', '130484'], ['25', '143774'], ['25', '112727'], ['25', '122105'], ['25', '116113'], ['25', '161339'], ['25', '136629'], ['25', '129255']], [['35', '137333'], ['35', '138620'], ['35', '126129'], ['35', '135285'], ['35', '152027'], ['35', '131099'], ['35', '125037'], ['35', '125722'], ['35', '123889']], [['45', '134006'], ['45', '135498'], ['45', '141323'], ['45', '144158'], ['45', '136900'], ['45', '138899'], ['45', '136481'], ['45', '138069'], ['45', '126139']], [['55', '133284'], ['55', '147915'], ['55', '154687'], ['55', '143752'], ['55', '134700'], ['55', '149766'], ['55', '142718'], ['55', '134566'], ['55', '148506']], [['65', '152291'], ['65', '138789'], ['65', '137525'], ['65', '143375'], ['65', '147114'], ['65', '146277'], ['65', '152829'], ['65', '146975'], ['65', '140090']], [['75', '142996'], ['75', '136615'], ['75', '135048'], ['75', '146946'], ['75', '139120'], ['75', '154609'], ['75', '142212'], ['75', '152000'], ['75', '154377']], [['85', '146370'], ['85', '143941'], ['85', '151651'], ['85', '156456'], ['85', '143532'], ['85', '148112'], ['85', '139851'], ['85', '150461'], ['85', '144173']]], 500000: [[['15', '127114'], ['15', '131226'], ['15', '129511'], ['15', '133992'], ['15', '125461'], ['15', '132565'], ['15', '132413'], ['15', '129323'], ['15', '132222']], [['25', '108927'], ['25', '113564'], ['25', '121396'], ['25', '115503'], ['25', '138321'], ['25', '142607'], ['25', '137377'], ['25', '125799'], ['25', '137778']], [['35', '134317'], ['35', '130078'], ['35', '147046'], ['35', '133584'], ['35', '145335'], ['35', '141423'], ['35', '136802'], ['35', '137684'], ['35', '133017']], [['45', '137504'], ['45', '150542'], ['45', '153617'], ['45', '139834'], ['45', '138031'], ['45', '145365'], ['45', '145472'], ['45', '151297'], ['45', '138024']], [['55', '157111'], ['55', '157772'], ['55', '155932'], ['55', '146120'], ['55', '143182'], ['55', '150992'], ['55', '148327'], ['55', '151614'], ['55', '148421']], [['65', '157501'], ['65', '145036'], ['65', '153111'], ['65', '143824'], ['65', '155796'], ['65', '153003'], ['65', '164141'], ['65', '154742'], ['65', '146934']], [['75', '159968'], ['75', '159862'], ['75', '162528'], ['75', '144667'], ['75', '159386'], ['75', '159127'], ['75', '163343'], ['75', '155490'], ['75', '166746']], [['85', '156615'], ['85', '150169'], ['85', '159894'], ['85', '153333'], ['85', '157751'], ['85', '153057'], ['85', '152400'], ['85', '164484'], ['85', '150733']]], 1500000: [[['15', '132594'], ['15', '128948'], ['15', '127768'], ['15', '130929'], ['15', '127347'], ['15', '128391'], ['15', '124883'], ['15', '130879'], ['15', '130823']], [['25', '132827'], ['25', '137264'], ['25', '133161'], ['25', '151563'], ['25', '128468'], ['25', '142422'], ['25', '110216'], ['25', '144647'], ['25', '126826']], [['35', '143396'], ['35', '136622'], ['35', '147418'], ['35', '133867'], ['35', '137982'], ['35', '147421'], ['35', '138289'], ['35', '146803'], ['35', '156002']], [['45', '160120'], ['45', '136322'], ['45', '149174'], ['45', '144464'], ['45', '150314'], ['45', '141807'], ['45', '157157'], ['45', '137538'], ['45', '159560']], [['55', '151911'], ['55', '160179'], ['55', '153099'], ['55', '149105'], ['55', '150638'], ['55', '155385'], ['55', '151037'], ['55', '148410'], ['55', '153539']], [['65', '159798'], ['65', '149297'], ['65', '152077'], ['65', '146443'], ['65', '168837'], ['65', '168467'], ['65', '144967'], ['65', '146121'], ['65', '167220']], [['75', '162822'], ['75', '156665'], ['75', '152529'], ['75', '169654'], ['75', '162251'], ['75', '155707'], ['75', '159442'], ['75', '150049'], ['75', '157297']], [['85', '165991'], ['85', '165781'], ['85', '173319'], ['85', '167146'], ['85', '156678'], ['85', '158844'], ['85', '164633'], ['85', '154485'], ['85', '157985']]], 150000: [[['15', '121677'], ['15', '127787'], ['15', '123712'], ['15', '122873'], ['15', '124175'], ['15', '128923'], ['15', '126052'], ['15', '128480'], ['15', '125566']], [['25', '119506'], ['25', '111878'], ['25', '122745'], ['25', '123755'], ['25', '112018'], ['25', '122681'], ['25', '108309'], ['25', '120425'], ['25', '111486']], [['35', '126625'], ['35', '131283'], ['35', '136465'], ['35', '130766'], ['35', '133938'], ['35', '143759'], ['35', '127869'], ['35', '138996'], ['35', '135710']], [['45', '145630'], ['45', '139146'], ['45', '140812'], ['45', '144192'], ['45', '143901'], ['45', '138433'], ['45', '148407'], ['45', '151122'], ['45', '155903']], [['55', '152513'], ['55', '152692'], ['55', '152436'], ['55', '148363'], ['55', '148642'], ['55', '147786'], ['55', '159206'], ['55', '151437'], ['55', '153223']], [['65', '153452'], ['65', '148107'], ['65', '161033'], ['65', '156433'], ['65', '156058'], ['65', '154914'], ['65', '155601'], ['65', '158861'], ['65', '160420']], [['75', '151524'], ['75', '152970'], ['75', '162289'], ['75', '152574'], ['75', '151485'], ['75', '145356'], ['75', '140615'], ['75', '157694'], ['75', '157391']], [['85', '151057'], ['85', '162366'], ['85', '156853'], ['85', '163983'], ['85', '161782'], ['85', '155929'], ['85', '151381'], ['85', '153981'], ['85', '154374']]]}, 'confirmation': {1000000: [[['15', '67725'], ['15', '67944'], ['15', '67386'], ['15', '68644'], ['15', '68699'], ['15', '68893'], ['15', '67915'], ['15', '68415'], ['15', '67487']], [['25', '96977'], ['25', '98512'], ['25', '97040'], ['25', '100587'], ['25', '98519'], ['25', '99742'], ['25', '97717'], ['25', '100990'], ['25', '100605']], [['35', '113544'], ['35', '116146'], ['35', '113508'], ['35', '118175'], ['35', '113558'], ['35', '113715'], ['35', '116527'], ['35', '116783'], ['35', '120519']], [['45', '136907'], ['45', '135576'], ['45', '132730'], ['45', '132209'], ['45', '135624'], ['45', '138083'], ['45', '134988'], ['45', '135338'], ['45', '134816']], [['55', '147927'], ['55', '151381'], ['55', '148400'], ['55', '148268'], ['55', '148559'], ['55', '151093'], ['55', '144703'], ['55', '151647'], ['55', '150106']], [['65', '152613'], ['65', '150489'], ['65', '154066'], ['65', '152480'], ['65', '152538'], ['65', '153866'], ['65', '154559'], ['65', '154074'], ['65', '150873']], [['75', '155694'], ['75', '152857'], ['75', '149494'], ['75', '153213'], ['75', '155045'], ['75', '155115'], ['75', '151487'], ['75', '152642'], ['75', '156114']], [['85', '152696'], ['85', '154297'], ['85', '156167'], ['85', '151559'], ['85', '156276'], ['85', '153985'], ['85', '154601'], ['85', '155012'], ['85', '151431']]], 500000: [[['15', '65187'], ['15', '67839'], ['15', '67533'], ['15', '65789'], ['15', '64552'], ['15', '69282'], ['15', '67885'], ['15', '67848'], ['15', '68029']], [['25', '96525'], ['25', '96859'], ['25', '98280'], ['25', '99582'], ['25', '100257'], ['25', '90240'], ['25', '98306'], ['25', '98516'], ['25', '97703']], [['35', '113399'], ['35', '113812'], ['35', '110532'], ['35', '106704'], ['35', '108719'], ['35', '111576'], ['35', '114488'], ['35', '110384'], ['35', '109259']], [['45', '131952'], ['45', '131310'], ['45', '130087'], ['45', '127606'], ['45', '133975'], ['45', '134666'], ['45', '135657'], ['45', '132314'], ['45', '132610']], [['55', '148078'], ['55', '149428'], ['55', '146657'], ['55', '146179'], ['55', '149858'], ['55', '148424'], ['55', '147556'], ['55', '149662'], ['55', '147665']], [['65', '155232'], ['65', '149669'], ['65', '149995'], ['65', '152441'], ['65', '150662'], ['65', '154372'], ['65', '150165'], ['65', '152271'], ['65', '152095']], [['75', '153742'], ['75', '149439'], ['75', '155913'], ['75', '150972'], ['75', '153619'], ['75', '152127'], ['75', '152293'], ['75', '150398'], ['75', '151757']], [['85', '150676'], ['85', '147224'], ['85', '152502'], ['85', '153432'], ['85', '152857'], ['85', '150665'], ['85', '151178'], ['85', '150435'], ['85', '153645']]], 1500000: [[['15', '68402'], ['15', '67811'], ['15', '68715'], ['15', '68297'], ['15', '67594'], ['15', '66770'], ['15', '68691'], ['15', '67768'], ['15', '67971']], [['25', '97820'], ['25', '102028'], ['25', '102176'], ['25', '102471'], ['25', '100898'], ['25', '96694'], ['25', '101582'], ['25', '96021'], ['25', '100675']], [['35', '118268'], ['35', '114902'], ['35', '117840'], ['35', '117434'], ['35', '116080'], ['35', '116257'], ['35', '118214'], ['35', '113276'], ['35', '113946']], [['45', '136847'], ['45', '137861'], ['45', '136647'], ['45', '135777'], ['45', '137216'], ['45', '136614'], ['45', '134479'], ['45', '134190'], ['45', '135202']], [['55', '151889'], ['55', '150591'], ['55', '151928'], ['55', '145187'], ['55', '148811'], ['55', '150258'], ['55', '149425'], ['55', '149527'], ['55', '150112']], [['65', '154044'], ['65', '152647'], ['65', '154689'], ['65', '152674'], ['65', '150106'], ['65', '153911'], ['65', '152587'], ['65', '153654'], ['65', '155207']], [['75', '142378'], ['75', '154214'], ['75', '151572'], ['75', '154225'], ['75', '152319'], ['75', '156747'], ['75', '158427'], ['75', '152330'], ['75', '150472']], [['85', '156354'], ['85', '155830'], ['85', '155968'], ['85', '157160'], ['85', '157951'], ['85', '152733'], ['85', '152712'], ['85', '155308'], ['85', '155453']]], 150000: [[['15', '65078'], ['15', '67409'], ['15', '66030'], ['15', '65910'], ['15', '66341'], ['15', '65404'], ['15', '66281'], ['15', '63212'], ['15', '68546']], [['25', '85620'], ['25', '84086'], ['25', '90202'], ['25', '88147'], ['25', '92816'], ['25', '94076'], ['25', '88522'], ['25', '88847'], ['25', '88265']], [['35', '102598'], ['35', '101643'], ['35', '107985'], ['35', '101966'], ['35', '97683'], ['35', '104956'], ['35', '100931'], ['35', '101993'], ['35', '99201']], [['45', '124637'], ['45', '122857'], ['45', '129695'], ['45', '123052'], ['45', '123303'], ['45', '125790'], ['45', '123762'], ['45', '117655'], ['45', '124146']], [['55', '138152'], ['55', '144476'], ['55', '142538'], ['55', '134314'], ['55', '138971'], ['55', '136788'], ['55', '141394'], ['55', '139597'], ['55', '143826']], [['65', '141283'], ['65', '150897'], ['65', '140328'], ['65', '141440'], ['65', '143287'], ['65', '136389'], ['65', '143599'], ['65', '130505'], ['65', '141404']], [['75', '142350'], ['75', '141263'], ['75', '150911'], ['75', '137458'], ['75', '139699'], ['75', '139337'], ['75', '138237'], ['75', '139083'], ['75', '150663']], [['85', '143452'], ['85', '136963'], ['85', '143141'], ['85', '140791'], ['85', '146574'], ['85', '150136'], ['85', '132433'], ['85', '142349'], ['85', '146408']]]}} \ No newline at end of file diff --git a/scripts/aggregated_parsed_logs/z-1000000-1000-x-aggregated_tps_log.txt b/scripts/aggregated_parsed_logs/z-1000000-1000-x-aggregated_tps_log.txt new file mode 100644 index 0000000000000..2773d29937be5 --- /dev/null +++ b/scripts/aggregated_parsed_logs/z-1000000-1000-x-aggregated_tps_log.txt @@ -0,0 +1 @@ +{'transfer': {'75': [[['4', '159453'], ['4', '143342'], ['4', '133069'], ['4', '141906'], ['4', '150621'], ['4', '154706'], ['4', '154771'], ['4', '153783'], ['4', '157787']], [['7', '170389'], ['7', '168839'], ['7', '149593'], ['7', '147182'], ['7', '157553'], ['7', '160847'], ['7', '151787'], ['7', '136981'], ['7', '163800']], [['10', '143117'], ['10', '143185'], ['10', '165443'], ['10', '145500'], ['10', '137976'], ['10', '150969'], ['10', '148075'], ['10', '146815'], ['10', '144135']], [['13', '156163'], ['13', '155495'], ['13', '153765'], ['13', '140751'], ['13', '156268'], ['13', '145218'], ['13', '138392'], ['13', '153863'], ['13', '158001']], [['16', '144371'], ['16', '156728'], ['16', '139481'], ['16', '144216'], ['16', '156507'], ['16', '149360'], ['16', '159970'], ['16', '160517'], ['16', '146848']], [['19', '160052'], ['19', '134985'], ['19', '139147'], ['19', '150465'], ['19', '153673'], ['19', '168009'], ['19', '148351'], ['19', '133418'], ['19', '156392']], [['22', '138756'], ['22', '149042'], ['22', '152273'], ['22', '161223'], ['22', '146446'], ['22', '164962'], ['22', '157840'], ['22', '142698'], ['22', '144127']], [['25', '157925'], ['25', '168075'], ['25', '149032'], ['25', '157927'], ['25', '141224'], ['25', '142602'], ['25', '147115'], ['25', '150211'], ['25', '138885']], [['28', '152182'], ['28', '150105'], ['28', '144538'], ['28', '141853'], ['28', '150181'], ['28', '142086'], ['28', '156350'], ['28', '144380'], ['28', '150477']]], '45': [[['4', '130030'], ['4', '141649'], ['4', '140369'], ['4', '141164'], ['4', '142562'], ['4', '144059'], ['4', '145279'], ['4', '139118'], ['4', '137481']], [['7', '155936'], ['7', '146421'], ['7', '137552'], ['7', '132077'], ['7', '152352'], ['7', '125601'], ['7', '132667'], ['7', '134759'], ['7', '133308']], [['10', '129593'], ['10', '132632'], ['10', '128335'], ['10', '139067'], ['10', '133390'], ['10', '126296'], ['10', '143399'], ['10', '136338'], ['10', '131245']], [['13', '148667'], ['13', '131097'], ['13', '125884'], ['13', '131690'], ['13', '130865'], ['13', '132744'], ['13', '139890'], ['13', '137189'], ['13', '148275']], [['16', '142608'], ['16', '130374'], ['16', '125541'], ['16', '131933'], ['16', '137087'], ['16', '131665'], ['16', '146656'], ['16', '136104'], ['16', '139724']], [['19', '145553'], ['19', '151656'], ['19', '143774'], ['19', '125261'], ['19', '154550'], ['19', '135674'], ['19', '156086'], ['19', '146521'], ['19', '153775']], [['22', '140356'], ['22', '135770'], ['22', '130759'], ['22', '134949'], ['22', '139056'], ['22', '139772'], ['22', '138954'], ['22', '137309'], ['22', '135926']], [['25', '147015'], ['25', '145532'], ['25', '149320'], ['25', '149278'], ['25', '135866'], ['25', '135603'], ['25', '141821'], ['25', '131668'], ['25', '137484']], [['28', '144637'], ['28', '133593'], ['28', '139430'], ['28', '147627'], ['28', '155912'], ['28', '150121'], ['28', '147096'], ['28', '140069'], ['28', '134327']]]}, 'confirmation': {'75': [[['4', '155835'], ['4', '148538'], ['4', '156164'], ['4', '152335'], ['4', '157437'], ['4', '156078'], ['4', '152958'], ['4', '153285'], ['4', '154659']], [['7', '125024'], ['7', '128608'], ['7', '127362'], ['7', '128129'], ['7', '128409'], ['7', '127147'], ['7', '128564'], ['7', '128708'], ['7', '125854']], [['10', '111124'], ['10', '107899'], ['10', '108182'], ['10', '109203'], ['10', '111238'], ['10', '110742'], ['10', '111529'], ['10', '108596'], ['10', '110813']], [['13', '95842'], ['13', '95705'], ['13', '96627'], ['13', '97533'], ['13', '91539'], ['13', '95787'], ['13', '94766'], ['13', '96133'], ['13', '97411']], [['16', '83999'], ['16', '84549'], ['16', '83050'], ['16', '86140'], ['16', '85564'], ['16', '84035'], ['16', '84267'], ['16', '84077'], ['16', '84019']], [['19', '74144'], ['19', '75751'], ['19', '76449'], ['19', '75734'], ['19', '76027'], ['19', '73419'], ['19', '75905'], ['19', '75246'], ['19', '76219']], [['22', '69053'], ['22', '68613'], ['22', '67435'], ['22', '68179'], ['22', '68404'], ['22', '66339'], ['22', '69007'], ['22', '68726'], ['22', '68352']], [['25', '57633'], ['25', '56989'], ['25', '58444'], ['25', '62399'], ['25', '61961'], ['25', '62229'], ['25', '60572'], ['25', '61369'], ['25', '62770']], [['28', '57500'], ['28', '57368'], ['28', '58147'], ['28', '57946'], ['28', '56960'], ['28', '58319'], ['28', '56396'], ['28', '57926'], ['28', '56097']]], '45': [[['4', '137422'], ['4', '132904'], ['4', '135381'], ['4', '134366'], ['4', '135658'], ['4', '133741'], ['4', '136425'], ['4', '136152'], ['4', '135894']], [['7', '101288'], ['7', '103729'], ['7', '105691'], ['7', '106289'], ['7', '105726'], ['7', '106862'], ['7', '109141'], ['7', '104831'], ['7', '105110']], [['10', '83599'], ['10', '85531'], ['10', '85439'], ['10', '85946'], ['10', '84059'], ['10', '82255'], ['10', '82658'], ['10', '86147'], ['10', '85304']], [['13', '74620'], ['13', '71622'], ['13', '73720'], ['13', '74904'], ['13', '73269'], ['13', '72885'], ['13', '72810'], ['13', '73082'], ['13', '73742']], [['16', '64573'], ['16', '63265'], ['16', '62117'], ['16', '63208'], ['16', '59063'], ['16', '63628'], ['16', '63908'], ['16', '62843'], ['16', '62484']], [['19', '57044'], ['19', '57186'], ['19', '56895'], ['19', '57068'], ['19', '56574'], ['19', '56347'], ['19', '53305'], ['19', '58948'], ['19', '60101']], [['22', '53931'], ['22', '52454'], ['22', '53925'], ['22', '52146'], ['22', '51605'], ['22', '50691'], ['22', '52874'], ['22', '51828'], ['22', '52531']], [['25', '45506'], ['25', '44326'], ['25', '44729'], ['25', '46741'], ['25', '48940'], ['25', '49686'], ['25', '47130'], ['25', '49116'], ['25', '49592']], [['28', '43497'], ['28', '46214'], ['28', '45591'], ['28', '47023'], ['28', '43139'], ['28', '40525'], ['28', '46580'], ['28', '42539'], ['28', '45071']]]}} \ No newline at end of file diff --git a/scripts/aggregated_tps_log.txt b/scripts/aggregated_tps_log.txt new file mode 100644 index 0000000000000..b70ac3ea7f562 --- /dev/null +++ b/scripts/aggregated_tps_log.txt @@ -0,0 +1 @@ +{'transfer': {'500000': [[['15', '11250'], ['15', '11132'], ['15', '11203'], ['15', '23430'], ['15', '118673'], ['15', '27404'], ['15', '26355'], ['15', '11160'], ['15', '26220']], [['25', '11215'], ['25', '11201'], ['25', '11283'], ['25', '11278'], ['25', '11296'], ['25', '12425'], ['25', '11194'], ['25', '11383'], ['25', '11167']], [['35', '11009'], ['35', '11075'], ['35', '11069'], ['35', '11054'], ['35', '11112'], ['35', '11025'], ['35', '10868'], ['35', '14123'], ['35', '11377']], [['45', '11139'], ['45', '11210'], ['45', '11096'], ['45', '11199'], ['45', '11224'], ['45', '11050'], ['45', '11337'], ['45', '11092'], ['45', '11359']], [['55', '151459'], ['55', '11115'], ['55', '11097'], ['55', '11088'], ['55', '10851'], ['55', '10880'], ['55', '11154'], ['55', '11165'], ['55', '10715']], [['65', '10781'], ['65', '10856'], ['65', '10823'], ['65', '10604'], ['65', '10929'], ['65', '10738'], ['65', '10851'], ['65', '10838'], ['65', '10630']], [['75', '10825'], ['75', '10688'], ['75', '10630'], ['75', '10659'], ['75', '10545'], ['75', '10548'], ['75', '10947'], ['75', '10474'], ['75', '10466']], [['85', '10130'], ['85', '10182'], ['85', '10356'], ['85', '10396'], ['85', '10475'], ['85', '10314'], ['85', '10416'], ['85', '10329'], ['85', '10378']]], '150000': [[['15', '115290'], ['15', '113964'], ['15', '11268'], ['15', '116156'], ['15', '115773'], ['15', '11188'], ['15', '11120'], ['15', '11181'], ['15', '11263']], [['25', '11264'], ['25', '11097'], ['25', '11113'], ['25', '12217'], ['25', '11050'], ['25', '15755'], ['25', '11035'], ['25', '14147'], ['25', '11090']], [['35', '11214'], ['35', '11566'], ['35', '10538'], ['35', '12614'], ['35', '11159'], ['35', '11401'], ['35', '10937'], ['35', '11338'], ['35', '11113']], [['45', '10889'], ['45', '11097'], ['45', '10928'], ['45', '10647'], ['45', '10936'], ['45', '11223'], ['45', '10975'], ['45', '10908'], ['45', '10811']], [['55', '11330'], ['55', '11088'], ['55', '134871'], ['55', '10831'], ['55', '10987'], ['55', '10393'], ['55', '46466'], ['55', '11182'], ['55', '10966']], [['65', '10448'], ['65', '12376'], ['65', '11432'], ['65', '11330'], ['65', '10839'], ['65', '148956'], ['65', '10897'], ['65', '10697'], ['65', '10834']], [['75', '10630'], ['75', '11053'], ['75', '10662'], ['75', '10630'], ['75', '10721'], ['75', '10701'], ['75', '10658'], ['75', '10581'], ['75', '10820']], [['85', '10126'], ['85', '10181'], ['85', '10236'], ['85', '10187'], ['85', '9906'], ['85', '9949'], ['85', '10110'], ['85', '10447'], ['85', '10322']]]}, 'confirmation': {'500000': [[['15', '12455'], ['15', '24064'], ['15', '13159'], ['15', '12094'], ['15', '12531'], ['15', '14367'], ['15', '12546'], ['15', '12824'], ['15', '12329']], [['25', '13483'], ['25', '14290'], ['25', '13928'], ['25', '13795'], ['25', '13024'], ['25', '13872'], ['25', '13488'], ['25', '14420'], ['25', '14084']], [['35', '11073'], ['35', '15216'], ['35', '14494'], ['35', '104306'], ['35', '11070'], ['35', '10992'], ['35', '11029'], ['35', '104886'], ['35', '11048']], [['45', '11787'], ['45', '11059'], ['45', '10986'], ['45', '11120'], ['45', '11023'], ['45', '12314'], ['45', '11123'], ['45', '11654'], ['45', '10983']], [['55', '11115'], ['55', '11080'], ['55', '10984'], ['55', '10994'], ['55', '11189'], ['55', '10975'], ['55', '11060'], ['55', '10995'], ['55', '11501']], [['65', '11131'], ['65', '10929'], ['65', '10708'], ['65', '11000'], ['65', '11004'], ['65', '10837'], ['65', '10904'], ['65', '10731'], ['65', '10863']], [['75', '10709'], ['75', '10801'], ['75', '10830'], ['75', '10725'], ['75', '10991'], ['75', '11021'], ['75', '11054'], ['75', '10787'], ['75', '10743']], [['85', '10295'], ['85', '10488'], ['85', '10417'], ['85', '10553'], ['85', '10691'], ['85', '10469'], ['85', '10426'], ['85', '10456'], ['85', '10453']]], '150000': [[['15', '18417'], ['15', '16283'], ['15', '17723'], ['15', '26176'], ['15', '31521'], ['15', '13116'], ['15', '28117'], ['15', '16072'], ['15', '15410']], [['25', '19949'], ['25', '24984'], ['25', '68363'], ['25', '38759'], ['25', '11181'], ['25', '22061'], ['25', '30270'], ['25', '18850'], ['25', '22923']], [['35', '101458'], ['35', '98073'], ['35', '98390'], ['35', '99715'], ['35', '17922'], ['35', '101494'], ['35', '89514'], ['35', '23398'], ['35', '101174']], [['45', '10748'], ['45', '10740'], ['45', '10811'], ['45', '11180'], ['45', '10934'], ['45', '10878'], ['45', '11135'], ['45', '10965'], ['45', '12609']], [['55', '11247'], ['55', '10552'], ['55', '10961'], ['55', '11005'], ['55', '10879'], ['55', '11175'], ['55', '10873'], ['55', '10935'], ['55', '11009']], [['65', '10935'], ['65', '10660'], ['65', '10849'], ['65', '11143'], ['65', '11012'], ['65', '10873'], ['65', '10742'], ['65', '10622'], ['65', '10582']], [['75', '10486'], ['75', '11185'], ['75', '10920'], ['75', '11015'], ['75', '10533'], ['75', '11356'], ['75', '10643'], ['75', '10334'], ['75', '10973']], [['85', '10230'], ['85', '10381'], ['85', '10104'], ['85', '10033'], ['85', '10212'], ['85', '10315'], ['85', '10401'], ['85', '10242'], ['85', '10419']]]}} \ No newline at end of file diff --git a/scripts/aws_plot.py b/scripts/aws_plot.py new file mode 100644 index 0000000000000..6f139d3050970 --- /dev/null +++ b/scripts/aws_plot.py @@ -0,0 +1,89 @@ +# Copyright (c) Facebook Inc. +# SPDX-License-Identifier: Apache-2.0 + +""" +Make plots on AWS as installing Matplotlib on macOS is a pain. +Then downloads parsed logs. +""" + +from fabric.api import run, roles, execute, task, put, env, local, sudo, settings, get +from fabric.contrib import files +import boto3 +from botocore.exceptions import ClientError +import os + +ec2 = boto3.client('ec2') + +region = os.environ.get("AWS_EC2_REGION") +env.user = 'ubuntu' +env.key_filename = '~/.ssh/aws-fb.pem' # SET PATH TO KEY FILE HERE + +""" +Initialise hosts, this command is run in conjunction with other commands. +COMMANDS: fab -f aws_plot.py set_hosts +""" + +instances_id = [] # automatically filled by 'set_hosts' +env.roledefs = {'dev': [], } # automatically filled by 'set_hosts' + +def set_hosts(value ='running', instance_type='dev', region=region): + ec2resource = boto3.resource('ec2') + instances = ec2resource.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': [value]}]) + for instance in instances: + for tag in instance.tags or []: + if 'Name'in tag['Key']: + name = tag['Value'] + if instance_type in name: + instances_id.append(instance.id) + env.roledefs['dev'].append(instance.public_ip_address) + +""" +Print commands to ssh into hosts (debug). +COMMANDS: fab -f aws_plot.py info +""" + +def info(): + set_hosts() + + print('\ndev:') + for dev in env.roledefs['dev']: + print('\t ssh -i '+env.key_filename+' '+env.user+'@'+dev) + +""" +Parse logs and create plots; then donwloads plots and parsed logs. +COMMANDS: fab -f aws_plot.py set_hosts clean + fab -f aws_plot.py set_hosts throughput + fab -f aws_plot.py set_hosts latency +""" + +tps_script = 'throughput.py' +tps_raw_logs = 'raw_logs/*' +latency_script = 'latency.py' +latency_raw_logs = 'latency_raw_logs/*' +subdir = 'fastpay/' + +@roles('dev') +def clean(): + run('rm -r '+subdir+'* || true') + #put(tps_raw_logs, subdir+'.') + #put(latency_raw_logs, subdir+'.') + +@roles('dev') +def throughput(): + put(tps_script, subdir+'.') + #put('aggregated_parsed_logs/*tps*', subdir+'.') + run('(cd '+subdir+' && python3 throughput.py)') + if files.exists(subdir+'*aggregated*'): + get(subdir+'*aggregated*', '.') + get(subdir+'*.pdf', '.') + local('open *.pdf') + +@roles('dev') +def latency(): + put(latency_script, subdir+'.') + #put(latency_raw_logs, subdir+'.') + run('(cd '+subdir+' && python3 %s plot)' % latency_script) + if files.exists(subdir+'*aggregated*'): + get(subdir+'*aggregated*', '.') + get(subdir+'*.pdf', '.') + local('open latency*.pdf') diff --git a/scripts/bench.sh b/scripts/bench.sh new file mode 100755 index 0000000000000..4c005c8566d37 --- /dev/null +++ b/scripts/bench.sh @@ -0,0 +1,68 @@ +#!/bin/bash + +num_shards=15 +num_accounts=500000 +max_in_flight=700 +committee_size=4 +protocol=UDP + +if [ "$1" != "" ]; then + num_shards=$1 +fi +if [ "$2" != "" ]; then + num_accounts=$2 +fi +if [ "$3" != "" ]; then + max_in_flight=$3 +fi +if [ "$4" != "" ]; then + committee_size=$4 +fi +if [ "$5" != "" ]; then + protocol=$5 +fi + +# Distinguish local and aws tests. +if [ "$6" != "aws" ]; then + cd ../../target/release/ +fi + +# Clean up. +killall server || true +killall client || true +rm *.json || true + +# Create committee and server configs. +key_files="" +for (( i=1; i<=$committee_size; i++ )) +do + key_files="$key_files server-$i.json" + ./server --server server-"$i".json generate \ + --host 127.0.0.1 \ + --port 9500 \ + --shards $num_shards \ + --protocol $protocol \ + >> committee.json +done + +# Create clients' accounts. +./client --committee committee.json --accounts accounts.json create_accounts $num_accounts >> initial_accounts.json + +# Run a single authority (with multiple shards). +for (( i=0; i<$num_shards; i++ )) +do + ./server --server server-1.json run \ + --initial_accounts initial_accounts.json \ + --initial_balance 100 \ + --committee committee.json \ + --shard $i & +done + +# Run the client benchmark. +sleep 1 # wait for server to be ready before benchmark +read -r line < committee.json +echo "$line" > committee-single.json +./client --committee committee-single.json --accounts accounts.json benchmark \ + --server_configs $key_files \ + --max_in_flight $max_in_flight + diff --git a/scripts/fabfile.py b/scripts/fabfile.py new file mode 100644 index 0000000000000..2967d1f531c8b --- /dev/null +++ b/scripts/fabfile.py @@ -0,0 +1,433 @@ +# Copyright (c) Facebook Inc. +# SPDX-License-Identifier: Apache-2.0 + +""" +AWS AT FB + Follow the instructions at https://fb.quip.com/YrDyAS3GDcw + +INSTALL: + 1. create a virtual env: + python -m virtualenv venv + source venv/bin/activate + + 2. install boto3 and fabric: + pip install boto3 + pip install fabric + + 3. configure aws: + pip install awscli + aws configure # input 'eu-north-1b' as region + +CROSS-COMPILATION FOR UBUNTU: + 1. run the following commands + brew install FiloSottile/musl-cross/musl-cross # warning: takes a long tome + brew link musl-cross + rustup target add x86_64-unknown-linux-musl + + 2. add the following lines to a file called `.cargo/config` in the project dir: + [target.x86_64-unknown-linux-musl] + linker = "x86_64-linux-musl-gcc" + + 3. build the executable + CC_x86_64_unknown_linux_musl="x86_64-linux-musl-gcc" cargo build --release --target=x86_64-unknown-linux-musl + +CREATE AWS INSTANCES: + 1. create a client instance, called `fastpay-client` + 2. create as many authority instances as required, called `fastpay-authorituy-#` (where # is a number) + 3. create a security group called `fastpay` and add all authorities to it + 4. open the following ports on the fastpay security group + TCP 22 + UDP ALL + +GET ACCESS TO EXISINT INSTANCES: + 1. got to the AWS console interface and generate a new .pem key file + 2. extract the public key from the .pem key file: + ssh-keygen -f YOUR_KEY.pem -y > YOUR_KEY.pub + 3. send YOUR_KEY.pub to someone that has access to the machines so that they can add it to each machine: + `./ssh/authorized_keys` + +POSSIBLE ISSUES: + - if boto3 outputs 'Request has expired', run 'source ~/bin/aws-mfa'. More info at https://fb.quip.com/YrDyAS3GDcwZ + - try to relink musl-cross: brew unlink musl-cross && brew link musl-cross + - if permission denied when cross compiling, run 'sudo cargo build --release --target=x86_64-unknown-linux-musl' +""" + +from fabric.api import * +import boto3 +from botocore.exceptions import ClientError +import os +import sys +import time + +ec2 = boto3.client('ec2') + +region = os.environ.get("AWS_EC2_REGION") +env.user = 'ubuntu' +env.key_filename = '~/.ssh/aws-fb.pem' # SET PATH TO KEY FILE HERE +linux_bin_dir = '../../target/x86_64-unknown-linux-musl/release/' +local_bin_dir = '../../target/release/' + +""" +Initialise hosts, this command is run in conjunction with other commands. +COMMANDS: fab set_hosts +""" + +instances_id = [] # automatically filled by 'set_hosts' +env.roledefs = {'client': [], 'authority': [], 'throughput': []} # automatically filled by 'set_hosts' + +def set_hosts(value ='running', instance_type='fastpay', region=region): + ec2resource = boto3.resource('ec2') + instances = ec2resource.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': [value]}]) + for instance in instances: + for tag in instance.tags or []: + if 'Name'in tag['Key']: + name = tag['Value'] + if instance_type in name: + instances_id.append(instance.id) + if name == 'fastpay-client': + env.roledefs['client'].append(instance.public_ip_address) + elif 'fastpay-authority' in name: + env.roledefs['authority'].append(instance.public_ip_address) + elif 'fastpay-throughput' in name: + env.roledefs['throughput'].append(instance.public_ip_address) + +""" +Start and stop instances. +COMMANDS: fab start start all instances + fab start:authority start all server + fab start:client start all clients + fab start:throughput start all throughput benchmark machines + + fab stop stop all instances + fab stop:authority stop all server + fab stop:client stop all clients + fab stop:throughput stop all throughput benchmark machines +""" + +def start(instance_type='fastpay'): + set_hosts(value='stopped', instance_type=instance_type) + try: + ec2.start_instances(InstanceIds=instances_id, DryRun=True) + except ClientError as e: + if 'DryRunOperation' not in str(e): + raise + try: + response = ec2.start_instances(InstanceIds=instances_id, DryRun=False) + print(response) + except ClientError as e: + print(e) + +def stop(instance_type='fastpay'): + set_hosts(value='running', instance_type=instance_type) + try: + ec2.stop_instances(InstanceIds=instances_id, DryRun=True) + except ClientError as e: + if 'DryRunOperation' not in str(e): + raise + try: + response = ec2.stop_instances(InstanceIds=instances_id, DryRun=False) + print(response) + except ClientError as e: + print(e) + +""" +Print commands to ssh into hosts (debug). +COMMANDS: fab info +""" + +def info(): + set_hosts() + + print('\nclients:') + for client in env.roledefs['client']: + print('\t ssh -i '+env.key_filename+' '+env.user+'@'+client) + + print('\nservers:') + for server in env.roledefs['authority']: + print('\t ssh -i '+env.key_filename+' '+env.user+'@'+server) + + print('\nthroughput:') + for server in env.roledefs['throughput']: + print('\t ssh -i '+env.key_filename+' '+env.user+'@'+server) + + +""" +Deploy the testnet. +COMMANDS: fab set_hosts deploy Update binary and reload same committee and initial accounts (but state is lost) + fab set_hosts reset deploy Erase all files and create new committee and initial accounts + +USE THE TESTNET: + 1. locate the file 'committee.json' specifying the set of FastPay authorities + + 2. create a user account (it creates 'accounts.json'): + ./client --committee committee.json --accounts accounts.json create_accounts 1 + + 3. ask someone nice to transfer coins to your address + + 4. read your balance: + ./client --committee committee.json --accounts accounts.json query_balance ' + + 5. transfer coins: + ./client --committee committee.json --accounts accounts.json transfer --from --to +""" + +committee_config = 'committee.json' # contains information about the committee +initial_accounts = 'initial_accounts.json' # hold addresses of the inital accounts +accounts = 'accounts.json' # hold all information about users accounts +base_port = 9500 +num_shards = 15 +num_initial_accounts = 10 # number of accounts to create intially +amount_initial_accounts = 10000 # amount to seed the initial accounts + +def local_run(command): + local('%s%s' % (local_bin_dir, command)) + +def cross_compile(): + local('(cd ../fastpay && \ + CC_x86_64_unknown_linux_musl="x86_64-linux-musl-gcc" \ + cargo build --release --target=x86_64-unknown-linux-musl)') + +@roles('authority') +def clean(): + local('rm -f *.json') + run('rm -r * || true') + +def intitalize(): + # make committee + for host in env.roledefs['authority']: + with settings(host_string=host): + command = './server --server %s.json generate --host %s --port %d --shards %d >> %s' \ + % (host, host, base_port, num_shards, committee_config) + execute(local_run, command) + + # generate initial state + command = './client --committee %s --accounts %s create_accounts %d >> %s' \ + % (committee_config, accounts, num_initial_accounts, initial_accounts) + execute(local_run, command) + + +@roles('authority') +def upload_server_files(): + put(committee_config, '.') + put(initial_accounts, '.') + + for host in env.roledefs['authority']: + with settings(host_string=host): + put(host+'.json', '.') + +@roles('authority') +def run_server(): + run('tmux kill-server || true') + run('rm -r server || true') + put(linux_bin_dir+'server', '.') + run('chmod +x *') + run('for f in *.*.*.*; do mv -i "$f" "server.json" || true; done') # rename key file + + for i in range(num_shards): + run('tmux new -d -s server-%d' % i) + command = 'taskset\ --cpu-list\ %d\ ./server\ --server\ server.json\ run\ --initial_accounts\ %s\ --initial_balance\ %d\ --committee\ %s\ --shard\ %d' \ + % (i, initial_accounts, amount_initial_accounts, committee_config, i) + run('tmux send -t server-%d.0 %s ENTER' % (i, command)) + + ''' + run('tmux new -d -s server') + command = './server\ --server\ server.json\ run\ --initial_accounts\ %s\ --initial_balance\ %d\ --committee\ %s' \ + % (initial_accounts, amount_initial_accounts, committee_config) + run('tmux send -t server.0 %s ENTER' % command) + ''' + +def reset(): + execute(cross_compile) + execute(clean) + execute(intitalize) + execute(upload_server_files) + +def deploy(): + execute(run_server) + +""" +Run client to test latency (once the testnet is deployed) +COMMANDS: fab set_hosts get_balance + fab set_hosts transfer + fab set_hosts mass_transfer + fab set_hosts quick_transfer +""" + +remote_client = False # set to True to run the client on AWS +latency_max_load = 10 +latency_max_in_flight = 1000 + +def initialize_client(remote_client=remote_client): + if remote_client: + execute(cross_compile) + run('killall client || true') + run('rm -r * || true') + put(committee_config, '.') + put(accounts, '.') + put(linux_bin_dir+'client', '.') + run('chmod +x *') + else: + local('(cd ../fastpay && cargo build --release)') + +@roles('client') +def get_balance(remote_client=remote_client): + execute(initialize_client, remote_client) + + f = open(initial_accounts, 'r') + addresses = f.read().splitlines() + f.close() + assert len(addresses) > 0 + for addr in addresses: + command = './client --committee %s --accounts %s query_balance %s' \ + % (committee_config, accounts, addr) + if remote_client: + run(command) + else: + execute(local_run, command) + +@roles('client') +def transfer(remote_client=remote_client): + execute(initialize_client, remote_client) + + f = open(initial_accounts, 'r') + addresses = f.read().splitlines() + f.close() + assert len(addresses) > 0 + + for i, sender in enumerate(addresses): + command = './client --committee %s --accounts %s transfer --from %s --to %s 1' \ + % (committee_config, accounts, sender, sender) + if remote_client: + run(command) + else: + execute(local_run, command) + +@roles('client') +def mass_transfer(remote_client=remote_client): + execute(initialize_client, remote_client) + + command = './client --committee %s --accounts %s benchmark --max_orders %d --max_in_flight %d' \ + % (committee_config, accounts, latency_max_load, latency_max_in_flight) + + if remote_client: + run(command) + else: + execute(local_run, command) + +@roles('client') +def quick_transfer(remote_client=remote_client): + # this function is used to test latency with crashed nodes. + execute(initialize_client, remote_client) + + f = open(initial_accounts, 'r') + addresses = f.read().splitlines() + f.close() + assert len(addresses) > 0 + + #recipient = 'raG+Bvmb9Wp4IdR3D8KmyRwZ8Wadf63A2liTiGkopHY=' + for i, sender in enumerate(addresses): + command = './client --committee %s --accounts %s quick_transfer --from %s --to %s 1' \ + % (committee_config, accounts, sender, sender) + if remote_client: + run(command) + else: + execute(local_run, command) + +""" +Run throughput measurement (run on a dedicated machine). +COMMANDS: fab set_hosts update updates the binaries + fab set_hosts tps run throughput benchmark +""" + +@roles('throughput') +def background_run(command): + command = 'nohup %s &> /dev/null &' % command + run(command, pty=False) + +@roles('throughput') +def update(): + execute(cross_compile) + run('killall client || true') + run('killall server || true') + run('rm -r * || true') + put(linux_bin_dir+'client', '.') + put(linux_bin_dir+'server', '.') + put('bench.sh', '.') + run('chmod +x *') + sudo('sysctl -w net.core.rmem_max=96214400') # increase network buffer + sudo('sysctl -w net.core.rmem_default=96214400') # increase network buffer + +@roles('throughput') +@parallel +def tps(tps_shards=65, tps_accounts=1000000, tps_max_in_flight=1000, tps_committee=4, tps_protocol='UDP', log_file=None): + shards = int(tps_shards) + accounts = int(tps_accounts) + max_in_flight = int(tps_max_in_flight) + committee = int(tps_committee) + protocol = tps_protocol + log = '2>> %s' % log_file if log_file is not None else '' + run('./bench.sh %d %d %d %d %s aws %s' % (shards, accounts, max_in_flight, committee, protocol, log)) + +""" +Run throughput measurements for different parameters (run on a dedicated machine), and dump output to file +COMMANDS: fab set_hosts tps_measurements run tps measurements for different parameters + fab set_hosts download_logs download logs from all benchmark servers +""" + +tps_shards = range(15, 86, 10) # the machine has 48 physical CPUs +tps_accounts = 1000000 +tps_in_flights = 1000 +tps_committee = 4 +tps_protocol = 'UDP' + +base_tps_log_file = 'tps_logs.txt' + +@roles('throughput') +def clean_logs(): + run('rm -r *txt* || true') + +def tps_measurements_11_12(): + # settings + in_flights = [100, 1000, 10000, 50000] + + execute(clean_logs) + for in_flight in in_flights: + print('Running measurements with %d in-flights orders.' % in_flight) + for shards in tps_shards: + print('Running measurements with %d shards.' % shards) + tps_log_file = '%d-%d-%d-%d-%s-%s' % (shards, tps_accounts, in_flight, tps_committee, tps_protocol, base_tps_log_file) + execute(tps, shards, tps_accounts, in_flight, tps_committee, tps_protocol, tps_log_file) + time.sleep(2) + +def tps_measurements_13_14(): + # settings + accounts = [150000, 500000, 1000000, 1500000] + + execute(clean_logs) + for account in accounts: + print('Running measurements with %d transaction load.' % account) + for shards in tps_shards: + print('Running measurements with %d shards.' % shards) + tps_log_file = '%d-%d-%d-%d-%s-%s' % (shards, account, tps_in_flights, tps_committee, tps_protocol, base_tps_log_file) + execute(tps, shards, account, tps_in_flights, tps_committee, tps_protocol, tps_log_file) + time.sleep(2) + +def tps_measurements_15(): + # settings + shards = [75] #shards = [75, 45] + committees = [3*f+1 for f in range(10, 33)] #committees = [3*f+1 for f in range(1, 10)] + + execute(clean_logs) + for shard in shards: + print('Running measurements with %d shards.' % shard) + for committee in committees: + print('Running measurements with %d authorities.' % committee) + tps_log_file = '%d-%d-%d-%d-%s-%s' % (shard, tps_accounts, tps_in_flights, committee, tps_protocol, base_tps_log_file) + execute(tps, shard, tps_accounts, tps_in_flights, committee, tps_protocol, tps_log_file) + time.sleep(2) + +def download_logs(): + for host in env.roledefs['throughput']: + with settings(host_string=host): + run('for f in *.txt; do mv -i "$f" "$f.%s" || true; done' % host) + get('*.txt*', './raw_logs') diff --git a/scripts/latency.py b/scripts/latency.py new file mode 100644 index 0000000000000..6f15cbbd134a9 --- /dev/null +++ b/scripts/latency.py @@ -0,0 +1,122 @@ +# Copyright (c) Facebook Inc. +# SPDX-License-Identifier: Apache-2.0 + +import numpy as np +import matplotlib.pyplot as plt +import re +import sys +import os.path +import os, fnmatch + +MPK = 'U.S. West Coast' +LDN = 'U.K.' + +def parse(row_log_file, parsed_log_file): + location = MPK + if 'ldn' in row_log_file: + location = LDN + + fname = os.path.abspath(row_log_file) + data = open(fname).read() + + latency = ''.join(re.findall(r'Received [0-9]* responses in [0-9]* ms', data)) + latency = re.findall(r'\d+',latency) + assert len(latency) % 4 == 0 + latency = [int(v) for v in latency] + latency = np.array(latency).reshape(int(len(latency)/4), 2, 2) + transfers, confirmations = list(zip(*latency)) + transfers = [i.tolist() for i in transfers] + confirmations = [i.tolist() for i in confirmations] + results = {} + results['transfer'] = {location: [transfers]} + results['confirmation'] = {location: [confirmations]} + + with open(parsed_log_file, 'w') as f: + f.write(str(results)) + +def aggregate(parsed_log_files, aggregated_log_file): + assert len(parsed_log_files) > 1 + + with open(parsed_log_files[0], 'r') as f: + aggregate_orders = eval(f.read()) + + for parsed_log_file in parsed_log_files[1:]: + with open(parsed_log_file, 'r') as f: + data = eval(f.read()) + for (orders_type, orders) in data.items(): + assert len(orders.items()) == 1 + (z_value, items) = list(orders.items())[0] + assert len(items) == 1 + if z_value in aggregate_orders[orders_type]: + aggregate_orders[orders_type][z_value] += items + else: + aggregate_orders[orders_type][z_value] = items + + with open(aggregated_log_file, 'w') as f: + f.write(str(aggregate_orders)) + print('aggregated %d log files' % len(parsed_log_files)) + +def byz(y): + byz_y = [] + for i,v in enumerate(y): + index = int(i/3)*2 + byz_y.append(y[index]) + return byz_y + +def plot(aggregated_log_file, x_label='Committee size', legend_position='upper right'): + with open(aggregated_log_file, 'r') as f: + orders = eval(f.read()) + + for (orders_type, order) in orders.items(): + fig = plt.figure() + for (z_value, items) in order.items(): + x_values = [] + y_values = [] + y_err = [] + for item in items: + x, y = list(zip(*item)) + x = int(x[0]) + y = y[15:len(y)-15] + x_values.append(x) + y_values.append(np.mean(y)) + y_err.append(np.std(y)) + + data = list(zip(x_values, y_values, y_err)) + data.sort(key=lambda tup: tup[0]) + x_values, y_values, y_err = list(zip(*data)) + plt.ylim(0, 300) + plt.errorbar(x_values, y_values, yerr=y_err, uplims=True, lolims=True, + label='%s' % z_value, marker='.', alpha=1, dashes=None) + + plt.legend(loc=legend_position) + plt.xlabel(x_label) + plt.ylabel('Observed latency (ms)') + + plt.savefig('latency-%s.pdf' % orders_type) + print('created figure "latency-%s.pdf".' % orders_type) + +def find(pattern, path): + result = [] + for root, dirs, files in os.walk(path): + for name in files: + if fnmatch.fnmatch(name, pattern): + result.append(os.path.join(root, name)) + return result + +if __name__== '__main__': + aggregated_log = 'aggregated_latency_log.txt' + commands = ['parse', 'aggregate', 'plot', 'all'] + command = sys.argv[1] + + execute_all = command == commands[3] + if command == commands[0] or execute_all: + raw_logs = find('raw_log_latency_*-*.txt', '.') + parsed_logs = ['parsed_%s' % os.path.basename(raw_log) for raw_log in raw_logs] + [parse(raw_log, parsed_log) for (raw_log, parsed_log) in zip(raw_logs, parsed_logs)] + + if command == commands[1] or execute_all: + parsed_logs = find('parsed_raw_log_latency_*.txt', '.') + aggregate(parsed_logs, aggregated_log) + + if command == commands[2] or execute_all: + plot(aggregated_log) diff --git a/scripts/latency_with_crash.py b/scripts/latency_with_crash.py new file mode 100644 index 0000000000000..a252323b51110 --- /dev/null +++ b/scripts/latency_with_crash.py @@ -0,0 +1,44 @@ +# Copyright (c) Facebook Inc. +# SPDX-License-Identifier: Apache-2.0 + +import numpy as np +import re +import sys +import os.path +import os, fnmatch + + +def parse(row_log_file, parsed_log_file): + fname = os.path.abspath(row_log_file) + data = open(fname).read() + + latency = ''.join(re.findall(r'Received certificate after [0-9]* us', data)) + latency = re.findall(r'\d+',latency) + latency = [int(v)/1000 for v in latency] + + print(row_log_file) + print('%d ms (average), %d ms (std)' % (np.mean(latency), np.std(latency))) + print('\n') + +def find(pattern, path): + result = [] + for root, dirs, files in os.walk(path): + for name in files: + if fnmatch.fnmatch(name, pattern): + result.append(os.path.join(root, name)) + return result + +''' +Experiment stes: + 1. Run a testnet with 10 authorities: + fab set_hosts reset deploy + + 2. Submit transactions: + fab set_hosts quick_transfer + + 3. Kill one node, and go at step 2; then repeat. +''' +if __name__== '__main__': + raw_logs = find('raw_log_latency_with_crash-*.txt', '.') + parsed_logs = ['parsed_%s' % os.path.basename(raw_log) for raw_log in raw_logs] + [parse(raw_log, parsed_log) for (raw_log, parsed_log) in zip(raw_logs, parsed_logs)] diff --git a/scripts/microbenchmark.py b/scripts/microbenchmark.py new file mode 100644 index 0000000000000..8b404e881a383 --- /dev/null +++ b/scripts/microbenchmark.py @@ -0,0 +1,28 @@ +# Copyright (c) Facebook Inc. +# SPDX-License-Identifier: Apache-2.0 + +import numpy as np + +# benchmark of serialize_tests +# run: cargo test --release time -- --nocapture + +write_order = [27, 31, 27, 27, 27] +write_vote = [27, 31, 26, 27, 25] +write_cert = [4, 4, 4, 5, 4] + +read_and_check_order = [58, 61, 58, 59, 58] +read_and_check_vote = [60, 62, 60, 60, 58] +read_and_check_cert = [235, 249, 219, 245, 236] + +print('Write Order: %d (average), %d (std)' % (np.mean(write_order), np.std(write_order))) +print('Write Vote: %d (average), %d (std)' % (np.mean(write_vote), np.std(write_vote))) +print('Write Cert: %d (average), %d (std)' % (np.mean(write_cert), np.std(write_cert))) + +print('Read & Check Order: %d (average), %d (std)' % + (np.mean(read_and_check_order), np.std(read_and_check_order))) + +print('Read & Check Vote: %d (average), %d (std)' % + (np.mean(read_and_check_vote), np.std(read_and_check_vote))) + +print('Read & Check Cert: %d (average), %d (std)' % + (np.mean(read_and_check_cert), np.std(read_and_check_cert))) diff --git a/scripts/throughput.py b/scripts/throughput.py new file mode 100644 index 0000000000000..22d74f7838fb2 --- /dev/null +++ b/scripts/throughput.py @@ -0,0 +1,198 @@ +# Copyright (c) Facebook Inc. +# SPDX-License-Identifier: Apache-2.0 + +import numpy as np +import matplotlib.pyplot as plt +import re +import sys +import os.path +import argparse +import os, fnmatch +from collections import Counter, OrderedDict +import operator + +SHARDS = 0 +LOAD = 1 +IN_FLIGHTS = 2 +COMMITTEE = 3 + +""" +Parsed raw logs and prints to disc the following dictionary, where '' is the parameter of the grpah, + is the value of the x-axis, and is the throughput: + +{ + 'transfer': { + '': [ + [(, )] + ], + }, + 'confirmation': { + '': [ + [(, )] + ], + } +} +""" +def parse(log_file, parsed_log_file, x_axis=SHARDS, z_axis=IN_FLIGHTS): + fname = os.path.abspath(log_file) + data = open(fname).read() + + parameters = re.findall(r'\d+', log_file) + x_value = parameters[x_axis] + z_value = parameters[z_axis] + #_accounts = parameters[1] # not used + #in_flights = parameters[2] + #_committee = parameters[3] # not used + + orders_types = ['transfer', 'confirmation'] + orders = {} + for orders_type in orders_types: + orders[orders_type] = {} + tps = ''.join(re.findall(r'Estimated server throughput: [0-9]* %s orders per sec' % orders_type, data)) + tps = re.findall(r'\d+',tps) + assert len(tps) == 1 + orders[orders_type][z_value] = [(x_value, tps[0])] + + with open(parsed_log_file, 'w') as f: + f.write(str(orders)) + +""" +Aggregate parsed logs and prints to disc the following dictionary, where '' is the parameter of the grpah, + is the value of the x-axis, and is the throughput + +{ + 'transfer': { + '': [ + [(, ), (, ), ...], + ... + ], + '': [ + [(, ), (, ), ...], + ... + ], + ... + }, + 'confirmation': { + '': [ + [(, ), (, ), ...], + ... + ], + '': [ + [(, ), (, ), ...], + ... + ], + ... + } +} +""" +def aggregate(parsed_log_files, aggregated_parsed_log_file): + assert len(parsed_log_files) > 1 + + with open(parsed_log_files[0], 'r') as f: + aggregate_orders = eval(f.read()) + + for parsed_log_file in parsed_log_files[1:]: + with open(parsed_log_file, 'r') as f: + data = eval(f.read()) + for (orders_type, orders) in data.items(): + assert len(orders.items()) == 1 + (z_value, items) = list(orders.items())[0] + assert len(items) == 1 + if z_value in aggregate_orders[orders_type]: + aggregate_orders[orders_type][z_value] += items + else: + aggregate_orders[orders_type][z_value] = items + + for (orders_type, orders) in aggregate_orders.items(): + for (z_value, items) in orders.items(): + items.sort(key=lambda tup: int(tup[0])) + counter = Counter(item[0] for item in items) + shards = len(counter.items()) + runs = list(counter.values())[0] + assert runs * shards == len(items) + arr = np.array(items) + items = arr.reshape((shards,runs,2)).tolist() + aggregate_orders[orders_type][z_value] = items + print(aggregate_orders) + + with open(aggregated_parsed_log_file, 'w') as f: + f.write(str(aggregate_orders)) + + +""" +Load parsed logs (as produced by 'parse'), and saves the following figures as PDF: + - the throughput of transfer orders VS the number of processes, for multiple max in-flight values + - the throughput of confirmation orders VS the number of processes, for multiple max in-flight values +""" +def plot(parsed_log_file, x_label='Number of shards', z_label='tx in-flight', legend_position='lower right', style='plot'): + with open(parsed_log_file, 'r') as f: + orders = eval(f.read()) + + for (orders_type, order) in orders.items(): + fig = plt.figure() + width = 2 + i = -3 + for (z_value, items) in sorted(order.items(), reverse=True): + x_values = [] + y_values = [] + y_err = [] + for item in items: + x, y = list(zip(*item)) + x = int(x[0]) + y = np.array(y).astype(np.int) + x_values.append(x) + y_values.append(np.mean(y)) + y_err.append(np.std(y)) + if style == 'bar': + plt.bar(np.array(x_values) + i, y_values, width, yerr=y_err, + label='%s %s' % (z_value, z_label)) + i = i + width + plt.xticks(x_values, x_values) + else: + #plt.plot(x_values, y_values) + plt.ylim(0, 180000) + plt.errorbar(x_values, y_values, yerr=y_err, uplims=True, lolims=True, + label='%s %s' % (z_value, z_label), marker='.', alpha=1, dashes=None) + + plt.legend(loc=legend_position) + plt.xlabel(x_label) + plt.ylabel('Observed throughput (tx / sec)') + plt.savefig('%s.pdf' % orders_type) + print('created figure "%s.pdf".' % orders_type) + +""" +Utility to find files +""" +def find(pattern, path): + result = [] + for root, dirs, files in os.walk(path): + for name in files: + if fnmatch.fnmatch(name, pattern): + result.append(os.path.join(root, name)) + return result + +if __name__== '__main__': + aggregated_log = 'aggregated_tps_log.txt' + commands = ['parse', 'aggregate', 'plot', 'all'] + command = 'plot' + + ''' + parser = argparse.ArgumentParser() + parser.add_argument('-c', action='store', dest='command', help = 'Command to execute (parse, aggregate, plot).') + args = vars(parser.parse_args()) + command = args['command'] + print(args) + ''' + + execute_all = command == commands[3] + if command == commands[0] or execute_all: + raw_logs = find('*.txt.*.*.*.*', '.') + parsed_logs = ['%s_parsed' % raw_log for raw_log in raw_logs] + [parse(raw_log, parsed_log, x_axis=SHARDS, z_axis=IN_FLIGHTS) for (raw_log, parsed_log) in zip(raw_logs, parsed_logs)] + + if command == commands[1] or execute_all: + parsed_logs = find('*_parsed', '.') + aggregate(parsed_logs, aggregated_log) + + if command == commands[2] or execute_all: + plot(aggregated_log, x_label='Committee size', z_label='tx shards')