diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..2381115 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,886 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "autocfg" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" + +[[package]] +name = "blake2" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84ce5b6108f8e154604bd4eb76a2f726066c3464d5a552a4229262a18c9bb471" +dependencies = [ + "byte-tools", + "byteorder", + "crypto-mac", + "digest", + "opaque-debug", +] + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e4cec68f03f32e44924783795810fa50a7035d8c8ebe78580ad7e6c703fba38" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "compauth" +version = "0.1.0" +dependencies = [ + "futures-util", + "hyper", + "num_cpus", + "rand", + "rust-clacc", + "serde", + "serde_json", + "tokio", + "velocypack", +] + +[[package]] +name = "crossbeam" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69323bff1fb41c635347b8ead484a5ca6c3f11914d784170b158d8449ab07f8e" +dependencies = [ + "cfg-if", + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-epoch", + "crossbeam-queue", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-channel" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cced8691919c02aac3cb0a1bc2e9b73d89e832bf9a06fc579d4e71b68a2da061" +dependencies = [ + "crossbeam-utils", + "maybe-uninit", +] + +[[package]] +name = "crossbeam-deque" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", + "maybe-uninit", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" +dependencies = [ + "autocfg", + "cfg-if", + "crossbeam-utils", + "lazy_static", + "maybe-uninit", + "memoffset", + "scopeguard", +] + +[[package]] +name = "crossbeam-queue" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "maybe-uninit", +] + +[[package]] +name = "crossbeam-utils" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" +dependencies = [ + "autocfg", + "cfg-if", + "lazy_static", +] + +[[package]] +name = "crypto-mac" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" +dependencies = [ + "generic-array", + "subtle", +] + +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[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-channel" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f366ad74c28cca6ba456d95e6422883cfb4b252a83bed929c83abfdbbf2967d5" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59f5fff90fd5d971f936ad674802482ba441b6f09ba5e15fd8b39145582ca399" + +[[package]] +name = "futures-macro" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0b5a30a4328ab5473878237c447333c093297bded83a4983d10f4deea240d39" +dependencies = [ + "proc-macro-hack", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f2032893cb734c7a05d85ce0cc8b8c4075278e93b24b66f9de99d6eb0fa8acc" + +[[package]] +name = "futures-task" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdb66b5f09e22019b1ab0830f7785bcea8e7a42148683f99214f73f8ec21a626" +dependencies = [ + "once_cell", +] + +[[package]] +name = "futures-util" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8764574ff08b701a084482c3c7031349104b07ac897393010494beaa18ce32c6" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project", + "pin-utils", + "proc-macro-hack", + "proc-macro-nested", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60fb4bb6bba52f78a471264d9a3b7d026cc0af47b22cd2cffbc0b787ca003e63" +dependencies = [ + "typenum", + "version_check", +] + +[[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 = "h2" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993f9e0baeed60001cf565546b0d3dbe6a6ad23f2bd31644a133c641eccf6d53" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hermit-abi" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3deed196b6e7f9e44a2ae8d94225d80302d81208b1bb673fd21fe634645c85a9" +dependencies = [ + "libc", +] + +[[package]] +name = "http" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d569972648b2c512421b5f2a405ad6ac9666547189d0c5477a3f200f3e02f9" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13d5ff830006f7646652e057693569bfe0d51760c0085a071769d142a205111b" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "httparse" +version = "1.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9" + +[[package]] +name = "hyper" +version = "0.13.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e68a8dd9716185d9e64ea473ea6ef63529252e3e27623295a0378a19665d5eb" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project", + "socket2", + "time", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "indexmap" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c398b2b113b55809ceb9ee3e753fcbac793f1956663f3c36549c1346015c2afe" +dependencies = [ + "autocfg", +] + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6" + +[[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.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9f8082297d534141b30c8d39e9b1773713ab50fdbe4ff30f750d063b3bfd701" + +[[package]] +name = "log" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "maybe-uninit" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" + +[[package]] +name = "memchr" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" + +[[package]] +name = "memoffset" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c198b026e1bbf08a937e94c6c60f9ec4a2267f5b0d2eec9c1b21b061ce2be55f" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mio" +version = "0.6.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fce347092656428bc8eaf6201042cb551b8d67855af7374542a92a0fbfcac430" +dependencies = [ + "cfg-if", + "fuchsia-zircon", + "fuchsia-zircon-sys", + "iovec", + "kernel32-sys", + "libc", + "log", + "miow", + "net2", + "slab", + "winapi 0.2.8", +] + +[[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 = "net2" +version = "0.2.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ba7c918ac76704fb42afcbbb43891e72731f3dcca3bef2a19786297baf14af7" +dependencies = [ + "cfg-if", + "libc", + "winapi 0.3.9", +] + +[[package]] +name = "num-traits" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31" +dependencies = [ + "num-traits 0.2.12", +] + +[[package]] +name = "num-traits" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac267bcc07f48ee5f8935ab0d24f316fb722d7a1292e2913f0cc196b29ffd611" +dependencies = [ + "autocfg", +] + +[[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 = "once_cell" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b631f7e854af39a1739f401cf34a8a013dfe09eac4fa4dba91e9768bd28168d" + +[[package]] +name = "opaque-debug" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" + +[[package]] +name = "pin-project" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e3a6cdbfe94a5e4572812a0201f8c0ed98c1c452c7b8563ce2276988ef9c17" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a0ffd45cf79d88737d7cc85bfd5d2894bee1139b356e616fe85dc389c61aaf7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282adbf10f2698a7a77f8e983a74b2d18176c19a7fd32a45446139ae7b02b715" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "ppv-lite86" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "237a5ed80e274dbc66f86bd59c1e25edc039660be53194b5fe0a482e0f2612ea" + +[[package]] +name = "proc-macro-hack" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e0456befd48169b9f13ef0f0ad46d492cf9d2dbb918bcf38e01eed4ce3ec5e4" + +[[package]] +name = "proc-macro-nested" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eba180dafb9038b050a4c280019bbedf9f2467b61e5d892dcad585bb57aadc5a" + +[[package]] +name = "proc-macro2" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "beae6331a816b1f65d04c45b078fd8e6c93e8071771f41b8163255bbd8d7c8fa" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "quote" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37" +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.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" + +[[package]] +name = "rust-clacc" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32ab0329c1c0ab599289a4efbaea0504f1aed48ceb47e9f111a6500b850ba160" +dependencies = [ + "blake2", + "crossbeam", + "generic-array", + "rand", + "rust-gmp", + "serde", + "typenum", + "velocypack", +] + +[[package]] +name = "rust-gmp" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3ddf28998d5730b96a9fe188557953de503d77ff403ae175ad1417921e5d906" +dependencies = [ + "libc", + "num-traits 0.1.43", +] + +[[package]] +name = "ryu" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "serde" +version = "1.0.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5317f7588f0a5078ee60ef675ef96735a1442132dc645eb1d12c018620ed8cd3" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a0be94b04690fbaed37cddffc5c134bf537c8e3329d53e982fe04c374978f8e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3433e879a558dde8b5e8feb2a04899cf34fdde1fafb894687e52105fc1162ac3" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[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.9", +] + +[[package]] +name = "subtle" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502d53007c02d7605a05df1c1a73ee436952781653da5d0bf57ad608f66932c1" + +[[package]] +name = "syn" +version = "1.0.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "936cae2873c940d92e697597c5eee105fb570cd5689c695806f672883653349b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "time" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438" +dependencies = [ + "libc", + "winapi 0.3.9", +] + +[[package]] +name = "tokio" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d099fa27b9702bed751524694adbe393e18b36b204da91eb1cbbbbb4a5ee2d58" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "iovec", + "lazy_static", + "memchr", + "mio", + "num_cpus", + "pin-project-lite", + "slab", + "tokio-macros", +] + +[[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 = "tokio-util" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be8242891f2b6cbef26a2d7e8605133c2c554cd35b3e4948ea892d6d68436499" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "log", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower-service" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e987b6bf443f4b5b3b6f38704195592cca41c5bb7aedd3c3693c7081f8289860" + +[[package]] +name = "tracing" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2e2a2de6b0d5cbb13fc21193a2296888eaab62b6044479aafb3c54c01c29fcd" +dependencies = [ + "cfg-if", + "log", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94ae75f0d28ae10786f3b1895c55fe72e79928fd5ccdebb5438c75e93fec178f" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "try-lock" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" + +[[package]] +name = "typenum" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "373c8a200f9e67a0c95e62a4f52fbf80c23b4381c05a17845531982fa99e6b33" + +[[package]] +name = "unicode-xid" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" + +[[package]] +name = "velocypack" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "997d1df4ebf8dc1202519028ec01245ca067393da48fedc3b1f9a95e250f2920" +dependencies = [ + "serde", +] + +[[package]] +name = "version_check" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed" + +[[package]] +name = "want" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +dependencies = [ + "log", + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-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-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", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..0e2206f --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "compauth" +version = "0.1.0" +authors = ["John Driscoll "] +edition = "2018" + +[dependencies] +futures-util = "0.3.5" +hyper = "0.13.7" +num_cpus = "1.13.0" +rand = "0.7.3" +rust-clacc = "0.5.0" +serde = {version = "1.0.114", features = ["derive"]} +serde_json = "1.0.56" +tokio = {version = "0.2.21", features = ["macros", "rt-threaded", "tcp", "time"]} +velocypack = "0.1.1" + +[[bin]] +name = "authority" +path = "src/service/authority.rs" + +[[bin]] +name = "worker" +path = "src/service/worker.rs" + +[[bin]] +name = "synchronizer" +path = "src/service/synchronizer.rs" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b1edbc1 --- /dev/null +++ b/README.md @@ -0,0 +1,145 @@ +# Compressing Authority + +A scalable proof-of-concept permission system using CL accumulators that is +resistant to downgrade attacks while reducing the security boundary to a +minimal physical device. + +## Usage + +Start the necessary services: + +```shell +$ cargo run --bin authority & +$ cargo run --bin worker & +$ cargo run --bin synchronizer & +``` + +Try adding a permission: + +```shell +$ curl -X POST localhost:3000/permission -w "\n" -d @- << EOF +> ["tick"] +> EOF +{"nonce":8302967033790438,"actions":["tick"],"version":0} +``` + +After the next update window has closed (60 seconds by default), you are +able to perform the `tick` action: + +```shell +$ curl -X POST localhost:3000/action -w "%{http_code}\n" -d @- << EOF +> { +> "perm": { +> "nonce": 8302967033790438, +> "actions": ["tick"], +> "version": 0 +> }, +> "action": "tick" +> } +> EOF +200 +``` + +Update the permission with a new action: + +```shell +$ curl -X PUT localhost:3000/permission -w "\n" -d @- << EOF +> { +> "perm": { +> "nonce": 8302967033790438, +> "actions": ["tick"], +> "version": 0 +> }, +> "actions": ["tock"] +> } +> EOF +{"nonce":8302967033790438,"actions":["tock"],"version":1} +``` + +Wait another minute for the next update and try performing the new action: + +```shell +$ curl -X POST localhost:3000/action -w "%{http_code}\n" -d @- << EOF +> { +> "perm": { +> "nonce": 8302967033790438, +> "actions": ["tock"], +> "version": 1 +> }, +> "action": "tock" +> } +> EOF +200 +``` + +You can also verify that attempting an action using the previous version of the +permission results in an 401 Unauthorized: + +```shell +$ curl -X POST localhost:3000/action -w "%{http_code}\n" -d @- << EOF +> { +> "perm": { +> "nonce": 8302967033790438, +> "actions": ["tick"], +> "version": 0 +> }, +> "action": "tick" +> } +> EOF +401 +``` + +In order to test that witness updates are correct for static elements, add +a new permission: + +```shell +$ curl -X POST localhost:3000/permission -w "\n" -d @- << EOF +> ["tack"] +> EOF +{"nonce":3276091879824438,"actions":["tack"],"version":0} +``` + +Thanks to the update window, service for the `tock` permission will not be +impacted by the addition of the `tack` permission: + +```shell +$ curl -X POST localhost:3000/action -w "%{http_code}\n" -d @- << EOF +> { +> "perm": { +> "nonce": 3276091879824438, +> "actions": ["tock"], +> "version": 1 +> }, +> "action": "tock" +> } +> EOF +200 +``` + +When the next update window is closed, you can verify that both permissions are +served successfully: + +```shell +$ curl -X POST localhost:3000/action -w "%{http_code}\n" -d @- << EOF +> { +> "perm": { +> "nonce": 3276091879824438, +> "actions": ["tack"], +> "version": 0 +> }, +> "action": "tack" +> } +> EOF +200 +$ curl -X POST localhost:3000/action -w "%{http_code}\n" -d @- << EOF +> { +> "perm": { +> "nonce": 8302967033790438, +> "actions": ["tock"], +> "version": 1 +> }, +> "action": "tock" +> } +> EOF +200 +``` diff --git a/src/authority.rs b/src/authority.rs new file mode 100644 index 0000000..6ed8dc6 --- /dev/null +++ b/src/authority.rs @@ -0,0 +1,145 @@ +use clacc::{ + Accumulator, + blake2::Mapper as M, + gmp::BigInt, + velocypack::VpackSerializer, + typenum::U16 as N, +}; +use tokio::sync::Mutex; +use crate::permission::Permission; +use crate::request::{UpdateRequest, UpdateResponse, ActionRequest}; + +/// Type for a VelocyPack serialized Permission. +type S = VpackSerializer; + +/// An Authority that controls the private key of an accumulator and is able +/// to add and delete Permissions. +pub struct Authority { + + /// The Accumulator's public key. + key: BigInt, + + /// The Accumulator used to verify Permissions. + verifying: Accumulator, + + /// The Accumulator containing Permissions whose Witnesses are currently + /// being updated by the Worker. + updating: Accumulator, + + /// The Accumulator containing the most recent versions of all + /// Permissions. + staging: Accumulator, + + /// Mutex locked while the Authority is operating on its Accumulators. + guard: Mutex<()>, +} + +impl Authority { + + /// Create a new Authority. + pub fn new() -> Self { + // Generate an accumulator. In a real world scenario, the + // Accumulator's private key would be generated and sharded as part of + // a key ceremony. Security officers entrusted with the shards would + // then submit their part of the key to the Authority server in order + // to reconstitute in a secure hardware environment. This is out-of- + // scope for the purposes of this demonstration, so an Accumulator is + // instead initialized from a random private key. + let (acc, _, _) = Accumulator::::with_random_key(None); + // Allocate the Authority using the public key and three copies of the + // Accumulator for each phase of the update process. + Authority { + key: acc.get_public_key().clone(), + verifying: acc.clone(), + updating: acc.clone(), + staging: acc.clone(), + guard: Mutex::new(()), + } + } + + /// Return the Accumulator's public key. + pub fn get_key(&self) -> &BigInt { + &self.key + } + + /// Add a Permission. + pub async fn add_permission( + &mut self, + mut perm: Permission, + ) -> Permission { + // Lock the Mutex. + let _guard = self.guard.lock().await; + // Assign a random Nonce that prevents other Permissions from + // overwriting this Permission in the future. + perm.nonce = rand::random::().into(); + // Add the Permission to the staging Accumulator. + self.staging.add::(&perm); + // Return the Permission with the new Nonce. + perm + } + + /// Update an existing Permission. + pub async fn update_permission( + &mut self, + req: UpdateRequest, + ) -> Result { + // Ensure the new Permission's Nonce matches the old Permission's + // Nonce. + if req.update.nonce != req.perm.nonce { + return Err("nonce mismatch"); + } + // Ensure the new Permission's version is greater than the old + // Permission's version. + if req.update.version <= req.perm.version { + return Err("new version must be greater than old version"); + } + // Lock the Mutex. + let _guard = self.guard.lock().await; + // Delete the old Permission from the staging Accumulator. + self.staging.del::(&req.perm, &req.witness)?; + // Add the new Permission to the staging Accumulator. + self.staging.add::(&req.update); + // Return the latest accumulation value. + Ok(UpdateResponse { + req: req, + value: self.staging.get_value().clone(), + }) + } + + /// Perform an action if a given Permission is part of the Accumulation. + pub async fn action( + &self, + req: ActionRequest, + ) -> Result<(), &'static str> { + // Lock the Mutex. + let _guard = self.guard.lock().await; + // Verify the Permission is part of the verifying Accumulator. + self.verifying.verify::(&req.perm, &req.witness)?; + // Ensure the requested action is in the actions list. + match req.perm.actions.iter().find(|&action| action == &req.action) { + Some(_) => Ok(()), + None => Err("permission not granted to perform action"), + } + } + + /// Copy the current staging Accumulator to the updating Accumulator. + /// + /// This should be called when the Worker begins updating Witnesses so + /// that the updating Accumulator captures all Permission additions and + /// deletions made during the update window. + pub async fn update(&mut self) { + let _guard = self.guard.lock().await; + self.updating = self.staging.clone(); + } + + /// Copy the current updating Accumulator to the verifying Accumulator. + /// + /// This should be called when the Worker has finished updating all + /// Witnesses so that the verifying Accumulator reflects all additions + /// and deletions that have been captured during the previous update + /// window. + pub async fn sync(&mut self) { + let _guard = self.guard.lock().await; + self.verifying = self.updating.clone(); + } +} diff --git a/src/constant.rs b/src/constant.rs new file mode 100644 index 0000000..4662592 --- /dev/null +++ b/src/constant.rs @@ -0,0 +1,4 @@ +pub const SYNCHRONIZER_ADDR: &str = "127.0.0.1:3000"; +pub const AUTHORITY_ADDR: &str = "127.0.0.1:3001"; +pub const WORKER_ADDR: &str = "127.0.0.1:3002"; +pub const UPDATE_WINDOW_MILLIS: u64 = 1 * 60 * 1000; diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..00a5da6 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,8 @@ +pub mod authority; +pub mod worker; +pub mod synchronizer; +pub mod constant; +pub mod permission; +pub mod request; +pub mod u53; +pub mod util; diff --git a/src/permission.rs b/src/permission.rs new file mode 100644 index 0000000..2ed0329 --- /dev/null +++ b/src/permission.rs @@ -0,0 +1,28 @@ +use serde::{Serialize, Deserialize}; +use crate::u53::u53; + +/// A unique number assigned to new Permissions by the Authority. +pub type Nonce = u53; + +/// Actions are identified by a string such as "sign-in" or "send-message". +pub type Action = String; + +/// A Permission is a versioned collection of actions. +#[derive(Serialize, Deserialize, Clone)] +pub struct Permission { + + /// The Permission's unique nonce. + /// + /// This acts like an ID and will persist for the Permission across + /// its lifetime of updates. + pub nonce: Nonce, + + /// The actions this Permission allows its owner to take. + pub actions: Vec, + + /// The version of the Permission. + /// + /// This must be incremented every time the Permission is updated with + /// different actions. + pub version: usize, +} diff --git a/src/request.rs b/src/request.rs new file mode 100644 index 0000000..1a1375e --- /dev/null +++ b/src/request.rs @@ -0,0 +1,44 @@ +use clacc::{Witness, gmp::BigInt}; +use serde::{Serialize, Deserialize}; +use crate::permission::{Action, Permission}; + +/// A request to perform an action. +#[derive(Deserialize, Serialize)] +pub struct ActionRequest { + + /// The Permission associated with the action. + pub perm: Permission, + + /// The Witness attesting that the Permission is a member of the + /// accumulation. + pub witness: Witness, + + /// The action being taken. + pub action: Action, +} + +/// A request to update an existing Permission by altering its actions. +#[derive(Deserialize, Serialize)] +pub struct UpdateRequest { + + /// The previous version of the Permission. + pub perm: Permission, + + /// The Witness attesting that the previous version of the Permission + /// is a member of the accumulation. + pub witness: Witness, + + /// The new version of the Permission. + pub update: Permission, +} + +/// A response to the UpdateRequest. +#[derive(Deserialize, Serialize)] +pub struct UpdateResponse { + + /// The original UpdateRequest. + pub req: UpdateRequest, + + /// The accumulation value after the Permision has been updated. + pub value: BigInt, +} diff --git a/src/service/authority.rs b/src/service/authority.rs new file mode 100644 index 0000000..a3d2473 --- /dev/null +++ b/src/service/authority.rs @@ -0,0 +1,155 @@ +use compauth::{ + authority::Authority, + constant::AUTHORITY_ADDR, + permission::Permission, + request::{UpdateRequest, ActionRequest}, + util::{to_bytes, from_bytes}, +}; +use hyper::{ + Body, Error, Method, Request, Response, Server, StatusCode, + service::{make_service_fn, service_fn}, +}; +use std::{convert::Infallible, sync::{Arc, atomic::AtomicPtr}}; +use tokio::sync::Mutex; + +async fn handle_key( + m: Arc>>, +) -> Response { + let auth = unsafe { + (*m.lock().await).get_mut().as_ref().unwrap() + }; + let resp = velocypack::to_bytes(auth.get_key()).unwrap(); + Response::new(resp.into()) +} + +async fn handle_add_perm( + m: Arc>>, + req: Request, +) -> Response { + let bytes = to_bytes(req.into_body()).await; + let perm: Permission = match from_bytes(bytes.as_ref()) { + Some(res) => res, + None => { + let mut bad_request = Response::default(); + *bad_request.status_mut() = StatusCode::BAD_REQUEST; + return bad_request; + }, + }; + let auth = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + let result = auth.add_permission(perm).await; + let resp = velocypack::to_bytes(&result).unwrap(); + Response::new(resp.into()) +} + +async fn handle_update_perm( + m: Arc>>, + req: Request, +) -> Response { + let bytes = to_bytes(req.into_body()).await; + let req: UpdateRequest = match from_bytes(bytes.as_ref()) { + Some(res) => res, + None => { + let mut bad_request = Response::default(); + *bad_request.status_mut() = StatusCode::BAD_REQUEST; + return bad_request; + }, + }; + let auth = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match auth.update_permission(req).await { + Ok(result) => { + let resp = velocypack::to_bytes(&result).unwrap(); + Response::new(resp.into()) + }, + _ => { + let mut unauthorized = Response::default(); + *unauthorized.status_mut() = StatusCode::UNAUTHORIZED; + unauthorized + }, + } +} + +async fn handle_action( + m: Arc>>, + req: Request, +) -> Response { + let bytes = to_bytes(req.into_body()).await; + let req: ActionRequest = match from_bytes(bytes.as_ref()) { + Some(res) => res, + None => { + let mut bad_request = Response::default(); + *bad_request.status_mut() = StatusCode::BAD_REQUEST; + return bad_request; + }, + }; + let auth = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match auth.action(req).await { + Ok(_) => Response::default(), + _ => { + let mut unauthorized = Response::default(); + *unauthorized.status_mut() = StatusCode::UNAUTHORIZED; + unauthorized + }, + } +} + +async fn handle_update( + m: Arc>>, +) -> Response { + let auth = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + auth.update().await; + Response::default() +} + +async fn handle_sync( + m: Arc>>, +) -> Response { + let auth = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + auth.sync().await; + Response::default() +} + +async fn handle( + m: Arc>>, + req: Request, +) -> Result, Error> { + match (req.method(), req.uri().path()) { + (&Method::GET, "/key") => Ok(handle_key(m).await), + (&Method::POST, "/permission") => Ok(handle_add_perm(m, req).await), + (&Method::PUT, "/permission") => Ok(handle_update_perm(m, req).await), + (&Method::POST, "/action") => Ok(handle_action(m, req).await), + (&Method::GET, "/update") => Ok(handle_update(m).await), + (&Method::GET, "/sync") => Ok(handle_sync(m).await), + _ => { + let mut not_found = Response::default(); + *not_found.status_mut() = StatusCode::NOT_FOUND; + Ok(not_found) + } + } +} + +#[tokio::main] +async fn main() { + let mut authority = Authority::new(); + let m = Arc::new(Mutex::new(AtomicPtr::new(&mut authority))); + let make_service = make_service_fn(move |_| { + let m = Arc::clone(&m); + async move { + Ok::<_, Infallible>(service_fn(move |req| { + handle(Arc::clone(&m), req) + })) + } + }); + let addr = AUTHORITY_ADDR.parse().unwrap(); + let server = Server::bind(&addr).serve(make_service); + server.await.unwrap(); +} diff --git a/src/service/synchronizer.rs b/src/service/synchronizer.rs new file mode 100644 index 0000000..91ab3c9 --- /dev/null +++ b/src/service/synchronizer.rs @@ -0,0 +1,138 @@ +use compauth::{ + synchronizer::Synchronizer, + constant::SYNCHRONIZER_ADDR, + permission::{Action, Permission}, + util::{to_bytes, from_json}, +}; +use hyper::{ + Body, Error, Method, Request, Response, Server, StatusCode, + service::{make_service_fn, service_fn}, +}; +use serde::Deserialize; +use std::{convert::Infallible, sync::{Arc, atomic::AtomicPtr}}; +use tokio::sync::Mutex; + +#[derive(Deserialize)] +struct UpdateRequest { + perm: Permission, + actions: Vec, +} + +#[derive(Deserialize)] +struct ActionRequest { + perm: Permission, + action: Action, +} + +async fn handle_add_perm( + m: Arc>>, + req: Request, +) -> Response { + let bytes = to_bytes(req.into_body()).await; + let actions: Vec = match from_json(bytes.as_ref()) { + Some(res) => res, + None => { + let mut bad_request = Response::default(); + *bad_request.status_mut() = StatusCode::BAD_REQUEST; + return bad_request; + }, + }; + let sync = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match sync.add_permission(actions).await { + Ok(res) => Response::new(serde_json::to_string(&res).unwrap().into()), + _ => { + let mut unauthorized = Response::default(); + *unauthorized.status_mut() = StatusCode::UNAUTHORIZED; + unauthorized + }, + } +} + +async fn handle_update_perm( + m: Arc>>, + req: Request, +) -> Response { + let bytes = to_bytes(req.into_body()).await; + let req: UpdateRequest = match from_json(bytes.as_ref()) { + Some(res) => res, + None => { + let mut bad_request = Response::default(); + *bad_request.status_mut() = StatusCode::BAD_REQUEST; + return bad_request; + }, + }; + let sync = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match sync.update_permission(req.perm, req.actions).await { + Ok(res) => Response::new(serde_json::to_string(&res).unwrap().into()), + _ => { + let mut unauthorized = Response::default(); + *unauthorized.status_mut() = StatusCode::UNAUTHORIZED; + unauthorized + }, + } +} + +async fn handle_action( + m: Arc>>, + req: Request, +) -> Response { + let bytes = to_bytes(req.into_body()).await; + let req: ActionRequest = match from_json(bytes.as_ref()) { + Some(res) => res, + None => { + let mut bad_request = Response::default(); + *bad_request.status_mut() = StatusCode::BAD_REQUEST; + return bad_request; + }, + }; + let sync = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match sync.action(req.perm, req.action).await { + Ok(_) => Response::default(), + _ => { + let mut unauthorized = Response::default(); + *unauthorized.status_mut() = StatusCode::UNAUTHORIZED; + unauthorized + }, + } +} + +async fn handle( + m: Arc>>, + req: Request, +) -> Result, Error> { + match (req.method(), req.uri().path()) { + (&Method::POST, "/permission") => Ok(handle_add_perm(m, req).await), + (&Method::PUT, "/permission") => Ok(handle_update_perm(m, req).await), + (&Method::POST, "/action") => Ok(handle_action(m, req).await), + _ => { + let mut not_found = Response::default(); + *not_found.status_mut() = StatusCode::NOT_FOUND; + Ok(not_found) + } + } +} + +#[tokio::main] +async fn main() { + let mut sync = Synchronizer::new().await.unwrap(); + let m = Arc::new(Mutex::new(AtomicPtr::new(&mut sync))); + let make_service = make_service_fn(move |_| { + let m = Arc::clone(&m); + async move { + Ok::<_, Infallible>(service_fn(move |req| { + handle(Arc::clone(&m), req) + })) + } + }); + let addr = SYNCHRONIZER_ADDR.parse().unwrap(); + let server = Server::bind(&addr).serve(make_service); + let sync_future = sync.sync(); + server.await.unwrap(); + sync_future.await.unwrap().unwrap(); +} diff --git a/src/service/worker.rs b/src/service/worker.rs new file mode 100644 index 0000000..079717b --- /dev/null +++ b/src/service/worker.rs @@ -0,0 +1,198 @@ +use clacc::gmp::BigInt; +use compauth::{ + constant::WORKER_ADDR, + permission::{Nonce, Permission}, + request::UpdateResponse, + util::{to_bytes, from_bytes}, + worker::Worker, +}; +use hyper::{ + Body, Error, Method, Request, Response, Server, StatusCode, + service::{make_service_fn, service_fn}, +}; +use tokio::sync::Mutex; +use std::{convert::Infallible, sync::{Arc, atomic::AtomicPtr}}; + +async fn handle_key( + m: Arc>>, + req: Request, +) -> Response { + let bytes = to_bytes(req.into_body()).await; + let key: BigInt = match from_bytes(bytes.as_ref()) { + Some(res) => res, + None => { + let mut bad_request = Response::default(); + *bad_request.status_mut() = StatusCode::BAD_REQUEST; + return bad_request; + }, + }; + let worker = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match worker.set_key(key).await { + Ok(_) => Response::default(), + _ => { + let mut forbidden = Response::default(); + *forbidden.status_mut() = StatusCode::FORBIDDEN; + forbidden + }, + } +} + +async fn handle_add_perm( + m: Arc>>, + req: Request, +) -> Response { + let bytes = to_bytes(req.into_body()).await; + let perm: Permission = match from_bytes(bytes.as_ref()) { + Some(res) => res, + None => { + let mut bad_request = Response::default(); + *bad_request.status_mut() = StatusCode::BAD_REQUEST; + return bad_request; + }, + }; + let worker = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match worker.add_permission(perm).await { + Ok(_) => Response::default(), + _ => { + let mut forbidden = Response::default(); + *forbidden.status_mut() = StatusCode::FORBIDDEN; + forbidden + }, + } +} + +async fn handle_update_perm( + m: Arc>>, + req: Request, +) -> Response { + let bytes = to_bytes(req.into_body()).await; + let res: UpdateResponse = match from_bytes(bytes.as_ref()) { + Some(res) => res, + None => { + let mut bad_request = Response::default(); + *bad_request.status_mut() = StatusCode::BAD_REQUEST; + return bad_request; + }, + }; + let worker = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match worker.update_permission(res).await { + Ok(_) => Response::default(), + _ => { + let mut forbidden = Response::default(); + *forbidden.status_mut() = StatusCode::FORBIDDEN; + forbidden + }, + } +} + +async fn handle_witness( + m: Arc>>, + nonce: Nonce, +) -> Response { + let worker = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match worker.witness(nonce).await { + Ok(res) => match res { + Some(witness) => { + let resp = velocypack::to_bytes(&witness).unwrap(); + Response::new(resp.into()) + }, + None => { + let mut unauthorized = Response::default(); + *unauthorized.status_mut() = StatusCode::UNAUTHORIZED; + unauthorized + }, + }, + _ => { + let mut forbidden = Response::default(); + *forbidden.status_mut() = StatusCode::FORBIDDEN; + forbidden + }, + } +} + +async fn handle_update( + m: Arc>>, +) -> Response { + let worker = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + match worker.update().await { + Ok(_) => Response::default(), + _ => { + let mut forbidden = Response::default(); + *forbidden.status_mut() = StatusCode::FORBIDDEN; + forbidden + }, + } +} + +async fn handle_sync( + m: Arc>>, +) -> Response { + let worker = unsafe { + (*m.lock().await).get_mut().as_mut().unwrap() + }; + worker.sync().await; + Response::default() +} + +async fn handle( + m: Arc>>, + req: Request, +) -> Result, Error> { + match (req.method(), req.uri().path()) { + (&Method::POST, "/key") => Ok(handle_key(m, req).await), + (&Method::POST, "/permission") => Ok(handle_add_perm(m, req).await), + (&Method::PUT, "/permission") => Ok(handle_update_perm(m, req).await), + (&Method::GET, "/update") => Ok(handle_update(m).await), + (&Method::GET, "/sync") => Ok(handle_sync(m).await), + _ => { + let path_bytes = req.uri().path().as_bytes(); + if path_bytes.len() > 0 && path_bytes[0] == b'/' { + let parts: Vec<&str> = req.uri().path().split("/").collect(); + if parts.len() == 3 { + match parts[1] { + "witness" => match parts[2].parse::() { + Ok(nonce) => { + return Ok(handle_witness( + m, + nonce.into() + ).await); + }, + _ => {}, + }, + _ => {}, + } + } + } + let mut not_found = Response::default(); + *not_found.status_mut() = StatusCode::NOT_FOUND; + Ok(not_found) + } + } +} + +#[tokio::main] +async fn main() { + let mut worker = Worker::new(); + let m = Arc::new(Mutex::new(AtomicPtr::new(&mut worker))); + let make_service = make_service_fn(move |_| { + let m = Arc::clone(&m); + async move { + Ok::<_, Infallible>(service_fn(move |req| { + handle(Arc::clone(&m), req) + })) + } + }); + let addr = WORKER_ADDR.parse().unwrap(); + let server = Server::bind(&addr).serve(make_service); + server.await.unwrap(); +} diff --git a/src/synchronizer.rs b/src/synchronizer.rs new file mode 100644 index 0000000..b0081fb --- /dev/null +++ b/src/synchronizer.rs @@ -0,0 +1,219 @@ +use clacc::{Witness, gmp::BigInt}; +use std::sync::atomic::AtomicPtr; +use tokio::{sync::Mutex, task::JoinHandle, time::{interval, Duration}}; +use crate::{ + constant::{AUTHORITY_ADDR, WORKER_ADDR, UPDATE_WINDOW_MILLIS}, + permission::{Action, Nonce, Permission}, + request::{ActionRequest, UpdateRequest, UpdateResponse}, + util::{from_bytes, to_bytes, AddrBaseClient}, +}; + +/// A Synchronizer manages the Witness update window by synchronizing +/// the Authority and the Worker. +/// +/// Requests to the system need to go through the Synchronizer to +/// eliminate possible race conditions during the update process. +pub struct Synchronizer { + auth_client: AddrBaseClient, + worker_client: AddrBaseClient, + guard_acc: Mutex<()>, + guard_update: Mutex<()>, +} + +impl Synchronizer { + + /// Create a new Synchronizer. + pub async fn new() -> Result { + Synchronizer { + auth_client: AddrBaseClient::new("http://", AUTHORITY_ADDR), + worker_client: AddrBaseClient::new("http://", WORKER_ADDR), + guard_acc: Mutex::new(()), + guard_update: Mutex::new(()), + }.key_worker().await + } + + /// Set the Worker's public key by requesting it from the Authority. + async fn key_worker(mut self) -> Result { + // Request the public key from the Authority. + let resp = self.auth_client.get("/key").await?; + // Deserialize the response to a BigInt. + let bytes = to_bytes(resp.into_body()).await; + let key: BigInt = match from_bytes(bytes.as_ref()) { + Some(res) => res, + None => { + return Err("response error"); + }, + }; + // Submit the public key to the Worker. + self.worker_client.post("/key", key).await?; + // Return self on success. + Ok(self) + } + + /// Add a permission to the system. + pub async fn add_permission( + &mut self, + actions: Vec, + ) -> Result { + // Lock the Mutex. + let _guard = self.guard_acc.lock().await; + // Create a Permission that includes the requested actions. + let mut perm = Permission { + nonce: 0.into(), + actions: actions, + version: 0, + }; + // Submit the permission to the Authority and read back the response + // that includes populated Nonce. + let resp = self.auth_client.post("/permission", perm).await?; + let bytes = to_bytes(resp.into_body()).await; + perm = match from_bytes(bytes.as_ref()) { + Some(res) => res, + None => { + return Err("response error"); + }, + }; + // Submit the finalized Permission to the Worker. + self.worker_client.post("/permission", perm.clone()).await?; + // Return the Permission on success. + Ok(perm) + } + + /// Internal helper to get the witness for a Permission. + /// + /// This code is reused by `update_permission` and `action` so that a + /// current witness can be attached to the request to the Authority. + async fn get_witness( + worker_client: &mut AddrBaseClient, + nonce: Nonce, + ) -> Result, &'static str> { + // Build the request path in the form of "/witness/{nonce}". + let mut path = "/witness/".to_owned(); + path.push_str(&nonce.to_string()); + // Request the path from the Worker and deserialize the response. + let resp = worker_client.get(&path).await?; + let bytes = to_bytes(resp.into_body()).await; + match from_bytes::>(bytes.as_ref()) { + Some(res) => Ok(res), + None => Err("response error"), + } + } + + /// Update a permission. + pub async fn update_permission( + &mut self, + perm: Permission, + actions: Vec + ) -> Result { + // Lock the Mutex. + let _guard = self.guard_acc.lock().await; + // Get the Permission's current Witness. + let witness = Self::get_witness( + &mut self.worker_client, + perm.nonce + ).await?; + // Create Permission with new actions and an incremented version. + let update = Permission { + nonce: perm.nonce, + actions: actions, + version: perm.version + 1, + }; + // Create the UpdateRequest struct containing the Witness as well as + // the old and new Permissions. + let req = UpdateRequest { + perm: perm, + witness: witness, + update: update.clone(), + }; + // Submit the request to the Authority and deserialize the response. + let resp = self.auth_client.put("/permission", req).await?; + let bytes = to_bytes(resp.into_body()).await; + let response: UpdateResponse = match from_bytes(bytes.as_ref()) { + Some(res) => res, + None => { + return Err("response error"); + }, + }; + // Submit the response to the Worker so that it has the most current + // accumulation value. + self.worker_client.put("/permission", response).await?; + // Return the updated Permission on success. + Ok(update) + } + + /// Perform an action. + pub async fn action( + &mut self, + perm: Permission, + action: Action, + ) -> Result<(), &'static str> { + // Lock the Mutex. + let _guard = self.guard_acc.lock().await; + // Get the Permission's current Witness. + let witness = Self::get_witness( + &mut self.worker_client, + perm.nonce + ).await?; + // Create the ActionRequest struct. + let req = ActionRequest { + perm: perm, + witness: witness, + action: action, + }; + // Submit the request. + self.auth_client.post("/action", req).await?; + // Return success. + Ok(()) + } + + /// Start the synchronization task. + /// + /// The synchronization task executes in a continuous loop until a + /// communication error occurs with the Authority or the Worker. + /// The owner of a Synchronizer instance must await the returned future + /// before the instance may be freed safely. + pub fn sync(&mut self) -> JoinHandle> { + // Create an AtomicPtr so that a reference to the instance may be moved + // into the task. + let mut ptr = AtomicPtr::new(self); + tokio::spawn(async move { + // Dereference the pointer to get the refenence. + let sync = unsafe { + ptr.get_mut().as_mut().unwrap() + }; + // Lock the update Mutex to prevent additional sync tasks from + // executing. + let _guard_update = sync.guard_update.lock().await; + // Define the update window. + let dur = Duration::from_millis(UPDATE_WINDOW_MILLIS); + let mut window = interval(dur); + // The first tick completes immediately. Get it out of the way. + window.tick().await; + // Start looping. + loop { + // Wait for the next interval tick. + window.tick().await; + // Create a future for the update task, but only lock the + // Accumulator Mutex while the Authority and Worker states + // are mutated. + { + // Lock the accumulator Mutex. + let _guard_acc = sync.guard_acc.lock().await; + // Tell the Authority to switch over its staging + // accumulation. + sync.auth_client.get("/update").await?; + // Tell the Worker to start updating Witnesses. + sync.worker_client.get("/update") + // Mutex gets released here, even though the Worker update + // result will be awaited for. + }.await?; + // Lock the accumulator Mutex. + let _guard_acc = sync.guard_acc.lock().await; + // Tell the Authority to switch over its updating accumulation. + sync.auth_client.get("/sync").await?; + // Tell the Worker to switch over its permissions map. + sync.worker_client.get("/sync").await?; + } + }) + } +} diff --git a/src/u53.rs b/src/u53.rs new file mode 100644 index 0000000..bd824b2 --- /dev/null +++ b/src/u53.rs @@ -0,0 +1,158 @@ +use serde::{ + Serialize, Deserialize, + ser::Serializer, + de::{self, Deserializer, Unexpected, Visitor}, +}; +use std::hash::Hash; + +/// An unsigned 53-bit integer. +/// +/// This is a minimal implementation that is intended soley for serialization +/// and comparison. In the current landscape, a 53-bit integer is a better +/// choice for a portable, double-worded integer than a 64-bit integer because +/// it is the largest sized integer possible in Javascript without losing +/// precision. +#[allow(non_camel_case_types)] +#[derive(Copy, Clone, Hash)] +pub struct u53(u64); + +impl From for u53 { + fn from(v: u64) -> Self { + u53(v & 0x1fffffffffffffu64) + } +} + +impl From for u53 { + fn from(v: u32) -> Self { + u53(v as u64) + } +} + +impl From for u53 { + fn from(v: u16) -> Self { + u53(v as u64) + } +} + +impl From for u53 { + fn from(v: u8) -> Self { + u53(v as u64) + } +} + +impl From for u53 { + fn from(v: i64) -> Self { + u53((v as u64).into()) + } +} + +impl From for u53 { + fn from(v: i32) -> Self { + u53((v as u32).into()) + } +} + +impl From for u53 { + fn from(v: i16) -> Self { + u53((v as u16).into()) + } +} + +impl From for u53 { + fn from(v: i8) -> Self { + u53((v as u8).into()) + } +} + +impl From for u64 { + fn from(v: u53) -> u64 { + v.0 + } +} + +impl Serialize for u53 { + fn serialize( + &self, + serializer: S + ) -> Result where S: Serializer { + serializer.serialize_u64(self.clone().into()) + } +} + +impl<'de> Deserialize<'de> for u53 { + fn deserialize(deserializer: D) -> Result + where D: Deserializer<'de> { + struct U53Visitor; + impl<'de> Visitor<'de> for U53Visitor { + type Value = u53; + fn visit_u64(self, value: u64) -> Result + where E: de::Error { + if (value & 0xffe0000000000000u64) == 0 { + Ok(value.into()) + } else { + Err(de::Error::invalid_value( + Unexpected::Unsigned(value), + &self + )) + } + } + fn visit_u32(self, value: u32) -> Result + where E: de::Error { + Ok(value.into()) + } + fn visit_u16(self, value: u16) -> Result + where E: de::Error { + Ok(value.into()) + } + fn visit_u8(self, value: u8) -> Result + where E: de::Error { + Ok(value.into()) + } + fn visit_i64(self, value: i64) -> Result + where E: de::Error { + if value >= 0 + && ((value as u64) & 0xffe0000000000000u64) == 0 { + Ok(value.into()) + } else { + Err(de::Error::invalid_value( + Unexpected::Signed(value), + &self + )) + } + } + fn visit_i32(self, value: i32) -> Result + where E: de::Error { + Ok(value.into()) + } + fn visit_i16(self, value: i16) -> Result + where E: de::Error { + Ok(value.into()) + } + fn visit_i8(self, value: i8) -> Result + where E: de::Error { + Ok(value.into()) + } + fn expecting( + &self, + f: &mut std::fmt::Formatter<'_> + ) -> Result<(), std::fmt::Error> { + write!(f, "u53") + } + } + deserializer.deserialize_u64(U53Visitor) + } +} + +impl Eq for u53 {} + +impl PartialEq for u53 { + fn eq(&self, other: &u53) -> bool { + self.0 == other.0 + } +} + +impl std::fmt::Display for u53 { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/src/util.rs b/src/util.rs new file mode 100644 index 0000000..3b1c3c0 --- /dev/null +++ b/src/util.rs @@ -0,0 +1,126 @@ +use futures_util::TryStreamExt; +use hyper::{ + Body, Client, Response, Request, StatusCode, + client::HttpConnector, +}; +use serde::{Serialize, Deserialize}; + +pub async fn to_bytes(body: Body) -> Option> { + let mut stream = body.map_ok(|chunk| -> Vec { + chunk.slice(0..chunk.len()).to_vec() + }); + match stream.try_next().await { + Ok(res) => res, + Err(_) => None, + } +} + +pub fn from_bytes<'a, T: Deserialize<'a>>( + bytes: Option<&'a Vec> +) -> Option { + match bytes { + Some(bytes) => { + match velocypack::from_bytes(bytes) { + Ok(res) => Some(res), + Err(_) => None, + } + } + None => None, + } +} + +pub fn from_json<'a, T: Deserialize<'a>>( + bytes: Option<&'a Vec> +) -> Option { + match bytes { + Some(bytes) => match std::str::from_utf8(&bytes) { + Ok(json) => match serde_json::from_str(json) { + Ok(res) => Some(res), + Err(x) => { + println!("{}", x); + None + }, + }, + Err(_) => None, + } + None => None, + } +} + +pub struct AddrBaseClient { + client: Client, + base: String, +} + +impl AddrBaseClient { + + pub fn new(scheme: &str, addr: &str) -> AddrBaseClient { + let mut base = String::new(); + base.push_str(scheme); + base.push_str(addr); + AddrBaseClient { + client: Client::new(), + base: base, + } + } + + pub async fn get( + &mut self, + path: &str + ) -> Result, &'static str> { + let mut uri = self.base.clone(); + uri.push_str(path); + let req = Request::get(uri).body(Body::empty()).unwrap(); + match self.client.request(req).await { + Ok(resp) => { + match resp.status() { + StatusCode::OK => Ok(resp), + x => Err(x.canonical_reason().unwrap()), + } + }, + _ => Err("request error"), + } + } + + pub async fn post( + &mut self, + path: &str, + body: T, + ) -> Result, &'static str> + where T: Serialize { + let mut uri = self.base.clone(); + uri.push_str(path); + let data = velocypack::to_bytes(&body).unwrap(); + let req = Request::post(uri).body(Body::from(data)).unwrap(); + match self.client.request(req).await { + Ok(resp) => { + match resp.status() { + StatusCode::OK => Ok(resp), + x => Err(x.canonical_reason().unwrap()), + } + }, + _ => Err("request error"), + } + } + + pub async fn put( + &mut self, + path: &str, + body: T, + ) -> Result, &'static str> + where T: Serialize { + let mut uri = self.base.clone(); + uri.push_str(path); + let data = velocypack::to_bytes(&body).unwrap(); + let req = Request::put(uri).body(Body::from(data)).unwrap(); + match self.client.request(req).await { + Ok(resp) => { + match resp.status() { + StatusCode::OK => Ok(resp), + x => Err(x.canonical_reason().unwrap()), + } + }, + _ => Err("request error"), + } + } +} diff --git a/src/worker.rs b/src/worker.rs new file mode 100644 index 0000000..a2485c7 --- /dev/null +++ b/src/worker.rs @@ -0,0 +1,272 @@ +use clacc::{ + Accumulator, Update, Witness, + blake2::Mapper as M, + gmp::BigInt, + velocypack::VpackSerializer, + typenum::U16 as N, +}; +use num_cpus; +use std::collections::HashMap; +use tokio::sync::Mutex; +use crate::permission::{Nonce, Permission}; +use crate::request::UpdateResponse; + +/// Type for a VelocyPack serialized Permission. +type S = VpackSerializer; + +/// Type for a map where Nonces map to Permission-Witness pairs. +type PermissionMap = HashMap)>; + +/// A Worker that absorbs new and update Permissions during a window and can +/// perform a batched Update on a set of Witnesses. +pub struct Worker { + + /// The value of the Accumulator before any updates absorbed during the + /// current window have been applied. + value: BigInt, + + /// The current Accumulator. Although it will only have the public key, + /// it will stay synchronized with the trusted value. + /// + /// The field will start in a None state until the public key from the + /// Authority can be set using `set_key`. + acc: Option>, + + /// The absorbed updates. + update: Update, + + /// The Permission-Witness pairs that will be added during the current + /// update window. + additions: PermissionMap, + + /// The current map of Permission-Witness pairs. + perms: PermissionMap, + + /// The additions that are having their initial witnesses calculated + /// during the update process. + updating_additions: PermissionMap, + + /// The permissions that are having their witnesses updated during the + /// update process. + updating_perms: PermissionMap, + + /// Mutex locked during updates to the Accumulator. + guard_acc: Mutex<()>, + + /// Mutex locked while the Worker is in the process of updating Witnesses. + guard_update: Mutex<()>, +} + +impl Worker { + + /// Create a new Worker using the public key returned from the Authority. + pub fn new() -> Self { + // Allocate Worker. + Worker { + value: 0.into(), + acc: None, + update: Update::new(), + additions: HashMap::new(), + perms: HashMap::new(), + updating_additions: HashMap::new(), + updating_perms: HashMap::new(), + guard_acc: Mutex::new(()), + guard_update: Mutex::new(()), + } + } + + /// Submit the Authority's public key. + /// + /// This allocates the Worker's Accumulator and allows the other methods + /// to be called successfully. If there is already an Accumulator + /// allocated, this method returns an error. + pub async fn set_key( + &mut self, + key: BigInt, + ) -> Result<(), &'static str> { + // Lock the Accumulator Mutex. + let _guard_acc = self.guard_acc.lock().await; + // Error out if there is already an Accumulator allocated. + match self.acc { + Some(_) => Err("already have public key"), + None => { + // Allocate new Accumulator initialized from the Authority's + // public key. + let acc = Accumulator::::with_public_key(key); + self.value = acc.get_value().clone(); + self.acc = Some(acc); + Ok(()) + } + } + } + + /// Internal helper to add a new permission. + /// + /// This code is reused by `add_permission` and `update_permission`. + /// It is assumed that the caller has locked a Mutex so that operations on + /// the Accumulator are thread safe. + fn add_permission_internal( + perm: Permission, + value: &BigInt, + acc: &mut Accumulator, + update: &mut Update, + additions: &mut PermissionMap, + ) { + // Add Permission to Accumulator. + let mut witness = acc.add::(&perm); + // Absorb the addition into the batched Update. + update.add::(&perm, &witness); + // Set the witness value. + witness.set_value(value); + // Insert the pair into the collection of added elements. + additions.insert(perm.nonce, (perm, witness)); + } + + /// Absorb a new Permission into the update window. + pub async fn add_permission( + &mut self, + perm: Permission, + ) -> Result<(), &'static str> { + // Lock the Accumulator Mutex. + let _guard_acc = self.guard_acc.lock().await; + // Error out if there is no Accumulator allocated. + let acc = match &mut self.acc { + Some(acc) => acc, + None => { + return Err("need public key"); + }, + }; + // Use the helper to add the Permission. + Self::add_permission_internal( + perm, + &self.value, + acc, + &mut self.update, + &mut self.additions, + ); + Ok(()) + } + + /// Absorb an updated Permission into the update window. + /// + /// This is simply a deletion of the old version and an addition of the + /// new version. + pub async fn update_permission( + &mut self, + res: UpdateResponse, + ) -> Result<(), &'static str> { + // Lock the Accumulator Mutex. + let _guard_acc = self.guard_acc.lock().await; + // Error out if there is no Accumulator allocated. + let acc = match &mut self.acc { + Some(acc) => acc, + None => { + return Err("need public key"); + }, + }; + // Absorb the deletion into the batched Update. + self.update.del::(&res.req.perm, &res.req.witness); + // Use the helper to add the Permission. + Self::add_permission_internal( + res.req.update, + &self.value, + acc, + &mut self.update, + &mut self.additions + ); + // Synchronize the Worker's accumulation with the Authority's. + // Note that the Worker can't call Accumulator.del because it does not + // have the private key. + acc.set_value(&res.value); + Ok(()) + } + + /// Retrieve the current Witness for a given Nonce. + pub async fn witness( + &self, + nonce: Nonce, + ) -> Result>, &'static str> { + // Lock the Accumulator Mutex to ensure latest Permissions collection + // is available if called during the update process. + let _guard_acc = self.guard_acc.lock().await; + // Error out if there is no Accumulator allocated. + match &self.acc { + Some(_) => {}, + None => { + return Err("need public key"); + }, + } + // Return the Witness stored for the Nonce. + match self.perms.get(&nonce) { + Some(pair) => Ok(Some(pair.1.clone())), + None => Ok(None), + } + } + + /// Perform Witness updates. + /// + /// This will block the current thread during the process, however, other + /// threads may call `add_permission` and `update_permission` to absorb + /// updates for the next window without adversely affecting the current + /// update process. + pub async fn update(&mut self) -> Result<(), &'static str> { + // Lock the update Mutex. + let _guard_update = self.guard_update.lock().await; + // Error out if there is no Accumulator allocated. + match self.acc { + Some(_) => {}, + None => { + return Err("need public key"); + }, + } + // Cache volatile values that are needed for the update process. + let acc; + let update; + { + // Lock the Accumulator Mutex so that other threads cannot call + // `add_permission` or `update_permission` while the instance + // values are copied to the local cache. + let _guard_acc = self.guard_acc.lock().await; + // Store a copy of the current Accumulator. + acc = self.acc.as_ref().unwrap().clone(); + // Store a copy of the updates absorbed during this update window. + update = self.update.clone(); + // Copy the elements added during this update window. + self.updating_additions = self.additions.clone(); + // Reset the batched Update and clear the additions collection + // for subsequent calls to `add_permission` and + // `update_permission`. + self.update = Update::new(); + self.additions.clear(); + // Set the accumulation value for the additions in the next + // update. + self.value = acc.get_value().clone(); + // The Accumulator Mutex gets unlocked here, allowing other + // threads to call `add_permission` or `update_permission`. + } + // Perform the Witness update using all available cores. + update.update_witnesses::( + &acc, + self.updating_perms.values_mut(), + self.updating_additions.values_mut(), + num_cpus::get() + ) + } + + /// Finalize the update process. + pub async fn sync(&mut self) { + // Lock the update Mutex. + let _guard_update = self.guard_update.lock().await; + // Insert the Permissions that were added during this update window + // into the updated Permissions map. + for pair in self.updating_additions.values() { + self.updating_perms.insert(pair.0.nonce, pair.clone()); + } + // Lock the Accumulator Mutex so that other threads may not call + // `add_permission` or `update_permission` while the updated + // Permissions map is copied back into the `perms` field. + let _guard_acc = self.guard_acc.lock().await; + // Copy the updated Permissions map into the `perms` field. + self.perms = self.updating_perms.clone(); + } +}