Compare commits

...

44 Commits

Author SHA1 Message Date
b73fd9e64e feat: add ml kem demo 2025-09-24 23:15:32 +08:00
5ef3b4d3e6 feat: add __security/keyring-demo/ 2025-09-14 17:52:26 +08:00
3dda4e8e5b feat: add pingora-demo 2025-08-17 15:50:54 +08:00
a1024943ff feat: update serde json test 2025-08-03 16:48:22 +08:00
9eba818de9 feat: update serde json 2025-08-03 16:43:05 +08:00
814b5e9442 feat: add clap-test-3 2025-08-03 16:33:52 +08:00
6d7273c6a3 feat: add crypto bcrypt issue test 2025-07-12 21:25:42 +08:00
bd9ea78e53 feat: add __term/tui-markup-demo/ 2025-07-12 18:24:46 +08:00
73d58350c2 feat: udpates 2025-07-12 13:23:01 +08:00
e45d14498c feat: add __wasm/rust-wasm-plugins-examples/ 2025-07-12 13:22:38 +08:00
f2fd57c342 feat: add bc1-btc-address 2025-07-03 00:27:01 +08:00
ed54a7e6ef feat: add orion-demo 2025-06-28 23:22:26 +08:00
7c0865fafd feat: add orion-demo 2025-06-28 23:22:11 +08:00
Hatter Jiang
6e681f0ba1 feat: updates 2025-06-28 09:59:35 +08:00
Hatter Jiang
0dcbb75879 feat: updates 2025-06-28 09:58:50 +08:00
Hatter Jiang
ad25ed2453 feat: add passkey-rs 2025-06-28 09:50:50 +08:00
Hatter Jiang
0491407e58 feat: add passkey-rs 2025-06-28 09:50:38 +08:00
564977aad7 feat: add __alloc 2025-06-27 23:11:48 +08:00
c966ad621d feat: add eth-address 2025-06-25 00:34:06 +08:00
Jiang Hatter
9982409535 feat: reset 2025-06-15 20:10:32 +08:00
Jiang Hatter
9e8cbf557d feat: add tcp-connect-reset 2025-06-15 20:08:54 +08:00
ada9691adc feat: add axum demo 2025-03-16 22:10:36 +08:00
48ad5122f2 add dns-server-tutorial 2025-03-08 21:24:00 +08:00
10672a86b1 feat: rename comfy table 2025-01-06 23:55:15 +08:00
744b16af6c feat: add __args 2025-01-01 09:54:00 +08:00
2ff99a832d feat: update jose-test 2024-11-14 00:23:44 +08:00
4f048b3981 feat: update jose-test 2024-11-14 00:18:55 +08:00
49d91c0dc1 feat: update jose-test 2024-11-14 00:17:29 +08:00
9d9575843c feat: update jose-test 2024-11-14 00:14:25 +08:00
1eb7aeab42 feat: update jose-test 2024-11-14 00:04:36 +08:00
cc4c793835 feat: update jose-test 2024-11-13 23:54:06 +08:00
1b59475ab9 feat: udpate jose-test 2024-11-13 23:10:28 +08:00
0f85300a74 feat: update jose-test 2024-11-13 22:46:58 +08:00
e4f4e70951 feat: rsa jwk 2024-11-13 01:19:06 +08:00
ae8747de70 feat: rsa jwk 2024-11-13 01:14:34 +08:00
2a9d6dfaac feat: jose 2024-11-13 00:15:30 +08:00
9b2c40d662 feat: updates 2024-11-10 22:07:46 +08:00
04a58e9f66 feat: add jost-test 2024-11-10 21:58:37 +08:00
1ae6bb6737 feat: update crypto/aes_ctr_test 2024-08-31 19:39:19 +08:00
8717ca7594 feat: udpate __crypto/aes_ctr_test 2024-08-31 17:35:14 +08:00
09129b38a1 feat: udpate __crypto/aes_ctr_test 2024-08-31 17:34:13 +08:00
7f0e18bbe4 feat: add __crypto/aes_ctr_test/ 2024-08-31 17:11:16 +08:00
22344b6d96 feat: add native db demo 2024-05-04 11:15:28 +08:00
f107f82b7c feat: add concurrent/waitgroup demo 2024-05-01 23:53:06 +08:00
98 changed files with 16214 additions and 97 deletions

View File

@@ -5,7 +5,12 @@ Simple Rust Tests
Project or files: Project or files:
``` ```
. .
├── README_2.md ├── __alloc
│   └── zeroizing-alloc-demo
├── __args
│   ├── argh-test
│   ├── clap-test
│   └── clap-test-2
├── __bin ├── __bin
│   ├── goblin │   ├── goblin
│   └── object-demo │   └── object-demo
@@ -13,28 +18,37 @@ Project or files:
│   └── zstd-demo │   └── zstd-demo
├── __concurrent ├── __concurrent
│   ├── arc-swap │   ├── arc-swap
│   ├── async-fn-resumed-after-completion
│   ├── async_study │   ├── async_study
│   ├── async-fn-resumed-after-completion
│   ├── crossbeam_n_parking_lot │   ├── crossbeam_n_parking_lot
│   ├── glommio │   ├── glommio
│   ├── green-threads │   ├── green-threads
│   ├── qcell │   ├── qcell
│   ── rayon │   ── rayon
│   └── waitgroup-demo
├── __cpu ├── __cpu
│   └── x86 │   └── x86
├── __crypto ├── __crypto
│   ├── aegis-test │   ├── aegis-test
│   ├── aes_ctr_test
│   ├── aes_gcm_crypto │   ├── aes_gcm_crypto
│   ├── asn1-der-test │   ├── asn1-der-test
│   ├── bc1-btc-address
│   ├── btc-address │   ├── btc-address
│   ├── crypto │   ├── crypto
│   ├── crypto2-demo │   ├── crypto2-demo
│   ├── curve25519 │   ├── curve25519
│   ├── efficient_sm2 │   ├── efficient_sm2
│   ├── eth-address
│   ├── highwayhash │   ├── highwayhash
│   ├── hmac_sha1 │   ├── hmac_sha1
│   ├── jose-test
│   ├── jsonwebtoken │   ├── jsonwebtoken
│   ├── liboqs-rust-demo │   ├── liboqs-rust-demo
│   ├── ml-kem-demo
│   ├── okta-bcrypt-issue
│   ├── orion-demo
│   ├── passkey-rs-demo
│   ├── password-hash │   ├── password-hash
│   ├── pkcs8 │   ├── pkcs8
│   ├── pwhash │   ├── pwhash
@@ -56,6 +70,7 @@ Project or files:
│   ├── duckdb-demo │   ├── duckdb-demo
│   ├── gluesql │   ├── gluesql
│   ├── mysqlsvr │   ├── mysqlsvr
│   ├── native_db-demo
│   ├── persy │   ├── persy
│   ├── rocksdb │   ├── rocksdb
│   ├── rusqlite │   ├── rusqlite
@@ -65,7 +80,7 @@ Project or files:
│   └── sqlx │   └── sqlx
├── __diff ├── __diff
│   ├── diffy │   ├── diffy
│   ── prettydiff │   ── prettydiff
├── __enclave ├── __enclave
│   └── virt_enclave │   └── virt_enclave
├── __err ├── __err
@@ -77,9 +92,9 @@ Project or files:
├── __ffi ├── __ffi
│   ├── abi_stable_crates │   ├── abi_stable_crates
│   ├── c │   ├── c
│   ├── c2
│   ├── c_export │   ├── c_export
│   ├── c_layout │   ├── c_layout
│   ├── c2
│   ├── calltoc │   ├── calltoc
│   ├── cpp │   ├── cpp
│   ├── dotalib │   ├── dotalib
@@ -90,7 +105,7 @@ Project or files:
├── __fs ├── __fs
│   ├── crypt4ghfs-rust │   ├── crypt4ghfs-rust
│   ├── fuse │   ├── fuse
│   ── fuser │   ── fuser
├── __gui ├── __gui
│   ├── druid │   ├── druid
│   ├── gtk │   ├── gtk
@@ -147,7 +162,9 @@ Project or files:
│   └── walkdir │   └── walkdir
├── __network ├── __network
│   ├── async-speed-limit │   ├── async-speed-limit
│   ├── axum-demo
│   ├── dingo │   ├── dingo
│   ├── dns-server-tutorial
│   ├── fetch-rs │   ├── fetch-rs
│   ├── fuso-socks5-test │   ├── fuso-socks5-test
│   ├── html-crawl-parse │   ├── html-crawl-parse
@@ -161,12 +178,14 @@ Project or files:
│   ├── nfqueue │   ├── nfqueue
│   ├── ngrok-demo │   ├── ngrok-demo
│   ├── pcap │   ├── pcap
│   ├── pingora-demo
│   ├── quinn │   ├── quinn
│   ├── rust-rawsock-demo
│   ├── rust_tcp │   ├── rust_tcp
│   ├── rust-rawsock-demo
│   ├── s2n_quic │   ├── s2n_quic
│   ├── socket2 │   ├── socket2
│   ├── tcp │   ├── tcp
│   ├── tcp-connect-reset
│   ├── tokio-kcp-demo │   ├── tokio-kcp-demo
│   ├── tuntapmac │   ├── tuntapmac
│   ├── udp_laminar │   ├── udp_laminar
@@ -184,6 +203,7 @@ Project or files:
│   └── tantivy │   └── tantivy
├── __security ├── __security
│   ├── keychain-services │   ├── keychain-services
│   ├── keyring-demo
│   ├── seckey │   ├── seckey
│   ├── secmem-proc │   ├── secmem-proc
│   ├── secrets │   ├── secrets
@@ -207,10 +227,10 @@ Project or files:
│   ├── sshrs │   ├── sshrs
│   └── xshell │   └── xshell
├── __shuttle ├── __shuttle
│   ── hatter-test │   ── hatter-test
├── __std ├── __std
│   ├── async-fn
│   ├── async_await │   ├── async_await
│   ├── async-fn
│   ├── into │   ├── into
│   ├── iter │   ├── iter
│   ├── misc │   ├── misc
@@ -224,7 +244,7 @@ Project or files:
├── __term ├── __term
│   ├── bunt │   ├── bunt
│   ├── colored_msg │   ├── colored_msg
│   ├── confy_table │   ├── comfy_table
│   ├── cursive-demo │   ├── cursive-demo
│   ├── dialoguer-demo │   ├── dialoguer-demo
│   ├── indicatif │   ├── indicatif
@@ -232,7 +252,8 @@ Project or files:
│   ├── rustyline │   ├── rustyline
│   ├── structopt │   ├── structopt
│   ├── tabled │   ├── tabled
│   ── term │   ── term
│   └── tui-markup-demo
├── __time ├── __time
│   ├── chrono │   ├── chrono
│   ├── humantime-demo │   ├── humantime-demo
@@ -240,20 +261,20 @@ Project or files:
├── __translate ├── __translate
│   └── retranslate │   └── retranslate
├── __wasm ├── __wasm
│   ├── connect.ssh
│   ├── deno_rust_wasm_import_functions │   ├── deno_rust_wasm_import_functions
│   ├── deno_rust_wasm_js_sandbox │   ├── deno_rust_wasm_js_sandbox
│   ├── deno_rust_wasm_qr_decode │   ├── deno_rust_wasm_qr_decode
│   ├── extism │   ├── extism
│   ├── js-wasm │   ├── js-wasm
│   ├── rust-wasm-plugins-examples
│   ├── wasi │   ├── wasi
│   ├── wasm │   ├── wasm
│   ├── wasmtime │   ├── wasmtime
│   ├── wasmtime-serde-demo │   ├── wasmtime-serde-demo
│   └── wit-bindgen-sample │   └── wit-bindgen-sample
├── __web ├── __web
│   ├── actix-web
│   ├── actix_rustls │   ├── actix_rustls
│   ├── actix-web
│   ├── alibabacloundfn │   ├── alibabacloundfn
│   ├── hyper_rustls │   ├── hyper_rustls
│   ├── hyperrs │   ├── hyperrs
@@ -267,10 +288,10 @@ Project or files:
│   ├── tide │   ├── tide
│   └── warp │   └── warp
├── build_readme.rs -> scripts/build_readme_rs/src/main.rs ├── build_readme.rs -> scripts/build_readme_rs/src/main.rs
├── README_2.md
├── scripts ├── scripts
│   ── build_readme_rs │   ── build_readme_rs
└── single_file_tests └── single_file_tests
├── 99.htm
├── 99.rs ├── 99.rs
├── chain.rs ├── chain.rs
├── closure.rs ├── closure.rs
@@ -293,6 +314,6 @@ Project or files:
├── vec.rs ├── vec.rs
└── while.rs └── while.rs
262 directories, 40 files 286 directories, 38 files
``` ```

View File

@@ -7,5 +7,3 @@ Projects:
* https://github.com/tafia/hyper-proxy * https://github.com/tafia/hyper-proxy
* https://github.com/rusticata/x509-parser * https://github.com/rusticata/x509-parser

16
__alloc/zeroizing-alloc-demo/Cargo.lock generated Normal file
View File

@@ -0,0 +1,16 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "zeroizing-alloc"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebff5e6b81c1c7dca2d0bd333b2006da48cb37dbcae5a8da888f31fcb3c19934"
[[package]]
name = "zeroizing-alloc-demo"
version = "0.1.0"
dependencies = [
"zeroizing-alloc",
]

View File

@@ -0,0 +1,7 @@
[package]
name = "zeroizing-alloc-demo"
version = "0.1.0"
edition = "2024"
[dependencies]
zeroizing-alloc = "0.1.0"

View File

@@ -0,0 +1,8 @@
use zeroizing_alloc::ZeroAlloc;
#[global_allocator]
static ALLOC: ZeroAlloc<std::alloc::System> = ZeroAlloc(std::alloc::System);
fn main() {
println!("Hello, world!");
}

103
__args/argh-test/Cargo.lock generated Normal file
View File

@@ -0,0 +1,103 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "argh"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34ff18325c8a36b82f992e533ece1ec9f9a9db446bd1c14d4f936bac88fcd240"
dependencies = [
"argh_derive",
"argh_shared",
"rust-fuzzy-search",
]
[[package]]
name = "argh-test"
version = "0.1.0"
dependencies = [
"argh",
]
[[package]]
name = "argh_derive"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb7b2b83a50d329d5d8ccc620f5c7064028828538bdf5646acd60dc1f767803"
dependencies = [
"argh_shared",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "argh_shared"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a464143cc82dedcdc3928737445362466b7674b5db4e2eb8e869846d6d84f4f6"
dependencies = [
"serde",
]
[[package]]
name = "proc-macro2"
version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rust-fuzzy-search"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a157657054ffe556d8858504af8a672a054a6e0bd9e8ee531059100c0fa11bb2"
[[package]]
name = "serde"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "syn"
version = "2.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c786062daee0d6db1132800e623df74274a0a87322d8e183338e01b3d98d058"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"

View File

@@ -0,0 +1,7 @@
[package]
name = "argh-test"
version = "0.1.0"
edition = "2021"
[dependencies]
argh = "0.1.13"

View File

@@ -0,0 +1,22 @@
use argh::FromArgs;
#[derive(Debug, FromArgs)]
/// Reach new heights.
struct GoUp {
/// whether or not to jump
#[argh(switch, short = 'j')]
jump: bool,
/// how high to go
#[argh(option)]
height: usize,
/// an optional nickname for the pilot
#[argh(option)]
pilot_nickname: Option<String>,
}
fn main() {
let up: GoUp = argh::from_env();
println!("{:#?}", up);
}

261
__args/clap-test-2/Cargo.lock generated Normal file
View File

@@ -0,0 +1,261 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "anstream"
version = "0.6.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "301af1932e46185686725e0fad2f8f2aa7da69dd70bf6ecc44d6b703844a3933"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd"
[[package]]
name = "anstyle-parse"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8bdeb6047d8983be085bab0ba1472e6dc604e7041dbf6fcd5e71523014fae9"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "403f75924867bb1033c59fbf0797484329750cfbe3c4325cd33127941fabc882"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "clap"
version = "4.5.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed87a9d530bb41a67537289bafcac159cb3ee28460e0a4571123d2a778a6a882"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap-test-2"
version = "0.1.0"
dependencies = [
"clap",
"clap-verbosity-flag",
]
[[package]]
name = "clap-verbosity-flag"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eeab6a5cdfc795a05538422012f20a5496f050223c91be4e5420bfd13c641fb1"
dependencies = [
"clap",
"log",
]
[[package]]
name = "clap_builder"
version = "4.5.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64f4f3f3c77c94aff3c7e9aac9a2ca1974a5adf392a8bb751e827d6d127ab966"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.5.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef4f52386a59ca4c860f7393bcf8abd8dfd91ecccc0f774635ff68e92eeef491"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675"
[[package]]
name = "colorchoice"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]]
name = "log"
version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
[[package]]
name = "once_cell_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad"
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

View File

@@ -0,0 +1,8 @@
[package]
name = "clap-test-2"
version = "0.1.0"
edition = "2024"
[dependencies]
clap = { version = "4.5.42", features = ["derive", "env"] }
clap-verbosity-flag = "3"

View File

@@ -0,0 +1,158 @@
use clap::Parser;
// https://github.com/fastn-stack/kulfi/blob/main/malai/src/main.rs
fn main() {
let cli = Cli::parse();
println!("{:?}", cli);
}
#[derive(clap::Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct Cli {
#[command(flatten)]
verbose: clap_verbosity_flag::Verbosity,
#[command(subcommand)]
pub command: Option<Command>,
// adding these two because when we run `cargo tauri dev,` it automatically passes these
// arguments. need to figure out why and how to disable that, till then this is a workaround
#[arg(default_value = "true", long, hide = true)]
no_default_features: bool,
#[arg(default_value = "auto", long, hide = true)]
color: String,
}
#[derive(clap::Subcommand, Debug)]
pub enum Command {
// TODO: add this to the docs when we have ACL
// By default it allows any peer to connect to the HTTP(s) service. You can pass --what-to-do
// argument to specify a What To Do service that can be used to add access control."
#[clap(about = "Expose HTTP Service on kulfi, connect using kulfi or browser")]
Http {
port: u16,
#[arg(
long,
default_value = "127.0.0.1",
help = "Host serving the http service."
)]
host: String,
#[arg(
long,
default_value = "kulfi.site",
help = "Use this for the HTTP bridge. To run an HTTP bridge, use `malai http-bridge`",
env = "MALAI_HTTP_BRIDGE"
)]
bridge: String,
#[arg(
long,
help = "Make the exposed service public. Anyone will be able to access."
)]
public: bool,
// #[arg(
// long,
// default_value_t = false,
// help = "Use this if the service is HTTPS"
// )]
// secure: bool,
// #[arg(
// long,
// help = "The What To Do Service that can be used to add access control."
// )]
// this will be the id52 of the identity server that should be consulted
// what_to_do: Option<String>,
},
#[clap(about = "Browse a kulfi site.")]
Browse {
#[arg(help = "The Kulfi URL to browse. Should look like kulfi://<id52>/<path>")]
url: String,
},
#[clap(about = "Expose TCP Service on kulfi.")]
Tcp {
port: u16,
#[arg(
long,
default_value = "127.0.0.1",
help = "Host serving the TCP service."
)]
host: String,
#[arg(
long,
help = "Make the exposed service public. Anyone will be able to access."
)]
public: bool,
},
#[clap(
about = "Run an http server that forwards requests to the given id52 taken from the HOST header"
)]
HttpBridge {
#[arg(
long,
short('t'),
help = "The id52 to which this bridge will forward incoming HTTP request. By default it forwards to every id52."
)]
proxy_target: Option<String>,
#[arg(
long,
short('p'),
help = "The port on which this bridge will listen for incoming HTTP requests. If you pass 0, it will bind to a random port.",
default_value = "0"
)]
port: u16,
},
#[clap(about = "Run a TCP server that forwards incoming requests to the given id52.")]
TcpBridge {
#[arg(help = "The id52 to which this bridge will forward incoming TCP request.")]
proxy_target: String,
#[arg(
help = "The port on which this bridge will listen for incoming TCP requests. If you pass 0, it will bind to a random port.",
default_value = "0"
)]
port: u16,
},
#[clap(about = "Expose a folder to kulfi network")]
Folder {
#[arg(help = "The folder to expose.")]
path: String,
#[arg(
long,
default_value = "kulfi.site",
help = "Use this for the HTTP bridge. To run an HTTP bridge, use `malai http-bridge`",
env = "MALAI_HTTP_BRIDGE"
)]
bridge: String,
#[arg(long, help = "Make the folder public. Anyone will be able to access.")]
public: bool,
},
#[clap(about = "Run all the services")]
Run {
#[arg(long, help = "Malai Home", env = "MALAI_HOME")]
home: Option<String>,
},
#[clap(about = "Run an iroh remote server that handles requests from http-proxy.")]
HttpProxyRemote {
#[arg(long, help = "Make the proxy public. Anyone will be able to access.")]
public: bool,
},
#[clap(about = "Run a http proxy server that forwards incoming requests to http-proxy-remote.")]
HttpProxy {
#[arg(help = "The id52 of remote to which this http proxy will forward request to.")]
remote: String,
#[arg(
help = "The port on which this proxy will listen for incoming TCP requests. If you pass 0, it will bind to a random port.",
default_value = "0"
)]
port: u16,
},
#[clap(about = "Generate a new identity.")]
Keygen {
#[arg(
long,
short,
num_args=0..=1,
//default_missing_value=kulfi_utils::SECRET_KEY_FILE,
help = "The file where the private key of the identity will be stored. If not provided, the private key will be printed to stdout."
)]
file: Option<String>,
},
}

237
__args/clap-test/Cargo.lock generated Normal file
View File

@@ -0,0 +1,237 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "anstream"
version = "0.6.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9"
[[package]]
name = "anstyle-parse"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125"
dependencies = [
"anstyle",
"windows-sys",
]
[[package]]
name = "clap"
version = "4.5.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap-test"
version = "0.1.0"
dependencies = [
"clap",
]
[[package]]
name = "clap_builder"
version = "4.5.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6"
[[package]]
name = "colorchoice"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]]
name = "proc-macro2"
version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c786062daee0d6db1132800e623df74274a0a87322d8e183338e01b3d98d058"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

View File

@@ -0,0 +1,7 @@
[package]
name = "clap-test"
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "4.5.23", features = ["derive"] }

View File

@@ -0,0 +1,165 @@
use std::ffi::OsStr;
use std::ffi::OsString;
use std::path::PathBuf;
use clap::{Args, Parser, Subcommand, ValueEnum};
/// A fictional versioning CLI
#[derive(Debug, Parser)] // requires `derive` feature
#[command(name = "git")]
#[command(about = "A fictional versioning CLI", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Debug, Subcommand)]
enum Commands {
/// Clones repos
#[command(arg_required_else_help = true)]
Clone {
/// The remote to clone
remote: String,
},
/// Compare two commits
Diff {
#[arg(value_name = "COMMIT")]
base: Option<OsString>,
#[arg(value_name = "COMMIT")]
head: Option<OsString>,
#[arg(last = true)]
path: Option<OsString>,
#[arg(
long,
require_equals = true,
value_name = "WHEN",
num_args = 0..=1,
default_value_t = ColorWhen::Auto,
default_missing_value = "always",
value_enum
)]
color: ColorWhen,
},
/// pushes things
#[command(arg_required_else_help = true)]
Push {
/// The remote to target
remote: String,
},
/// adds things
#[command(arg_required_else_help = true)]
Add {
/// Stuff to add
#[arg(required = true)]
path: Vec<PathBuf>,
},
Stash(StashArgs),
#[command(external_subcommand)]
External(Vec<OsString>),
}
#[derive(ValueEnum, Copy, Clone, Debug, PartialEq, Eq)]
enum ColorWhen {
Always,
Auto,
Never,
}
impl std::fmt::Display for ColorWhen {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_possible_value()
.expect("no values are skipped")
.get_name()
.fmt(f)
}
}
#[derive(Debug, Args)]
#[command(args_conflicts_with_subcommands = true)]
#[command(flatten_help = true)]
struct StashArgs {
#[command(subcommand)]
command: Option<StashCommands>,
#[command(flatten)]
push: StashPushArgs,
}
#[derive(Debug, Subcommand)]
enum StashCommands {
Push(StashPushArgs),
Pop { stash: Option<String> },
Apply { stash: Option<String> },
}
#[derive(Debug, Args)]
struct StashPushArgs {
#[arg(short, long)]
message: Option<String>,
}
fn main() {
let args = Cli::parse();
match args.command {
Commands::Clone { remote } => {
println!("Cloning {remote}");
}
Commands::Diff {
mut base,
mut head,
mut path,
color,
} => {
if path.is_none() {
path = head;
head = None;
if path.is_none() {
path = base;
base = None;
}
}
let base = base
.as_deref()
.map(|s| s.to_str().unwrap())
.unwrap_or("stage");
let head = head
.as_deref()
.map(|s| s.to_str().unwrap())
.unwrap_or("worktree");
let path = path.as_deref().unwrap_or_else(|| OsStr::new(""));
println!(
"Diffing {}..{} {} (color={})",
base,
head,
path.to_string_lossy(),
color
);
}
Commands::Push { remote } => {
println!("Pushing to {remote}");
}
Commands::Add { path } => {
println!("Adding {path:?}");
}
Commands::Stash(stash) => {
let stash_cmd = stash.command.unwrap_or(StashCommands::Push(stash.push));
match stash_cmd {
StashCommands::Push(push) => {
println!("Pushing {push:?}");
}
StashCommands::Pop { stash } => {
println!("Popping {stash:?}");
}
StashCommands::Apply { stash } => {
println!("Applying {stash:?}");
}
}
}
Commands::External(args) => {
println!("Calling out to {:?} with {:?}", &args[0], &args[1..]);
}
}
// Continued program logic goes here...
}

444
__concurrent/waitgroup-demo/Cargo.lock generated Normal file
View File

@@ -0,0 +1,444 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "addr2line"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb"
dependencies = [
"gimli",
]
[[package]]
name = "adler"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "atomic-waker"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "autocfg"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80"
[[package]]
name = "backtrace"
version = "0.3.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d"
dependencies = [
"addr2line",
"cc",
"cfg-if",
"libc",
"miniz_oxide",
"object",
"rustc-demangle",
]
[[package]]
name = "bitflags"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
[[package]]
name = "bytes"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cc"
version = "1.0.96"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "065a29261d53ba54260972629f9ca6bffa69bac13cd1fed61420f7fa68b9f8bd"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "gimli"
version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
[[package]]
name = "hermit-abi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
[[package]]
name = "libc"
version = "0.2.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346"
[[package]]
name = "lock_api"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "memchr"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
[[package]]
name = "miniz_oxide"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7"
dependencies = [
"adler",
]
[[package]]
name = "mio"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"
dependencies = [
"libc",
"wasi",
"windows-sys 0.48.0",
]
[[package]]
name = "num_cpus"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43"
dependencies = [
"hermit-abi",
"libc",
]
[[package]]
name = "object"
version = "0.32.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441"
dependencies = [
"memchr",
]
[[package]]
name = "parking_lot"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e4af0ca4f6caed20e900d564c242b8e5d4903fdacf31d3daf527b66fe6f42fb"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-targets 0.52.5",
]
[[package]]
name = "pin-project-lite"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02"
[[package]]
name = "proc-macro2"
version = "1.0.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e"
dependencies = [
"bitflags",
]
[[package]]
name = "rustc-demangle"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "signal-hook-registry"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
dependencies = [
"libc",
]
[[package]]
name = "smallvec"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
name = "socket2"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c"
dependencies = [
"libc",
"windows-sys 0.52.0",
]
[[package]]
name = "syn"
version = "2.0.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tokio"
version = "1.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787"
dependencies = [
"backtrace",
"bytes",
"libc",
"mio",
"num_cpus",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys 0.48.0",
]
[[package]]
name = "tokio-macros"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "waitgroup"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1f50000a783467e6c0200f9d10642f4bc424e39efc1b770203e88b488f79292"
dependencies = [
"atomic-waker",
]
[[package]]
name = "waitgroup-demo"
version = "0.1.0"
dependencies = [
"tokio",
"waitgroup",
]
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets 0.48.5",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.5",
]
[[package]]
name = "windows-targets"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm 0.48.5",
"windows_aarch64_msvc 0.48.5",
"windows_i686_gnu 0.48.5",
"windows_i686_msvc 0.48.5",
"windows_x86_64_gnu 0.48.5",
"windows_x86_64_gnullvm 0.48.5",
"windows_x86_64_msvc 0.48.5",
]
[[package]]
name = "windows-targets"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
dependencies = [
"windows_aarch64_gnullvm 0.52.5",
"windows_aarch64_msvc 0.52.5",
"windows_i686_gnu 0.52.5",
"windows_i686_gnullvm",
"windows_i686_msvc 0.52.5",
"windows_x86_64_gnu 0.52.5",
"windows_x86_64_gnullvm 0.52.5",
"windows_x86_64_msvc 0.52.5",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"

View File

@@ -0,0 +1,10 @@
[package]
name = "waitgroup-demo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { version = "1.37.0", features = ["full"] }
waitgroup = "0.1.2"

View File

@@ -0,0 +1,26 @@
use std::time::Duration;
use tokio::task::yield_now;
use tokio::time;
use tokio::time::Instant;
use waitgroup::WaitGroup;
#[tokio::main]
async fn main() {
let wg = WaitGroup::new();
for i in 80..100 {
let w = wg.worker();
tokio::spawn(async move {
println!("Start work #{}", i);
time::sleep(Duration::from_millis(i * 100)).await;
println!("Finish work #{}", i);
drop(w);
});
yield_now().await;
}
let instant = Instant::now();
println!("Start waiting...");
wg.wait().await;
println!("Finish wait, elapsed: {}ms", instant.elapsed().as_millis());
}

100
__crypto/aes_ctr_test/Cargo.lock generated Normal file
View File

@@ -0,0 +1,100 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aes"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
]
[[package]]
name = "aes_ctr_test"
version = "0.1.0"
dependencies = [
"aes",
"hex",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "cpufeatures"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51e852e6dc9a5bed1fae92dd2375037bf2b768725bf3be87811edee3249d09ad"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "inout"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5"
dependencies = [
"generic-array",
]
[[package]]
name = "libc"
version = "0.2.158"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439"
[[package]]
name = "typenum"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"

View File

@@ -0,0 +1,8 @@
[package]
name = "aes_ctr_test"
version = "0.1.0"
edition = "2021"
[dependencies]
aes = "0.8.4"
hex = "0.4.3"

View File

@@ -0,0 +1,42 @@
Test Java codes:
```java
public class AesCtrTest {
public static void main(String[] args) throws Exception {
final byte[] key = new byte[]{
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
final byte[] iv = new byte[]{
1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0
};
final SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
final Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
System.out.println(Bytes.from(cipher.doFinal("hello world".getBytes())).asHex());
System.out.println(Bytes.from(cipher.doFinal(
"hello world.hello world.hello world.hello world.hello world.hello world.".getBytes())).asHex());
}
}
```
Outputs:
```
84ad8d80732490c061177a
84ad8d80732490c061177a58bd26d032d6fcff2e66f9afe3cf95717485d3a4485d4a2a7bd835df3d0756b8192e3bf5a287ad8dd81942c43bc812c82d666ebbb34df4e2a5069467d9
```
<br>
Java `nonce` counter:
`com.sun.crypto.provider.CounterMode`
```java
private static void increment(byte[] nonce) {
for(int index = nonce.length - 1; index >= 0 && ++nonce[index] == 0; --index) {
}
}
```

View File

@@ -0,0 +1,109 @@
use aes::cipher::generic_array::GenericArray;
use aes::cipher::{Block, BlockEncryptMut, KeyInit};
use aes::Aes128;
fn main() {
let key = [0_u8; 16];
let iv = [0_u8; 16];
let plaintext = b"hello world";
let ciphertext = encrypt_ctr(&key, &iv, plaintext);
assert_eq!("0e8c27b880aa5b54fa209e", hex::encode(&ciphertext));
let plaintext = b"hello world.hello world.hello world.hello world.hello world.hello world.";
let ciphertext = encrypt_ctr(&key, &iv, plaintext);
assert_eq!("0e8c27b880aa5b54fa209e77a251474237c28ba18812544f5e1a713bcbc7323571e4bee008d3cf\
fe9c08b5d603de9a569ff0c6c7266b2e4c8591edd1fceead8c4f22664e3c1ff0f4", hex::encode(&ciphertext));
let key = [1_u8; 16];
let mut iv = [0_u8; 16];
for i in 0..8 {
iv[i] = i as u8 + 1;
}
let plaintext = b"hello world.hello world.hello world.hello world.hello world.hello world.";
let ciphertext = encrypt_ctr(&key, &iv, plaintext);
assert_eq!("84ad8d80732490c061177a58bd26d032d6fcff2e66f9afe3cf95717485d3a4485d4a2a7bd835df\
3d0756b8192e3bf5a287ad8dd81942c43bc812c82d666ebbb34df4e2a5069467d9", hex::encode(&ciphertext));
let key = [1_u8; 16];
let iv = [1, 2, 3, 4, 5, 6, 7, 0, 1, 1, 2, 2, 3, 3, 4, 4];
let plaintext = b"hello world.hello world.hello world.hello world.hello world.hello world.";
let ciphertext = encrypt_ctr(&key, &iv, plaintext);
assert_eq!("d373d6b3491c7b8940996f9efefc98d0f564d066a557cf0aa29935a638f99d077a85338e574ee6\
7f69da41b8a87569c324b4d421f1350e11d6be30721605b9dd6401bc3780da3452", hex::encode(&ciphertext));
let key = [1_u8; 16];
let iv = [1, 2, 3, 4, 5, 6, 7, 0, 1, 1, 2, 2, 3, 3, 4, 4];
let plaintext = b"hello world.hello world.hello world.hello world.hello world.h\
ello world.hello world.hello world.hello world.hello world.hello world.hello world.hello w\
orld.hello world.hello world.hello world.hello world.hello world.hello world.hello world.h\
ello world.hello world.hello world.hello world.hello world.hello world.hello world.hello w\
orld.hello world.hello world.hello world.hello world.hello world.hello world.hello world.h\
ello world.hello world.hello world.hello world.hello world.hello world.hello world.hello w\
orld.hello world.hello world.hello world.hello world.hello world.hello world.hello world.h\
ello world.hello world.hello world.hello world.hello world.hello world.hello world.hello w\
orld.hello world.hello world.hello world.hello world.hello world.hello world.hello world.h\
ello world.hello world.hello world.hello world.hello world.hello world.hello world.hello w\
orld.hello world.hello world.hello world.hello world.hello world.hello world.hello world.h\
ello world.hello world.hello world.hello world.";
let ciphertext = encrypt_ctr(&key, &iv, plaintext);
assert_eq!("d373d6b3491c7b8940996f9efefc98d0f564d066a557cf0aa29935a638f99d077a85338e574ee6\
7f69da41b8a87569c324b4d421f1350e11d6be30721605b9dd6401bc3780da3452033164403472b0ea84a7894b\
500100959ccc2cfbe2b6792691f1a1b047755c1961a730c7bcd941ab50b4ece7501d624d5af457875370dbc7e6\
0e73fd6ab10b5033fb3b3e2caed7489cc02bf174a3e7f04bd1e5c81c811314689b2bb7f6f0f0333d9b3bf637ff\
7ac34b32bc4905638204dbd97d4cefd1a823b5d49364c72d987807991eb703e47d56631f9f1a62c9f691bd3641\
509884144fc6e1b63e8177c8e1247ccc0769cb59cd973869f2ac3dd6cb90534ee42f69995e4af48de870936d21\
cf1b4ccd52e4bd0eafaff46dd6f34c91072ffd61f73050580b790deba9dc30d9557c4142a0dfa52b70e050a563\
abd69e87150da9325751a58bb3e162ea3a69347684e50710ea2bd25f6c285903d7b200a56a7eb042639410da17\
471c93e2b26b13091cc22ec81c3912a7121a1337a560d9733d904b6c6752993b2943861d3b770693281d3519fb\
69158df2353913aebe1e6c16787b8d2ff363c1c31bb8b491cec0214bd3ef61357569c8ecf9487087e22eca48b2\
d1c2c718ad7d3984eb7d0ca27b96653d90847ed138b581f8a01c0bea33c435e7f124f4009de059c46c006431fa\
5cf41ad9f16e6457389f928216ebd4efd048840a4dbc80da170c666a5293209866e9371f47005a12d6dc76f7fd\
57fc5b265cc38f4aef6e5496836d1c4c6d96b2c807997b3f61fd45f0acf505f3512ea04a0ad89cc35b344bdc3f\
2126b24bee40406ff00a733555316b8ccb57d661326d6b2d48a7a7fe33fbec23d69890b9368f6321d60b231cf2\
5680bcf7e8f43e443c19150b72394b5a9617fb8cc9666d43968fecdb56c22db6421ffbe3351fe479d9e7841288\
15fbeb7f1b5f9dc1f8b3d772741f7ef9884b5ca81d972d8537ea4c12cbf29c7e362ccd14ed83781db312da5d83\
8e11b20b050b6be472d8133f8f6525649dc9b967d40f430feb4cb3408a623a12658959f8cd8a115d8f63dd6e8b\
b8449937620b1cf783a0761fcbd4f48dcb572c1463a7c756bf9dd77d45f92cfe9a04dfb4d007a448d9b1a8c936\
9bcd35db598e7cdec566d075ff4c8d445e94ef49c0d0a78bb45921bf4c6e6b750a4d0f3310fc9a767a368ced10\
293987bf88026c69dcd805aea561d9b207c2710e6e90658ec5e0f8560449889ba8af852ea36b272aebb73ef59e\
74d1c0fe963ecbf1049743263681f5733cdf3b0b89b52667f63f65e4e7327ca45a2c1bd385f7c5fbf74b82e4f8\
0425c237813f2d39c4d7a06b49eec49b26dd234323747cf41eb4c2a7647b8548dcd72d59a4f0da2b1120759cfc\
dae5df80c55a9015fc48f985bda3d416f7301d72a4348953", hex::encode(&ciphertext));
}
fn encrypt_ctr(key: &[u8; 16], iv: &[u8; 16], plaintext: &[u8]) -> Vec<u8> {
let mut aes128 = Aes128::new_from_slice(key).unwrap();
let plaintext_len = plaintext.len();
let blocks_count = (plaintext_len / 16) + if plaintext_len % 16 == 0 { 0 } else { 1 };
let iv_u128 = u128::from_be_bytes(iv.clone());
let mut cipher_text = vec![0_u8; plaintext_len];
for i in 0..blocks_count {
let enc_iv_u128 = iv_u128 + i as u128;
let mut block: Block<Aes128> = GenericArray::from(enc_iv_u128.to_be_bytes()).clone();
aes128.encrypt_block_mut(&mut block);
let block_slice = block.as_slice();
for j in 0..block_slice.len() {
let oi = i * 16 + j;
if oi < plaintext_len {
cipher_text[oi] = block_slice[j] ^ plaintext[oi];
}
}
}
cipher_text
}
#[test]
fn test_aes() {
let mut aes128 = Aes128::new_from_slice(
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
).unwrap();
let mut a: Block<Aes128> = GenericArray::from_slice(&[0_u8; 16]).clone();
aes128.encrypt_block_mut(&mut a);
println!("{}", hex::encode(a.as_slice()));
assert_eq!("66e94bd4ef8a2c3b884cfa59ca342b2e", hex::encode(a.as_slice()));
}

284
__crypto/bc1-btc-address/Cargo.lock generated Normal file
View File

@@ -0,0 +1,284 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]]
name = "base58ck"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c8d66485a3a2ea485c1913c4572ce0256067a5377ac8c75c4960e1cda98605f"
dependencies = [
"bitcoin-internals",
"bitcoin_hashes",
]
[[package]]
name = "bc1-btc-address"
version = "0.1.0"
dependencies = [
"bitcoin",
"hex",
"rand",
]
[[package]]
name = "bech32"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d965446196e3b7decd44aa7ee49e31d630118f90ef12f97900f262eb915c951d"
[[package]]
name = "bitcoin"
version = "0.32.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8929a18b8e33ea6b3c09297b687baaa71fb1b97353243a3f1029fad5c59c5b"
dependencies = [
"base58ck",
"bech32",
"bitcoin-internals",
"bitcoin-io",
"bitcoin-units",
"bitcoin_hashes",
"hex-conservative",
"hex_lit",
"secp256k1",
]
[[package]]
name = "bitcoin-internals"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30bdbe14aa07b06e6cfeffc529a1f099e5fbe249524f8125358604df99a4bed2"
[[package]]
name = "bitcoin-io"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b47c4ab7a93edb0c7198c5535ed9b52b63095f4e9b45279c6736cec4b856baf"
[[package]]
name = "bitcoin-units"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5285c8bcaa25876d07f37e3d30c303f2609179716e11d688f51e8f1fe70063e2"
dependencies = [
"bitcoin-internals",
]
[[package]]
name = "bitcoin_hashes"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb18c03d0db0247e147a21a6faafd5a7eb851c743db062de72018b6b7e8e4d16"
dependencies = [
"bitcoin-io",
"hex-conservative",
]
[[package]]
name = "bitflags"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
[[package]]
name = "cc"
version = "1.2.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d487aa071b5f64da6f19a3e848e3578944b726ee5a4854b82172f02aa876bfdc"
dependencies = [
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
[[package]]
name = "getrandom"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"wasi",
]
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hex-conservative"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5313b072ce3c597065a808dbf612c4c8e8590bdbf8b579508bf7a762c5eae6cd"
dependencies = [
"arrayvec",
]
[[package]]
name = "hex_lit"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3011d1213f159867b13cfd6ac92d2cd5f1345762c63be3554e84092d85a50bbd"
[[package]]
name = "libc"
version = "0.2.174"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "rand"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
dependencies = [
"getrandom",
]
[[package]]
name = "secp256k1"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113"
dependencies = [
"bitcoin_hashes",
"secp256k1-sys",
]
[[package]]
name = "secp256k1-sys"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9"
dependencies = [
"cc",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "syn"
version = "2.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "wasi"
version = "0.14.2+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3"
dependencies = [
"wit-bindgen-rt",
]
[[package]]
name = "wit-bindgen-rt"
version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
dependencies = [
"bitflags",
]
[[package]]
name = "zerocopy"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181"
dependencies = [
"proc-macro2",
"quote",
"syn",
]

View File

@@ -0,0 +1,9 @@
[package]
name = "bc1-btc-address"
version = "0.1.0"
edition = "2024"
[dependencies]
bitcoin = "0.32.6"
hex = "0.4.3"
rand = "0.9.1"

View File

@@ -0,0 +1,29 @@
use bitcoin::key::Secp256k1;
use bitcoin::{Address, CompressedPublicKey, Network, PrivateKey};
use rand::RngCore;
// generate btc address:
// https://coinb.in/#newSegWit
fn main() {
let secp = Secp256k1::new();
let mut sk_bytes = [0u8; 32];
rand::rng().fill_bytes(&mut sk_bytes);
let secret_key = PrivateKey::from_slice(&sk_bytes, Network::Bitcoin).unwrap();
// let secret_key = PrivateKey::from_wif("L2HajtedHgDT16o3Er8L8tyRrPNbXkeBK69vhGi7K9eK4Yg3dJuj").unwrap();
let public_key = secret_key.public_key(&secp);
let compress_public_key = CompressedPublicKey::try_from(public_key).unwrap();
// 构造 P2WPKH 地址 (bc1 开头)
let address = Address::p2wpkh(&compress_public_key, Network::Bitcoin);
let address = address.to_string();
println!("Private Key (WIF): {}", secret_key.to_wif());
println!("Public Key: {}", public_key);
println!(
"Public Key: {}",
hex::encode(&public_key.inner.serialize_uncompressed())
);
println!("SegWit Address (bc1): {}", address);
}

317
__crypto/eth-address/Cargo.lock generated Normal file
View File

@@ -0,0 +1,317 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]]
name = "bitcoin-io"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b47c4ab7a93edb0c7198c5535ed9b52b63095f4e9b45279c6736cec4b856baf"
[[package]]
name = "bitcoin_hashes"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb18c03d0db0247e147a21a6faafd5a7eb851c743db062de72018b6b7e8e4d16"
dependencies = [
"bitcoin-io",
"hex-conservative",
]
[[package]]
name = "bitflags"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cc"
version = "1.2.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d487aa071b5f64da6f19a3e848e3578944b726ee5a4854b82172f02aa876bfdc"
dependencies = [
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
[[package]]
name = "crunchy"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929"
[[package]]
name = "eth-address"
version = "0.1.0"
dependencies = [
"hex",
"keccak-hash",
"num_cpus",
"rand",
"secp256k1",
]
[[package]]
name = "fixed-hash"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534"
dependencies = [
"static_assertions",
]
[[package]]
name = "getrandom"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"wasi",
]
[[package]]
name = "hermit-abi"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hex-conservative"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5313b072ce3c597065a808dbf612c4c8e8590bdbf8b579508bf7a762c5eae6cd"
dependencies = [
"arrayvec",
]
[[package]]
name = "keccak-hash"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e1b8590eb6148af2ea2d75f38e7d29f5ca970d5a4df456b3ef19b8b415d0264"
dependencies = [
"primitive-types",
"tiny-keccak",
]
[[package]]
name = "libc"
version = "0.2.174"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
[[package]]
name = "num_cpus"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
dependencies = [
"hermit-abi",
"libc",
]
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "primitive-types"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d15600a7d856470b7d278b3fe0e311fe28c2526348549f8ef2ff7db3299c87f5"
dependencies = [
"fixed-hash",
"uint",
]
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "rand"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
dependencies = [
"getrandom",
]
[[package]]
name = "secp256k1"
version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c3c81b43dc2d8877c216a3fccf76677ee1ebccd429566d3e67447290d0c42b2"
dependencies = [
"bitcoin_hashes",
"rand",
"secp256k1-sys",
]
[[package]]
name = "secp256k1-sys"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcb913707158fadaf0d8702c2db0e857de66eb003ccfdda5924b5f5ac98efb38"
dependencies = [
"cc",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "syn"
version = "2.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tiny-keccak"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
dependencies = [
"crunchy",
]
[[package]]
name = "uint"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "909988d098b2f738727b161a106cfc7cab00c539c2687a8836f8e565976fb53e"
dependencies = [
"byteorder",
"crunchy",
"hex",
"static_assertions",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "wasi"
version = "0.14.2+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3"
dependencies = [
"wit-bindgen-rt",
]
[[package]]
name = "wit-bindgen-rt"
version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
dependencies = [
"bitflags",
]
[[package]]
name = "zerocopy"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181"
dependencies = [
"proc-macro2",
"quote",
"syn",
]

View File

@@ -0,0 +1,11 @@
[package]
name = "eth-address"
version = "0.1.0"
edition = "2024"
[dependencies]
hex = "0.4.3"
keccak-hash = "0.11.0"
num_cpus = "1.17.0"
rand = "0.9.1"
secp256k1 = { version = "0.31.1", features = ["rand"] }

View File

@@ -0,0 +1,157 @@
use keccak_hash::keccak_256;
use secp256k1::{PublicKey, Secp256k1};
use std::{
sync::{Arc, Mutex},
thread,
};
fn main() {
let args = std::env::args();
if args.len() <= 1 {
println!("[ERROR] Need at least one argument, e.g. 0xff 0xffff ...");
return;
}
let continue_on_found = std::env::var("CONTINUE_ON_FOUND")
.map(|c| c.to_lowercase())
.map(|c| c == "1" || c == "true" || c == "yes" || c == "on")
.unwrap_or_else(|_| false);
let prefixes: Vec<String> = args.skip(1).collect();
println!("Prefixes: {:?}", prefixes);
if continue_on_found {
println!("CONTINUE_ON_FOUND is ON");
} else {
println!("CONTINUE_ON_FOUND is OFF");
}
let loop_count = std::env::var("LOOP_COUNT")
.map(|c| c.parse::<u64>())
.unwrap_or_else(|_| Ok(10_000_000_u64))
.unwrap_or_else(|_| 10_000_000_u64);
println!("LOOP_COUNT={}", loop_count);
let num_of_vcpus = num_cpus::get();
let num_of_phycpus = num_cpus::get_physical();
println!(
"You have {} vCPUs, from {} phyCPUs",
num_of_vcpus, num_of_phycpus
);
let concurrent_count = std::env::var("CONCURRENT_COUNT")
.map(|c| c.parse::<u64>())
.unwrap_or_else(|_| Ok(num_of_phycpus as u64))
.unwrap_or_else(|_| 1_u64);
println!("CONCURRENT_COUNT={}", concurrent_count);
let stop_flag = Arc::new(Mutex::new(false));
let mut handles = vec![];
for ind in 0..concurrent_count {
println!("- Running task {} of {}", ind, concurrent_count);
let the_stop_flag = Arc::clone(&stop_flag);
let prefixes = prefixes.clone();
let child = thread::spawn(move || {
run_one_task(prefixes, continue_on_found, loop_count, ind, the_stop_flag);
});
handles.push(child);
}
while let Some(h) = handles.pop() {
h.join().unwrap();
}
println!("Finished!");
}
fn run_one_task(
prefixes: Vec<String>,
continue_on_found: bool,
loop_count: u64,
ind: u64,
the_stop_flag: Arc<Mutex<bool>>,
) {
let secp = Secp256k1::new();
for i in 0..loop_count {
let (secret_key, public_key) = secp.generate_keypair(&mut rand::rng());
let s = make_eth_address(&public_key);
if i % 1_000 == 0 {
if *the_stop_flag.lock().unwrap() {
return;
}
if i > 0 && i % 100_000 == 0 {
println!("> {} - {}", ind, i);
}
}
let lower_s = s.to_ascii_lowercase();
if prefixes.iter().any(|p| lower_s.starts_with(p)) {
println!(">> {}\n{}", s, hex::encode(secret_key.as_ref()));
if !continue_on_found {
*the_stop_flag.lock().unwrap() = true;
break;
}
}
}
}
// reference: https://eips.ethereum.org/EIPS/eip-55
fn make_eth_address(public_key: &PublicKey) -> String {
let public_key_bytes = public_key.serialize_uncompressed().to_vec();
let mut output = [0_u8; 32];
keccak_256(&public_key_bytes[1..], &mut output);
let addr_without_prefix_0x = hex::encode(&output[32 - 20..]);
let mut addr_keccak_256_output = [0_u8; 32];
keccak_256(
addr_without_prefix_0x.as_bytes(),
&mut addr_keccak_256_output,
);
let addr_keccak_256_hex = hex::encode(&addr_keccak_256_output);
let mut addr = String::with_capacity(42);
addr.push_str("0x");
let addr_keccak_256_chars = addr_keccak_256_hex.chars().collect::<Vec<_>>();
let addr_chars = addr_without_prefix_0x.chars().collect::<Vec<_>>();
for i in 0..addr_chars.len() {
if addr_keccak_256_chars[i] >= '8' {
addr.push(addr_chars[i].to_ascii_uppercase());
} else {
addr.push(addr_chars[i])
}
}
addr
}
#[test]
fn test_make_eth_address() {
use secp256k1::{SecretKey};
for (private_key, eth_address) in [
(
"961fc1985ceca1e23b169103e041ecfa642ff8690a6ecc59d91f2dba648ab02b",
"0x0005119dEE1fD8763fE6ADBbc801484a3728F0db",
),
(
"2fa0db47c5939d7d4831d05dcdb329f6e7f7d5ca2c7247a666729aa513ea26bf",
"0x23aEf078e0997434Eb47E6d0B3C7770010473456",
),
(
"e6a8f02f9d308eca44b8437d6dc1d08101449ecef5851dfe5093bcf0bc21fa5b",
"0xef87E9712c412ef7B90804EbaB763FAe24E10123",
),
(
"3d541861865959e1e1c303d5c2a90084192415b61ead3fdb778047278011170b",
"0x1451449D05A3C232a543A995C2A38c07095f6666",
),
] {
let temp_key = hex::decode(private_key).unwrap();
let mut key_32_bytes = [0_u8; 32];
for i in 0..32 {
key_32_bytes[i] = temp_key[i];
}
let secp = Secp256k1::new();
let secret_key =
SecretKey::from_byte_array(key_32_bytes).expect("32 bytes, within curve order");
let public_key = PublicKey::from_secret_key(&secp, &secret_key);
assert_eq!(eth_address, make_eth_address(&public_key));
}
}

1357
__crypto/jose-test/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,20 @@
[package]
name = "jose-test"
version = "0.1.0"
edition = "2021"
[dependencies]
aes-gcm-stream = "0.2.3"
aes-kw = { version = "0.2.1", features = ["alloc"] }
base64 = "0.22.1"
biscuit = "0.7.0"
#jose-jwe = "0.0.0"
jose-jwk = { version = "0.1.2", features = ["rsa"] }
josekit = "0.10.0"
rand = { version = "0.8.5", features = [] }
rsa = "0.9.6"
rust_util = "0.6.47"
serde = "1.0.214"
serde_json = "1.0.132"
sha1 = "0.10.6"
sha2 = "0.10.8"

View File

@@ -0,0 +1,241 @@
use aes_gcm_stream::{Aes256GcmStreamDecryptor, Aes256GcmStreamEncryptor};
use aes_kw::Kek;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use josekit::jwe;
use josekit::jwe::alg::aeskw::AeskwJweAlgorithm;
use josekit::jwe::alg::rsaes::RsaesJweAlgorithm;
use josekit::jwe::JweHeader;
use josekit::jwk::alg::rsa::RsaKeyPair;
use josekit::jwk::Jwk;
use rand::{random, thread_rng};
use rsa::{Oaep, RsaPrivateKey, RsaPublicKey};
use rust_util::{opt_result, simple_error, XResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha1::Sha1;
const LOCAL_KMS_PREFIX: &str = "LKMS:";
// JWE format:
// BASE64URL(UTF8(JWE Protected Header)) || '.' ||
// BASE64URL(JWE Encrypted Key) || '.' || BASE64URL(JWE Initialization Vector)
// || '.' || BASE64URL(JWE Ciphertext) || '.' || BASE64URL(JWE Authentication Tag).
//
// RSA JWE Header:
// {"enc":"A256GCM","vendor":"local-mini-kms","alg":"RSA-OAEP"}
// eyJlbmMiOiJBMjU2R0NNIiwidmVuZG9yIjoibG9jYWwtbWluaS1rbXMiLCJhbGciOiJSU0EtT0FFUCJ9.VQ_R
// yGjXqQlUIbRIMgaYRSaX5FMRBzZ6ApfdZ2yAwiG70hjNfR3ss7x4PYqMm6QtITm1O4_fp7I3bY8iUz5Njyth_
// Min7Xm2-WsQ6gq9yN58btkUBFm60c7SC5XLaqE1pEtBAz7786bJk6M4NeOtDAOFAmIb2j1EwnS5vweBtmNv7N
// UFIgvx806T3WkCFDOkMSJ10_6LSa0z-lIac-s68svsU5WW8CXVKxHAbxaHyX_otu2HxXzDZlF5Goamh5ZJtr0
// 0yW_bzDCx3hZ2nMK3Ve7IJ2ZLAMmvhj9LKWkPtoqH0dGHaPHWff5P3rZ4vtKywt_h5b6SYII_mEoJcpByMyGw
// TXCtZymDt82Tyv_FesW2721JgyGxnukuOxQRTw4MfGYIO5bldL3uGGI_H4HXlXhM_kp3wuPAZ0vH4Jj2KD6MV
// DDTJQaEBQIEF07i7WiNynr57kbahYwextRXYP7LgoUHfFwA5GGGpN-UkuWLlKkYLTmXGrPYnL6Cf9D3euP7nF
// ml2oA2hjig-UuYf9A_QSEqNsMxYDuG-rggn3H_iXNl4ooYcxSVOXhTKfoV578MkNwG75BdHN5FeRYIKq0HCTM
// lGqqBWmDibPtMd7Uq1JrDd8774lnA8JcZcCMSia4m6WJSbG0kOuJ4NJPOUrYtNEJXgWKU3FQzDB-apLMQdac.
// WYJgsdZRLk310KWd.P333-S2VYg.PCfruTdk8vh3a8wcjJCe-g
//
// RSA-OAEP RSA using Optimal Asymmetric Encryption Padding (OAEP), as defined in RFC 3447 [RFC3447]
// A256GCM Advanced Encryption Standard (AES) using 256 bit keys in Galois/Counter Mode, as defined in [FIPS197] and [NIST80038D]
//
// AES JWE Header:
// {"enc":"A256GCM","vendor":"local-mini-kms","version":"5b90f66a1c6a918d","alg":"A256KW"}
// eyJlbmMiOiJBMjU2R0NNIiwidmVuZG9yIjoibG9jYWwtbWluaS1rbXMiLCJ2ZXJzaW9uIjoiNWI5MGY2NmExYz
// ZhOTE4ZCIsImFsZyI6IkEyNTZLVyJ9.K2_P-b_Gq9wbrssbcS5AmiUwcnNTnnZSe7rBI1SixVrC7TfFK0fruw.
// ez3OKjOHAIIYnfM0.wSO3aXo.-vGJwk8JQKhi3voIlAA9gQ
//
// A256GCM Advanced Encryption Standard (AES) using 256 bit keys in Galois/Counter Mode, as defined in [FIPS197] and [NIST80038D]
// A256KW Advanced Encryption Standard (AES) Key Wrap Algorithm using 256 bit keys, as defined in RFC 3394 [RFC3394]
// JWE Header: {"alg":"dir","enc":"A256GCM"}
// Encrypted key (CEK): (blank)
// IV: Vlf_WdLm-spHbfJe
// Ciphertext: RxMPrw
// Authentication Tag: 5VC8Y_qSPdSubbGNGyfn6A
//
// JWE Header: {"alg":"A256KW","enc":"A256GCM"}
// Encrypted key (CEK): 66xZoxFI18zfvLMO6WU1zzqqX1tT8xu_qZzMQyPcfVuajPNkOJUXQA
// IV: X5ZL8yaOektXmfny
// Ciphertext: brz-Lg
// Authentication Tag: xG-EvM-9hrw0XRiuRW7HrA
//
// https://security.stackexchange.com/questions/80966/what-is-the-point-of-aes-key-wrap-with-json-web-encryption
const JWE_ENC_A256GCM: &str = "A256GCM";
const JWE_ALG_A256KW: &str = "A256KW";
const JWE_ALG_RSA_OAEP: &str = "RSA-OAEP";
const JWE_DOT: &str = ".";
pub fn generate_rsa_key_2(bits: u32) -> XResult<RsaPrivateKey> {
let mut rng = thread_rng();
Ok(RsaPrivateKey::new(&mut rng, bits as usize)?)
}
pub fn generate_rsa_key(bits: u32) -> XResult<RsaKeyPair> {
Ok(RsaKeyPair::generate(bits)?)
}
pub fn serialize_jwe_rsa_2(payload: &[u8], rsa_public_key: &RsaPublicKey) -> XResult<String> {
let header = JweHeader2 {
enc: JWE_ENC_A256GCM.to_string(),
alg: JWE_ALG_RSA_OAEP.to_string(),
vendor: "local-mini-kms".to_string(),
version: None,
};
serialize_jwe_fn(&header, payload, |data_key| -> XResult<Vec<u8>> {
let mut r = thread_rng();
Ok(opt_result!(rsa_public_key.encrypt(&mut r, Oaep::new::<Sha1>(), data_key), "Wrap key failed: {}"))
})
}
pub fn serialize_jwe_rsa(payload: &[u8], jwk: &Jwk) -> XResult<String> {
let mut header = JweHeader::new();
header.set_content_encryption(JWE_ENC_A256GCM);
header.set_claim("vendor", Some(Value::String("local-mini-kms".to_string())))?;
let encrypter = RsaesJweAlgorithm::RsaOaep.encrypter_from_jwk(jwk)?;
Ok(format!("{}{}", LOCAL_KMS_PREFIX, jwe::serialize_compact(payload, &header, &encrypter)?))
}
pub fn deserialize_jwe_rsa_2(jwe: &str, rsa: &RsaPrivateKey) -> XResult<(Vec<u8>, JweHeader2)> {
deserialize_jwe_fn(jwe, |alg, key_wrap| -> XResult<Vec<u8>> {
if alg != JWE_ALG_RSA_OAEP {
return simple_error!("Invalid JWE header alg: {}", alg);
}
Ok(opt_result!(rsa.decrypt(Oaep::new::<Sha1>(), &key_wrap), "Unwrap key failed: {}"))
})
}
pub fn deserialize_jwe_rsa(jwe: &str, jwk: &Jwk) -> XResult<(Vec<u8>, JweHeader)> {
let decrypter = RsaesJweAlgorithm::RsaOaep.decrypter_from_jwk(jwk)?;
Ok(jwe::deserialize_compact(&get_jwe(jwe), &decrypter)?)
}
#[derive(Debug, Serialize, Deserialize)]
pub struct JweHeader2 {
pub enc: String,
pub alg: String,
pub vendor: String,
pub version: Option<String>,
}
pub fn serialize_jwe_aes_2(payload: &[u8], key: [u8; 32]) -> XResult<String> {
let header = JweHeader2 {
enc: JWE_ENC_A256GCM.to_string(),
alg: JWE_ALG_A256KW.to_string(),
vendor: "local-mini-kms".to_string(),
version: None,
};
serialize_jwe_fn(&header, payload, |data_key| -> XResult<Vec<u8>> {
let kek = Kek::from(key);
Ok(opt_result!(kek.wrap_vec(&data_key[..]), "Wrap key failed: {}"))
})
}
pub fn serialize_jwe_aes(payload: &[u8], key: &[u8]) -> XResult<String> {
let mut header = JweHeader::new();
header.set_content_encryption(JWE_ENC_A256GCM);
header.set_claim("vendor", Some(Value::String("local-mini-kms".to_string())))?;
// header.set_claim("version", Some(Value::String(get_master_key_checksum(key))))?;
let encrypter = AeskwJweAlgorithm::A256kw.encrypter_from_bytes(key)?;
Ok(format!("{}{}", LOCAL_KMS_PREFIX, jwe::serialize_compact(payload, &header, &encrypter)?))
}
pub fn deserialize_jwe_aes_2(jwe: &str, key: [u8; 32]) -> XResult<(Vec<u8>, JweHeader2)> {
deserialize_jwe_fn(jwe, |alg, key_wrap| -> XResult<Vec<u8>> {
if alg != JWE_ALG_A256KW {
return simple_error!("Invalid JWE header alg: {}", alg);
}
let kek = Kek::from(key);
Ok(opt_result!(kek.unwrap_vec(&key_wrap), "Unwrap key failed: {}"))
})
}
pub fn deserialize_jwe_aes(jwe: &str, key: &[u8]) -> XResult<(Vec<u8>, JweHeader)> {
let decrypter = AeskwJweAlgorithm::A256kw.decrypter_from_bytes(key)?;
Ok(jwe::deserialize_compact(&get_jwe(jwe), &decrypter)?)
}
fn serialize_jwe_fn<F>(header: &JweHeader2, payload: &[u8], key_wrap_fn: F) -> XResult<String>
where
F: Fn(&[u8]) -> XResult<Vec<u8>>,
{
let header_str = opt_result!(serde_json::to_string(&header), "Invalid JWE header: {}");
let header_b64 = URL_SAFE_NO_PAD.encode(header_str.as_bytes());
let data_key: [u8; 32] = random();
let iv: [u8; 12] = random();
let mut encryptor = Aes256GcmStreamEncryptor::new(data_key, &iv);
encryptor.init_adata(header_b64.as_bytes());
let mut ciphertext = encryptor.update(payload);
let (ciphertext_final, tag) = encryptor.finalize();
ciphertext.extend_from_slice(&ciphertext_final);
let cek = key_wrap_fn(&data_key)?;
Ok(format!(
"{}.{}.{}.{}.{}",
header_b64,
URL_SAFE_NO_PAD.encode(&cek),
URL_SAFE_NO_PAD.encode(&iv),
URL_SAFE_NO_PAD.encode(&ciphertext),
URL_SAFE_NO_PAD.encode(&tag)
))
}
fn deserialize_jwe_fn<F>(jwe: &str, key_unwrap_fn: F) -> XResult<(Vec<u8>, JweHeader2)>
where
F: Fn(&str, &[u8]) -> XResult<Vec<u8>>,
{
let jwe_parts = jwe.split(JWE_DOT).collect::<Vec<&str>>();
if jwe_parts.len() != 5 {
return simple_error!("Invalid JWE: {}", jwe);
}
let header_bytes = opt_result!(decode_url_safe_no_pad(jwe_parts[0]), "Invalid JWE header: {}, JWE: {}", jwe);
let header: JweHeader2 = opt_result!(serde_json::from_slice(&header_bytes), "Invalid JWE header: {}, JWE: {}", jwe);
if header.enc != JWE_ENC_A256GCM {
return simple_error!("Invalid JWE header enc: {}", header.enc);
}
let cek = opt_result!(decode_url_safe_no_pad(jwe_parts[1]), "Invalid JWE CEK: {}, JWE: {}", jwe);
let iv = opt_result!(decode_url_safe_no_pad(jwe_parts[2]), "Invalid JWE IV: {}, JWE: {}", jwe);
let ciphertext = opt_result!(decode_url_safe_no_pad(jwe_parts[3]), "Invalid JWE ciphertext: {}, JWE: {}", jwe);
let tag = opt_result!(decode_url_safe_no_pad(jwe_parts[4]), "Invalid JWE tag: {}, JWE: {}", jwe);
let data_key = key_unwrap_fn(&header.alg, &cek)?;
let data_key_b32 = opt_result!(to_bytes32(&data_key), "Invalid JWE CEK: {}, JWE: {}", jwe);
let mut decryptor = Aes256GcmStreamDecryptor::new(data_key_b32, &iv);
decryptor.init_adata(jwe_parts[0].as_bytes());
let mut plaintext = decryptor.update(&ciphertext);
let plaintext_2 = decryptor.update(&tag);
let plaintext_final = opt_result!(decryptor.finalize(), "Invalid JWE: {}, JWE: {}", jwe);
plaintext.extend_from_slice(&plaintext_2);
plaintext.extend_from_slice(&plaintext_final);
Ok((plaintext, header))
}
#[inline]
fn decode_url_safe_no_pad(s: &str) -> XResult<Vec<u8>> {
Ok(URL_SAFE_NO_PAD.decode(s.as_bytes())?)
}
#[inline]
fn to_bytes32(bytes: &[u8]) -> XResult<[u8; 32]> {
if bytes.len() != 32 {
return simple_error!("Not valid 32 bytes");
}
let mut ret = [0; 32];
for i in 0..32 {
ret[i] = bytes[i];
}
Ok(ret)
}
#[inline]
fn get_jwe(jwe: &str) -> String {
if jwe.starts_with(LOCAL_KMS_PREFIX) {
jwe.chars().skip(LOCAL_KMS_PREFIX.len()).collect()
} else {
jwe.to_string()
}
}

View File

@@ -0,0 +1,92 @@
mod jose;
use crate::jose::{deserialize_jwe_aes, deserialize_jwe_aes_2, deserialize_jwe_rsa_2, serialize_jwe_aes_2, serialize_jwe_rsa, serialize_jwe_rsa_2};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use jose_jwk::{Jwk, Key, Rsa};
use rand::random;
use rand::rngs::ThreadRng;
use rsa::traits::{PrivateKeyParts, PublicKeyParts};
use rsa::{Oaep, Pkcs1v15Encrypt};
use sha2::Sha256;
fn main() {
let key: [u8; 32] = random();
let payload = b"hello world";
let e = serialize_jwe_aes_2(payload, key).unwrap();
println!("{}", e);
let (d, h) = deserialize_jwe_aes(&e, &key).unwrap();
println!("{:?}", d);
println!("{:?}", h);
let (d2, h2) = deserialize_jwe_aes_2(&e, key).unwrap();
println!("{:?}", d2);
println!("{:?}", h2);
let rsa_key = jose::generate_rsa_key_2(2048).unwrap();
let rsa_public_key = rsa_key.as_ref();
let public_rsa: Rsa = rsa_public_key.into();
// let rsa: Rsa = rsa_key.into();
// println!("{:?}", public_rsa);
// println!("{:?}", rsa);
let jwk = Jwk {
key: Key::Rsa(public_rsa),
prm: Default::default(),
};
let jwk_str = serde_json::to_string(&jwk).unwrap();
println!("{}", &jwk_str);
// let rsa: Rsa = serde_json::from_str(&jwk_str).unwrap();
let josekitjwk = josekit::jwk::Jwk::from_bytes(jwk_str.as_bytes()).unwrap();
let rsa_jwe = serialize_jwe_rsa(b"hello world 001", &josekitjwk).unwrap();
// let rsa_key_2: RsaPrivateKey = rsa.try_into().unwrap();
println!(">>> {}", rsa_jwe);
let rsa_jwe = rsa_jwe.chars().skip(5).collect::<String>();
let (dd, hh) = deserialize_jwe_rsa_2(&rsa_jwe, &rsa_key).unwrap();
println!("DD: {}", String::from_utf8_lossy(&dd));
println!("HH: {:?}", hh);
println!("-------------------------------------------------------------------------------------");
let rsa_jwe2 = serialize_jwe_rsa_2(b"hello world 003", rsa_public_key).unwrap();
println!(">>> {}", rsa_jwe2);
// let rsa_jwe2 = rsa_jwe2.chars().skip(5).collect::<String>();
let (ddd, hhh) = deserialize_jwe_rsa_2(&rsa_jwe2, &rsa_key).unwrap();
println!("DDD: {}", String::from_utf8_lossy(&ddd));
println!("HHH: {:?}", hhh);
println!("-------------------------------------------------------------------------------------");
main2();
}
fn main2() {
let rsa_jwk = r##"{
"kty":"RSA",
"e":"AQAB",
"n":"5xyyPQx8Z7AjVf8Mg4xTE6yN8efPHc0lCdO056R2lzaEQeFwVCbOxFCnmly2-HtE_F_Wd3-B0nxOmODIyC4T
kLS3hXuflZb-OH73GwYDRmfcvWorACm0hv_a3p8YCuXvZ9aQUPRXwLn1jmAnKJiVRtObZTmmG5TsO-Q-U1DJjKhuP
--4co9T434y3U9xGIBYAudQ8tn4QSuVInrO2svg4gb9PExLDBn_46yEiLn-q0TzvO-s2rZ0iCpfB0Gji3djQiF-op
WUjLeGIMLC-gwAOKB4PjlsJBPlIg3pYpRuUEDERIy7kxZ8PIe4Nrfli_sRwMknm9HgQaigu3euYcjxXG9CALTs_vR
a7lRdpEKQY1ysY_z0bjIk1v-erEyNflQimpDHXGxujVj1EUrYz2diu60acmLSEciThafweAupr_qyKXUutBsc_KPK
33n8KBIPjl8X7bX2z-dXMKXo312vfPb6iO1ZcoFXG2nkFzwvFUKYFHSGjuZTQKgiaVEhlbq7N-80BlynnkHLYGcbn
9MtrT8O2Fci1i2ByxyL6B3vB1D5J1VyZ7IBY5AD1GanK2uFmC9nAoFvjTQJt3k2TI_MiPHgb1fZkHu0r-yrf9W_Hr
PrhBTp5wbepRSC6hs-yTykLJKSE5CD43KbjoW5GCqOkkQMnVjvSY4FpAdTj8Qt7kk"
}"##;
let rsa_jwk = rsa_jwk.replace(" ", "");
let rsa_jwk = rsa_jwk.replace("\r", "");
let rsa_jwk = rsa_jwk.replace("\n", "");
println!("{}", rsa_jwk);
let rsa: Rsa = serde_json::from_str(&rsa_jwk).unwrap();
let rsa_public_key = rsa::RsaPublicKey::try_from(rsa).unwrap();
// println!("{:?}", rsa_public_key);
let mut r = ThreadRng::default();
let enc = rsa_public_key.encrypt(&mut r, Pkcs1v15Encrypt, b"aaaaaaaa").unwrap();
println!("{}", STANDARD.encode(&enc));
let enc2 = rsa_public_key.encrypt(&mut r, Oaep::new::<Sha256>(), b"").unwrap();
println!("{}", STANDARD.encode(&enc2));
}

258
__crypto/ml-kem-demo/Cargo.lock generated Normal file
View File

@@ -0,0 +1,258 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "cfg-if"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "hybrid-array"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2d35805454dc9f8662a98d6d61886ffe26bd465f5960e0e55345c70d5c0d2a9"
dependencies = [
"typenum",
]
[[package]]
name = "keccak"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc2af9a1119c51f12a14607e783cb977bde58bc069ff0c3da1095e635d70654"
dependencies = [
"cpufeatures",
]
[[package]]
name = "kem"
version = "0.3.0-pre.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b8645470337db67b01a7f966decf7d0bafedbae74147d33e641c67a91df239f"
dependencies = [
"rand_core",
"zeroize",
]
[[package]]
name = "libc"
version = "0.2.176"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174"
[[package]]
name = "ml-kem"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97befee0c869cb56f3118f49d0f9bb68c9e3f380dec23c1100aedc4ec3ba239a"
dependencies = [
"hybrid-array",
"kem",
"rand_core",
"sha3",
"zeroize",
]
[[package]]
name = "ml-kem-demo"
version = "0.1.0"
dependencies = [
"base64",
"ml-kem",
"rand",
]
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "sha3"
version = "0.10.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60"
dependencies = [
"digest",
"keccak",
]
[[package]]
name = "syn"
version = "2.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"
[[package]]
name = "unicode-ident"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "zerocopy"
version = "0.8.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zeroize"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"

View File

@@ -0,0 +1,9 @@
[package]
name = "ml-kem-demo"
version = "0.1.0"
edition = "2024"
[dependencies]
base64 = "0.22.1"
ml-kem = { version = "0.2.1", features = ["zeroize"] }
rand = "0.8"

View File

@@ -0,0 +1,31 @@
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use ml_kem::kem::Encapsulate;
use ml_kem::{Encoded, EncodedSizeUser, KemCore, MlKem768};
fn main() {
let ek_bytes = STANDARD.decode("fZKrgJTGZYMogAO0u8XI/skLXXCx/hCmQjKdEGGaBitoBWCrbaw\
+t7nAT7G8lexlEdwGJrdwNuBVJFZOEnxH9Fu2e7kZrAA0EWZThrhrlCQb7SKSJ3MKP9jGeNA2igU/cXhQj9qSaWzNqplMffhuZHjBAT\
Nxglk6IwBcUnNpgEit0dYJgsxsMkfD8AzOaHKm4ybKwzJtYBN6nREl/OZE9CvDtVmZx+wkE1JwWuJJzLqdHWvJ4lyFq2YRUnxtpACKp\
xAkVfOzRuqlPUDJijwAc1UvXaFDLydJ/kcKiAorUfQtUoVJ8hkGK8OED3B15NxfJsRwt1kLhEgk89lD6GGhRRFmU8WQHBuX0pppe5A5\
BEm148Gv82c+KUUXSAcIFTFMg+UyPDKCaPFu5XBfyvM5RveXuyBFs/IF47BTmKfMVVOPXuh/SIZCONsBAOZgoneexKp8NyjMsVc8kWC\
OCVc+2sIcKjIElmRtjDFK9vooRVwGXppfPcV2vMeUk5IMF7aGnDdjkdGm1/oYkPqnvesi5bIpL+kGj9EPDibIPAS4AUQajgNNioRErB\
mxAdlZHWpXD+ixmbJp4geG7gJ3OsbBhmmBtJuPTcZeSLOg3HVtQTwyhxd1WjcMh1eqp0i5bDF/0Zin8dcqE0JRmTBj4MTAEbs1xNe1+\
xCZB3tnviVOU9d5uSpF6MNmdVWFiYmJJFYyeiJIOWmL1Och79S565dhxxO+ndd2DHVIuTaBW3cu4WSn9AlMqAcPvMxPAYcY7kFcOjc/\
PvYI4+oIfGgLaCcFNWcZUCBKz2Qi1zYqSjYYTrnJQVGClpOaGpdXi0zDYvagA2ZSDzNZS6oki6ZeimU0YzQDlRirNPx6ARSgdJU7WgA\
SpUNen0QLcoa7iwTDwGeEkHMt2OhUmqdv8bUNJ7YjpJuHOKuMX2C6fJslY5pyP5FJNVE7BugCSdSU1rxOKcHN0iiQSEgd8BU8hkZmof\
GahyzPgABI1cJjViMb/cgoiRtrsZuzBWDCVjog8mx7ulYhkszM9ghookGbHHwx/abBbRcTr1HIl0ursSCJPoZT3UWFRNgvVuA7gMQVJ\
FxxiFBOxOuHrMTABhVdpPCpNYvEgWRC+Skj3XhZRWovTLuDWPazRMe31iWVirBWTUIeIEEiRsvBPXMW3Ne1gsVwDFEOiaxp5SOAnAGK\
mkg/8LIRTHA0LbpBDEjEK+VllQeCIaUJk9g2FxlgatuqcDgIY2KH2NZapIOiRyZYs8shb2JJIRAWqcwRNIBL7ZwBOpafsyJc3BS4YSY\
ErVdAOOZe8/G9mcrNwOKzkkPFDUsb+eBEdHIr4bCUGGyinLkGskkXb1Gl8FCbTOGU04ZZtqhFI6eP5Stb7MiY7ywRhiOvokduQTLN26\
CsRJa579VOqdeSsNjFI6lxMhgwaxGaHcwWiGBDSbGGcyskujyPebYl+UlhDXGGVHYfZStkj8Sm84KGWqaq9BSQmIgU8oCj7SRMTGC3c\
dmjK5QiTGV+LEZKWwpQ9+GU5TIrTqImmeBj+dpGoPFmbliytiKbH53ZsFCfVNMqOvJ24IxdfgWNpBmrChnYmLQ=").unwrap();
let e: Encoded<<MlKem768 as KemCore>::EncapsulationKey> =
ek_bytes.as_slice().try_into().unwrap();
let ek = <MlKem768 as KemCore>::EncapsulationKey::from_bytes(&e);
let mut rng = rand::rngs::OsRng;
let k = ek.encapsulate(&mut rng).unwrap();
println!("{}", STANDARD.encode(k.0.as_slice()));
println!("Shared secret: {}", STANDARD.encode(k.1.as_slice()));
}

257
__crypto/okta-bcrypt-issue/Cargo.lock generated Normal file
View File

@@ -0,0 +1,257 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bcrypt"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92758ad6077e4c76a6cadbce5005f666df70d4f13b19976b1a8062eef880040f"
dependencies = [
"base64",
"blowfish",
"getrandom",
"subtle",
"zeroize",
]
[[package]]
name = "bitflags"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
[[package]]
name = "blowfish"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7"
dependencies = [
"byteorder",
"cipher",
]
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cfg-if"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"wasi",
]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]]
name = "libc"
version = "0.2.174"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
[[package]]
name = "okta-bcrypt-issue"
version = "0.1.0"
dependencies = [
"base64",
"bcrypt",
"rand",
]
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "rand"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
dependencies = [
"getrandom",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wasi"
version = "0.14.2+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3"
dependencies = [
"wit-bindgen-rt",
]
[[package]]
name = "wit-bindgen-rt"
version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
dependencies = [
"bitflags",
]
[[package]]
name = "zerocopy"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zeroize"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"

View File

@@ -0,0 +1,9 @@
[package]
name = "okta-bcrypt-issue"
version = "0.1.0"
edition = "2024"
[dependencies]
base64 = "0.22.1"
bcrypt = "0.17.0"
rand = "0.9.1"

View File

@@ -0,0 +1,33 @@
use rand::RngCore;
use base64::{Engine as _, engine::general_purpose::URL_SAFE};
use std::error::Error;
fn random_string(length: usize) -> String {
let mut bytes = vec![0u8; length];
rand::rng().fill_bytes(&mut bytes);
URL_SAFE.encode(&bytes)[..length].to_string()
}
// https://n0rdy.foo/posts/20250121/okta-bcrypt-lessons-for-better-apis/
fn main() -> Result<(), Box<dyn Error>> {
// 18 + 55 + 1 = 74, so above 72 characters' limit of BCrypt
let user_id = random_string(18);
let username = random_string(55);
let password = "super-duper-secure-password";
let combined_string = format!("{}:{}:{}", user_id, username, password);
let combined_hash = bcrypt::hash(combined_string.as_bytes(), bcrypt::DEFAULT_COST)?;
// let's try to break it
let wrong_password = "wrong-password";
let wrong_combined_string = format!("{}:{}:{}", user_id, username, wrong_password);
match bcrypt::verify(wrong_combined_string.as_bytes(), &combined_hash) {
Ok(true) => println!("Password is correct"),
Ok(false) => println!("Password is incorrect"),
Err(e) => println!("{}", e),
}
Ok(())
}

108
__crypto/orion-demo/Cargo.lock generated Normal file
View File

@@ -0,0 +1,108 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bitflags"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
[[package]]
name = "cfg-if"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
[[package]]
name = "ct-codecs"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b10589d1a5e400d61f9f38f12f884cfd080ff345de8f17efda36fe0e4a02aa8"
[[package]]
name = "fiat-crypto"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
[[package]]
name = "getrandom"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"wasi",
]
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "libc"
version = "0.2.174"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
[[package]]
name = "orion"
version = "0.17.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b3da83b2b4cdc74ab6a556b2e7b473da046d5aa4008c0a7a3ae96b1b4aabb4"
dependencies = [
"ct-codecs",
"fiat-crypto",
"getrandom",
"subtle",
"zeroize",
]
[[package]]
name = "orion-demo"
version = "0.1.0"
dependencies = [
"hex",
"orion",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "wasi"
version = "0.14.2+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3"
dependencies = [
"wit-bindgen-rt",
]
[[package]]
name = "wit-bindgen-rt"
version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
dependencies = [
"bitflags",
]
[[package]]
name = "zeroize"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"

View File

@@ -0,0 +1,8 @@
[package]
name = "orion-demo"
version = "0.1.0"
edition = "2024"
[dependencies]
hex = "0.4.3"
orion = "0.17.11"

View File

@@ -0,0 +1,44 @@
use orion::hazardous::ecc::x25519::key_agreement;
use orion::kex::{PrivateKey, PublicKey};
use orion::pwhash::{Password, hash_password, hash_password_verify};
fn main() {
let password = Password::from_slice(b"hello_world").unwrap();
let password_hash = hash_password(&password, 100, 1024).unwrap();
println!("{}", password_hash.unprotected_as_encoded());
println!("{:?}", hash_password_verify(&password_hash, &password));
println!("{}", "-".repeat(88));
let alice_sk = PrivateKey::generate();
let alice_pk = PublicKey::try_from(&alice_sk).unwrap();
let bob_sk = PrivateKey::generate();
let bob_pk = PublicKey::try_from(&bob_sk).unwrap();
let alice_shared = key_agreement(&alice_sk, &bob_pk).unwrap();
let bob_shared = key_agreement(&bob_sk, &alice_pk).unwrap();
println!("{}", hex::encode(alice_shared.unprotected_as_bytes()));
println!("{}", hex::encode(bob_shared.unprotected_as_bytes()));
println!("{}", "-".repeat(88));
let user_password = Password::from_slice(b"hello_world").unwrap();
let salt = orion::kdf::Salt::default();
let derived_key = orion::kdf::derive_key(&user_password, &salt, 3, 1 << 16, 32).unwrap();
println!(
"{} {}",
hex::encode(salt.as_ref()),
hex::encode(derived_key.unprotected_as_bytes())
);
println!("{}", "-".repeat(88));
let aead_key = orion::aead::SecretKey::generate(32).unwrap();
let ciphertext = orion::aead::seal(&aead_key, b"hello world").unwrap();
let plaintext = orion::aead::open(&aead_key, &ciphertext).unwrap();
println!("{}", hex::encode(&ciphertext));
println!("{} {}", hex::encode(&plaintext), String::from_utf8_lossy(&plaintext));
}

1504
__crypto/passkey-rs-demo/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
[package]
name = "passkey-rs-demo"
version = "0.1.0"
edition = "2024"
[dependencies]
passkey = "0.4.0"
url = "2.5.4"
async-trait = "0.1.88"
passkey-client = "0.4.0"
coset = "0.3.8"
tokio = { version = "1.45.1", features = ["full"] }

View File

@@ -0,0 +1,4 @@
Source code: https://github.com/1Password/passkey-rs/blob/main/passkey/examples/usage.rs

View File

@@ -0,0 +1,230 @@
use passkey::{
authenticator::{Authenticator, UserCheck, UserValidationMethod},
client::{Client, WebauthnError},
types::{crypto::sha256, ctap2::*, rand::random_vec, webauthn::*, Bytes, Passkey},
};
use coset::iana;
use passkey_client::DefaultClientData;
use url::Url;
// MyUserValidationMethod is a stub impl of the UserValidationMethod trait, used later.
struct MyUserValidationMethod {}
#[async_trait::async_trait]
impl UserValidationMethod for MyUserValidationMethod {
type PasskeyItem = Passkey;
async fn check_user<'a>(
&self,
_credential: Option<&'a Passkey>,
presence: bool,
verification: bool,
) -> Result<UserCheck, Ctap2Error> {
Ok(UserCheck {
presence,
verification,
})
}
fn is_verification_enabled(&self) -> Option<bool> {
Some(true)
}
fn is_presence_enabled(&self) -> bool {
true
}
}
// Example of how to set up, register and authenticate with a `Client`.
async fn client_setup(
challenge_bytes_from_rp: Bytes,
parameters_from_rp: PublicKeyCredentialParameters,
origin: &Url,
user_entity: PublicKeyCredentialUserEntity,
) -> Result<(CreatedPublicKeyCredential, AuthenticatedPublicKeyCredential), WebauthnError> {
// First create an Authenticator for the Client to use.
let my_aaguid = Aaguid::new_empty();
let user_validation_method = MyUserValidationMethod {};
// Create the CredentialStore for the Authenticator.
// Option<Passkey> is the simplest possible implementation of CredentialStore
let store: Option<Passkey> = None;
let my_authenticator = Authenticator::new(my_aaguid, store, user_validation_method);
// Create the Client
// If you are creating credentials, you need to declare the Client as mut
let mut my_client = Client::new(my_authenticator);
// The following values, provided as parameters to this function would usually be
// retrieved from a Relying Party according to the context of the application.
let request = CredentialCreationOptions {
public_key: PublicKeyCredentialCreationOptions {
rp: PublicKeyCredentialRpEntity {
id: None, // Leaving the ID as None means use the effective domain
name: origin.domain().unwrap().into(),
},
user: user_entity,
challenge: challenge_bytes_from_rp,
pub_key_cred_params: vec![parameters_from_rp],
timeout: None,
exclude_credentials: None,
authenticator_selection: None,
hints: None,
attestation: AttestationConveyancePreference::None,
attestation_formats: None,
extensions: None,
},
};
// Now create the credential.
let my_webauthn_credential = my_client
.register(origin, request, DefaultClientData)
.await?;
// Let's try and authenticate.
// Create a challenge that would usually come from the RP.
let challenge_bytes_from_rp: Bytes = random_vec(32).into();
// Now try and authenticate
let credential_request = CredentialRequestOptions {
public_key: PublicKeyCredentialRequestOptions {
challenge: challenge_bytes_from_rp,
timeout: None,
rp_id: Some(String::from(origin.domain().unwrap())),
allow_credentials: None,
user_verification: UserVerificationRequirement::default(),
hints: None,
attestation: AttestationConveyancePreference::None,
attestation_formats: None,
extensions: None,
},
};
let authenticated_cred = my_client
.authenticate(origin, credential_request, DefaultClientData)
.await?;
Ok((my_webauthn_credential, authenticated_cred))
}
async fn authenticator_setup(
user_entity: PublicKeyCredentialUserEntity,
client_data_hash: Bytes,
algorithms_from_rp: PublicKeyCredentialParameters,
rp_id: String,
) -> Result<get_assertion::Response, StatusCode> {
let store: Option<Passkey> = None;
let user_validation_method = MyUserValidationMethod {};
let my_aaguid = Aaguid::new_empty();
let mut my_authenticator = Authenticator::new(my_aaguid, store, user_validation_method);
let reg_request = make_credential::Request {
client_data_hash: client_data_hash.clone(),
rp: make_credential::PublicKeyCredentialRpEntity {
id: rp_id.clone(),
name: None,
},
user: user_entity,
pub_key_cred_params: vec![algorithms_from_rp],
exclude_list: None,
extensions: None,
options: make_credential::Options::default(),
pin_auth: None,
pin_protocol: None,
};
let credential: make_credential::Response =
my_authenticator.make_credential(reg_request).await?;
ctap2_creation_success(credential);
let auth_request = get_assertion::Request {
rp_id,
client_data_hash,
allow_list: None,
extensions: None,
options: make_credential::Options::default(),
pin_auth: None,
pin_protocol: None,
};
let response = my_authenticator.get_assertion(auth_request).await?;
Ok(response)
}
fn ctap2_creation_success(credential: make_credential::Response) {
println!(
"CTAP2 credential creation succeeded:\n\n{:?}\n\n",
credential
);
}
fn ctap2_auth_success(credential: get_assertion::Response) {
println!(
"CTAP2 credential authentication succeeded:\n\n{:?}\n\n",
credential
);
}
fn ctap2_credential_not_found() {
println!("CTAP2 error: Credential not found.");
}
fn ctap2_other_error(code: StatusCode) {
println!("CTAP2 error: Other Status Code: {:?}", code);
}
#[tokio::main]
async fn main() -> Result<(), WebauthnError> {
let rp_url = Url::parse("https://example.com/").expect("Should Parse");
let user_entity = PublicKeyCredentialUserEntity {
id: random_vec(32).into(),
display_name: "Hatter Jiang".into(),
name: "jpasskey@example.org".into(),
};
// Set up a client, create and authenticate a credential, then report results.
let (created_cred, authed_cred) = client_setup(
random_vec(32).into(), // challenge_bytes_from_rp
PublicKeyCredentialParameters {
ty: PublicKeyCredentialType::PublicKey,
alg: iana::Algorithm::ES256,
},
&rp_url, // origin
user_entity.clone(),
)
.await?;
println!("Webauthn credential created:\n\n{:?}\n\n", created_cred);
println!("Webauthn credential auth'ed:\n\n{:?}\n\n", authed_cred);
// Generate the client_data_hash from the created_cred response
let client_data_hash = sha256(&created_cred.response.client_data_json).to_vec();
// Authenticator Version
let authenticator_result = authenticator_setup(
user_entity,
client_data_hash.into(),
PublicKeyCredentialParameters {
ty: PublicKeyCredentialType::PublicKey,
alg: iana::Algorithm::ES256,
},
rp_url
.domain()
.expect("Our example should unwrap.")
.to_string(), // tld_from_rp
)
.await;
match authenticator_result {
Ok(authresponse) => {
ctap2_auth_success(authresponse);
}
Err(StatusCode::Ctap2(Ctap2Code::Known(Ctap2Error::NoCredentials))) => {
ctap2_credential_not_found()
}
Err(status_code) => ctap2_other_error(status_code),
};
Ok(())
}

496
__database/native_db-demo/Cargo.lock generated Normal file
View File

@@ -0,0 +1,496 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "anyhow"
version = "1.0.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519"
[[package]]
name = "bincode"
version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
dependencies = [
"serde",
]
[[package]]
name = "bitflags"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
[[package]]
name = "bytecount"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ce89b21cab1437276d2650d57e971f9d548a2d9037cc231abdc0562b97498ce"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "camino"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c59e92b5a388f549b863a7bea62612c09f24c8393560709a54558a9abdfb3b9c"
dependencies = [
"serde",
]
[[package]]
name = "cargo-platform"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24b1f0365a6c6bb4020cd05806fd0d33c44d38046b8bd7f0e40814b9763cabfc"
dependencies = [
"serde",
]
[[package]]
name = "cargo_metadata"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa"
dependencies = [
"camino",
"cargo-platform",
"semver",
"serde",
"serde_json",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "errno"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "error-chain"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc"
dependencies = [
"version_check",
]
[[package]]
name = "fastrand"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a"
[[package]]
name = "glob"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
[[package]]
name = "itoa"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
[[package]]
name = "libc"
version = "0.2.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346"
[[package]]
name = "linux-raw-sys"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c"
[[package]]
name = "memchr"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
[[package]]
name = "native_db"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27182169b7a825037923cf6c62ac76f6f5df66f7d6f9b8a85fe1ad5d12eb2fb5"
dependencies = [
"native_db_macro",
"native_model",
"redb 1.5.1",
"redb 2.1.0",
"serde",
"skeptic",
"thiserror",
]
[[package]]
name = "native_db-demo"
version = "0.1.0"
dependencies = [
"native_db",
"native_model",
"serde",
]
[[package]]
name = "native_db_macro"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf27ba40601fb6888260c815874d4d36b47e8288e99a5c0c1af59f4b854bef69"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "native_model"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfd94f3003aa4f8fdcf3312ef8108b921bf4840dc29f5df624939528bcef185c"
dependencies = [
"anyhow",
"bincode",
"native_model_macro",
"serde",
"skeptic",
"thiserror",
"zerocopy",
]
[[package]]
name = "native_model_macro"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05bdda3f323d488a499c7d5808af7898bac454d551e27c3c4fa76a25aa16f5cb"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pulldown-cmark"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57206b407293d2bcd3af849ce869d52068623f19e1b5ff8e8778e3309439682b"
dependencies = [
"bitflags",
"memchr",
"unicase",
]
[[package]]
name = "quote"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redb"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd7f82ecd6ba647a39dd1a7172b8a1cd9453c0adee6da20cb553d83a9a460fa5"
dependencies = [
"libc",
]
[[package]]
name = "redb"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed7508e692a49b6b2290b56540384ccae9b1fb4d77065640b165835b56ffe3bb"
dependencies = [
"libc",
]
[[package]]
name = "rustix"
version = "0.38.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "ryu"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "semver"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d43fe69e652f3df9bdc2b85b2854a0825b86e4fb76bc44d945137d053639ca"
dependencies = [
"serde",
]
[[package]]
name = "serde"
version = "1.0.200"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddc6f9cc94d67c0e21aaf7eda3a010fd3af78ebf6e096aa6e2e13c79749cce4f"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.200"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "856f046b9400cee3c8c94ed572ecdb752444c24528c035cd35882aad6f492bcb"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.116"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "skeptic"
version = "0.13.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16d23b015676c90a0f01c197bfdc786c20342c73a0afdda9025adb0bc42940a8"
dependencies = [
"bytecount",
"cargo_metadata",
"error-chain",
"glob",
"pulldown-cmark",
"tempfile",
"walkdir",
]
[[package]]
name = "syn"
version = "2.0.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1"
dependencies = [
"cfg-if",
"fastrand",
"rustix",
"windows-sys",
]
[[package]]
name = "thiserror"
version = "1.0.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicase"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89"
dependencies = [
"version_check",
]
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "version_check"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "winapi-util"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
[[package]]
name = "windows_i686_gnu"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
[[package]]
name = "windows_i686_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
[[package]]
name = "zerocopy"
version = "0.7.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be"
dependencies = [
"byteorder",
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.7.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6"
dependencies = [
"proc-macro2",
"quote",
"syn",
]

View File

@@ -0,0 +1,11 @@
[package]
name = "native_db-demo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
native_db = "0.6.0"
native_model = "0.4.18"
serde = "1.0.200"

View File

@@ -0,0 +1,46 @@
use native_db::*;
use native_model::Model;
use native_model::native_model;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
#[native_model(id = 1, version = 1)]
#[native_db]
struct Item {
#[primary_key]
id: u32,
#[secondary_key]
name: String,
}
fn main() -> Result<(), db_type::Error> {
let mut builder = DatabaseBuilder::new();
// Initialize the model
builder.define::<Item>()?;
// Create a database in memory
let db = builder.create_in_memory()?;
// Insert data (open a read-write transaction)
let rw = db.rw_transaction().unwrap();
rw.insert(Item { id: 1, name: "red".to_string() })?;
rw.insert(Item { id: 2, name: "green".to_string() })?;
rw.insert(Item { id: 3, name: "blue".to_string() })?;
rw.commit()?;
// Open a read-only transaction
let r = db.r_transaction()?;
// Retrieve data with id=3
let retrieve_data: Item = r.get().primary(3_u32)?.unwrap();
println!("data id='3': {:?}", retrieve_data);
// Iterate items with name starting with "red"
for item in r.scan().secondary::<Item>(ItemKey::name)?.start_with("red") {
println!("data name=\"red\": {:?}", item);
}
// Remove data (open a read-write transaction)
let rw = db.rw_transaction()?;
rw.remove(retrieve_data)?;
rw.commit()?;
Ok(())
}

710
__network/axum-demo/Cargo.lock generated Normal file
View File

@@ -0,0 +1,710 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "addr2line"
version = "0.24.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1"
dependencies = [
"gimli",
]
[[package]]
name = "adler2"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"
[[package]]
name = "axum"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d6fd624c75e18b3b4c6b9caf42b1afe24437daaee904069137d8bab077be8b8"
dependencies = [
"axum-core",
"bytes",
"form_urlencoded",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-util",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"rustversion",
"serde",
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "axum-core"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df1362f362fd16024ae199c1970ce98f9661bf5ef94b9808fee734bc3698b733"
dependencies = [
"bytes",
"futures-util",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"rustversion",
"sync_wrapper",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "axum-demo"
version = "0.1.0"
dependencies = [
"axum",
"serde",
"tokio",
"tracing-subscriber",
]
[[package]]
name = "backtrace"
version = "0.3.74"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a"
dependencies = [
"addr2line",
"cfg-if",
"libc",
"miniz_oxide",
"object",
"rustc-demangle",
"windows-targets",
]
[[package]]
name = "bytes"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-channel"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"
dependencies = [
"futures-core",
]
[[package]]
name = "futures-core"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-task"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
[[package]]
name = "futures-util"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"pin-utils",
]
[[package]]
name = "gimli"
version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
[[package]]
name = "http"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565"
dependencies = [
"bytes",
"fnv",
"itoa",
]
[[package]]
name = "http-body"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
dependencies = [
"bytes",
"http",
]
[[package]]
name = "http-body-util"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"pin-project-lite",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hyper"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc2b571658e38e0c01b1fdca3bbbe93c00d3d71693ff2770043f8c29bc7d6f80"
dependencies = [
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"smallvec",
"tokio",
]
[[package]]
name = "hyper-util"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df2dcfbe0677734ab2f3ffa7fa7bfd4706bfdc1ef393f2ee30184aed67e631b4"
dependencies = [
"bytes",
"futures-util",
"http",
"http-body",
"hyper",
"pin-project-lite",
"tokio",
"tower-service",
]
[[package]]
name = "itoa"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "libc"
version = "0.2.171"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6"
[[package]]
name = "log"
version = "0.4.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e"
[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "miniz_oxide"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5"
dependencies = [
"adler2",
]
[[package]]
name = "mio"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd"
dependencies = [
"libc",
"wasi",
"windows-sys",
]
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
dependencies = [
"overload",
"winapi",
]
[[package]]
name = "object"
version = "0.36.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87"
dependencies = [
"memchr",
]
[[package]]
name = "once_cell"
version = "1.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d75b0bedcc4fe52caa0e03d9f1151a323e4aa5e2d78ba3580400cd3c9e2bc4bc"
[[package]]
name = "overload"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]]
name = "percent-encoding"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "proc-macro2"
version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustc-demangle"
version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
[[package]]
name = "rustversion"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2"
[[package]]
name = "ryu"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]]
name = "serde"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.140"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
dependencies = [
"itoa",
"memchr",
"ryu",
"serde",
]
[[package]]
name = "serde_path_to_error"
version = "0.1.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59fab13f937fa393d08645bf3a84bdfe86e296747b506ada67bb15f10f218b2a"
dependencies = [
"itoa",
"serde",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "sharded-slab"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
dependencies = [
"lazy_static",
]
[[package]]
name = "smallvec"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd"
[[package]]
name = "socket2"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c970269d99b64e60ec3bd6ad27270092a5394c4e309314b18ae3fe575695fbe8"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "syn"
version = "2.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
[[package]]
name = "thread_local"
version = "1.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c"
dependencies = [
"cfg-if",
"once_cell",
]
[[package]]
name = "tokio"
version = "1.44.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f382da615b842244d4b8738c82ed1275e6c5dd90c459a30941cd07080b06c91a"
dependencies = [
"backtrace",
"libc",
"mio",
"pin-project-lite",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tower"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9"
dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
"sync_wrapper",
"tokio",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "tracing"
version = "0.1.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0"
dependencies = [
"log",
"pin-project-lite",
"tracing-core",
]
[[package]]
name = "tracing-core"
version = "0.1.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c"
dependencies = [
"once_cell",
"valuable",
]
[[package]]
name = "tracing-log"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
dependencies = [
"log",
"once_cell",
"tracing-core",
]
[[package]]
name = "tracing-subscriber"
version = "0.3.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008"
dependencies = [
"nu-ansi-term",
"sharded-slab",
"smallvec",
"thread_local",
"tracing-core",
"tracing-log",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "valuable"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

View File

@@ -0,0 +1,10 @@
[package]
name = "axum-demo"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = "0.8.1"
serde = { version = "1.0.219", features = ["derive"] }
tokio = { version = "1.44.1", features = ["macros", "rt-multi-thread"] }
tracing-subscriber = "0.3.19"

View File

@@ -0,0 +1,57 @@
use axum::{
routing::{get, post},
http::StatusCode,
Json, Router,
};
use serde::{Deserialize, Serialize};
#[tokio::main]
async fn main() {
// initialize tracing
tracing_subscriber::fmt::init();
// build our application with a route
let app = Router::new()
// `GET /` goes to `root`
.route("/", get(root))
// `POST /users` goes to `create_user`
.route("/users", post(create_user));
// run our app with hyper, listening globally on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
// basic handler that responds with a static string
async fn root() -> &'static str {
"Hello, World!"
}
async fn create_user(
// this argument tells axum to parse the request body
// as JSON into a `CreateUser` type
Json(payload): Json<CreateUser>,
) -> (StatusCode, Json<User>) {
// insert your application logic here
let user = User {
id: 1337,
username: payload.username,
};
// this will be converted into a JSON response
// with a status code of `201 Created`
(StatusCode::CREATED, Json(user))
}
// the input to our `create_user` handler
#[derive(Deserialize)]
struct CreateUser {
username: String,
}
// the output to our `create_user` handler
#[derive(Serialize)]
struct User {
id: u64,
username: String,
}

View File

@@ -0,0 +1,49 @@
# DNS Server in Rust
This repository contains the code for a **DNS server implemented in Rust**, as part of the tutorial [**Building a DNS Server in Rust**](https://rust-trends.com/posts/building-a-dns-server-in-rust/) . The tutorial covers:
- Understanding DNS requests and responses.
- Handling UDP packets in Rust.
- Parsing and constructing DNS packets.
- Implementing decompression of DNS packets.
- Forwarding DNS queries to resolvers.
## 📖 Tutorial
For a step-by-step guide, check out the full tutorial:
[Building a DNS Server in Rust: Part 1 of 2](https://rust-trends.com/posts/building-a-dns-server-in-rust/)
## 🛠 Installation
Ensure you have **Rust** installed:
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
## Clone this repository:
```sh
git clone https://github.com/Rust-Trends/dns-server-tutorial.git
cd dns-server-tutorial
```
## 🚀 Running the Server
Goto to the step you want to explore, e.g. step1, and start the DNS server on port 1053:
```sh
cd step1
cargo run
```
## 🔍 Testing with dig
To test your server, open another terminal and run:
```sh
dig @localhost -p 1053 www.rust-trends.com
```
## 🤝 Contributions
Feel free to open issues or submit pull requests to improve the project!
📜 License: MIT

View File

@@ -0,0 +1,9 @@
[package]
name = "dns-server"
authors = ["Bob Peters <contact@rust-trends.com>"]
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "4.5.29", features = ["derive"] }
thiserror = "2.0.11"

View File

@@ -0,0 +1,78 @@
// src/dns.rs
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ErrorCondition {
#[error("Serialization Error: {0}")]
SerializationErr(String),
#[error("Deserialization Error: {0}")]
DeserializationErr(String),
}
#[derive(Debug)]
pub struct Header {
pub id: u16, // identifier
pub qr: bool, // 0 for query, 1 for response
pub opcode: u8, // 0 for standard query
pub aa: bool, // authoritative answer
pub tc: bool, // truncated message
pub rd: bool, // recursion desired
pub ra: bool, // recursion available
pub z: u8, // reserved for future use
pub rcode: u8, // 0 for no error
pub qdcount: u16, // number of entries in the question section
pub ancount: u16, // number of resource records in the answer section
pub nscount: u16, // number of name server resource records in the authority records section
pub arcount: u16, // number of resource records in the additional records section
}
impl Header {
const DNS_HEADER_LEN: usize = 12;
// Serialize the header to a byte array
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(Header::DNS_HEADER_LEN);
buf.extend_from_slice(&self.id.to_be_bytes());
buf.push(
(self.qr as u8) << 7
| self.opcode << 3
| (self.aa as u8) << 2
| (self.tc as u8) << 1
| self.rd as u8,
);
buf.push((self.ra as u8) << 7 | self.z << 4 | self.rcode);
buf.extend_from_slice(&self.qdcount.to_be_bytes());
buf.extend_from_slice(&self.ancount.to_be_bytes());
buf.extend_from_slice(&self.nscount.to_be_bytes());
buf.extend_from_slice(&self.arcount.to_be_bytes());
buf
}
// Deserialize the header from a byte array
pub fn from_bytes(buf: &[u8]) -> Result<Header, ErrorCondition> {
if buf.len() < Header::DNS_HEADER_LEN {
return Err(ErrorCondition::DeserializationErr(
"Buffer length is less than header length".to_string(),
));
}
Ok(Header {
id: u16::from_be_bytes([buf[0], buf[1]]),
qr: (buf[2] & 0b1000_0000) != 0,
opcode: (buf[2] & 0b0111_1000) >> 3,
aa: (buf[2] & 0b0000_0100) != 0,
tc: (buf[2] & 0b0000_0010) != 0,
rd: (buf[2] & 0b0000_0001) != 0,
ra: (buf[3] & 0b1000_0000) != 0,
z: (buf[3] & 0b0111_0000) >> 4,
rcode: buf[3] & 0b0000_1111,
qdcount: u16::from_be_bytes([buf[4], buf[5]]),
ancount: u16::from_be_bytes([buf[6], buf[7]]),
nscount: u16::from_be_bytes([buf[8], buf[9]]),
arcount: u16::from_be_bytes([buf[10], buf[11]]),
})
}
}

View File

@@ -0,0 +1,44 @@
// src/main.rs
use std::net::UdpSocket;
mod dns;
use dns::Header;
// Debug print hex bytes of a buffer 16 bytes width followed by the ASCII representation of the bytes
fn debug_print_bytes(buf: &[u8]) {
for (i, chunk) in buf.chunks(16).enumerate() {
print!("{:08x}: ", i * 16);
for byte in chunk {
print!("{:02x} ", byte);
}
for _ in 0..(16 - chunk.len()) {
print!(" ");
}
print!(" ");
for byte in chunk {
if *byte >= 32 && *byte <= 126 {
print!("{}", *byte as char);
} else {
print!(".");
}
}
println!();
}
}
fn main() {
let socket = UdpSocket::bind("0.0.0.0:1053").expect("Could not bind to port 1053");
let mut buf = [0; 512];
println!("DNS server is running at port 1053");
loop {
let (len, addr) = socket.recv_from(&mut buf).expect("Could not receive data");
println!("\nReceived query from {} with length {} bytes", addr, len);
debug_print_bytes(&buf[..len]);
let header = Header::from_bytes(&buf[..len]).expect("Could not parse DNS header");
println!("\n{:?}", header);
}
}

View File

@@ -0,0 +1,9 @@
[package]
name = "dns-server"
authors = ["Bob Peters <contact@rust-trends.com>"]
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "4.5.29", features = ["derive"] }
thiserror = "2.0.11"

View File

@@ -0,0 +1,306 @@
// src/dns.rs
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ErrorCondition {
#[error("Serialization Error: {0}")]
SerializationErr(String),
#[error("Deserialization Error: {0}")]
DeserializationErr(String),
#[error("Invalid Label")]
InvalidLabel,
}
/// Maximum DNS message size without EDNS0
const MAX_DNS_MESSAGE_SIZE: usize = 512;
#[derive(Debug)]
pub struct Header {
pub id: u16, // identifier
pub qr: bool, // 0 for query, 1 for response
pub opcode: u8, // 0 for standard query
pub aa: bool, // authoritative answer
pub tc: bool, // truncated message
pub rd: bool, // recursion desired
pub ra: bool, // recursion available
pub z: u8, // reserved for future use
pub rcode: u8, // 0 for no error
pub qdcount: u16, // number of entries in the question section
pub ancount: u16, // number of resource records in the answer section
pub nscount: u16, // number of name server resource records in the authority records section
pub arcount: u16, // number of resource records in the additional records section
}
impl Header {
const DNS_HEADER_LEN: usize = 12;
// Serialize the header to a byte array
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(Header::DNS_HEADER_LEN);
buf.extend_from_slice(&self.id.to_be_bytes());
buf.push(
(self.qr as u8) << 7
| self.opcode << 3
| (self.aa as u8) << 2
| (self.tc as u8) << 1
| self.rd as u8,
);
buf.push((self.ra as u8) << 7 | self.z << 4 | self.rcode);
buf.extend_from_slice(&self.qdcount.to_be_bytes());
buf.extend_from_slice(&self.ancount.to_be_bytes());
buf.extend_from_slice(&self.nscount.to_be_bytes());
buf.extend_from_slice(&self.arcount.to_be_bytes());
buf
}
// Deserialize the header from a byte array
pub fn from_bytes(buf: &[u8]) -> Result<Header, ErrorCondition> {
if buf.len() < Header::DNS_HEADER_LEN {
return Err(ErrorCondition::DeserializationErr(
"Buffer length is less than header length".to_string(),
));
}
Ok(Header {
id: u16::from_be_bytes([buf[0], buf[1]]),
qr: (buf[2] & 0b1000_0000) != 0,
opcode: (buf[2] & 0b0111_1000) >> 3,
aa: (buf[2] & 0b0000_0100) != 0,
tc: (buf[2] & 0b0000_0010) != 0,
rd: (buf[2] & 0b0000_0001) != 0,
ra: (buf[3] & 0b1000_0000) != 0,
z: (buf[3] & 0b0111_0000) >> 4,
rcode: buf[3] & 0b0000_1111,
qdcount: u16::from_be_bytes([buf[4], buf[5]]),
ancount: u16::from_be_bytes([buf[6], buf[7]]),
nscount: u16::from_be_bytes([buf[8], buf[9]]),
arcount: u16::from_be_bytes([buf[10], buf[11]]),
})
}
}
#[derive(Debug, Clone)]
pub struct Question {
pub name: Vec<Label>,
pub qtype: Type,
pub qclass: Class,
}
#[derive(Debug, Clone)]
pub struct Label(String);
impl Label {
pub fn new(label: &[u8]) -> Result<Self, ErrorCondition> {
match std::str::from_utf8(label) {
Ok(s) => Ok(Label(s.to_string())),
Err(_) => Err(ErrorCondition::InvalidLabel),
}
}
pub fn len(&self) -> usize {
self.0.len()
}
}
#[derive(Debug, Clone)]
pub enum Type {
// Below are Resource Record Types and QTYPES
A = 1, // a host address
NS = 2, // an authoritative name server
MD = 3, // a mail destination (Obsolete - use MX)
MF = 4, // a mail forwarder (Obsolete - use MX)
CNAME = 5, // the canonical name for an alias
SOA = 6, // marks the start of a zone of authority
MB = 7, // a mailbox domain name (EXPERIMENTAL)
MG = 8, // a mail group member (EXPERIMENTAL)
MR = 9, // a mail rename domain name (EXPERIMENTAL)
NULL = 10, // a null RR (EXPERIMENTAL)
WKS = 11, // a well known service description
PTR = 12, // a domain name pointer
HINFO = 13, // host information
MINFO = 14, // mailbox or mail list information
MX = 15, // mail exchange
TXT = 16, // text strings
// Below are only QTYPES
AXFR = 252, // A request for a transfer of an entire zone
MAILB = 253, // A request for mailbox-related records (MB, MG or MR)
MAILA = 254, // A request for mail agent RRs (Obsolete - see MX)
_ALL_ = 255, // A request for all records
}
#[derive(Debug, Clone)]
pub enum Class {
// Below are Resource Record Classes and QCLASS
IN = 1, // the Internet
CS = 2, // the CSNET class (Obsolete - used only for examples in some obsolete RFCs)
CH = 3, // the CHAOS class
HS = 4, // Hesiod [Dyer 87]
// Below are only QCLASSES
_ALL_ = 255,
}
impl std::fmt::Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let msg: &str = match self {
Type::A => "a host address",
Type::NS => "an authoritative name server",
Type::MD => "a mail destination (Obsolete - use MX)",
Type::MF => "a mail forwarder (Obsolete - use MX)",
Type::CNAME => "the canonical name for an alias",
Type::SOA => "marks the start of a zone of authority",
Type::MB => "a mailbox domain name (EXPERIMENTAL)",
Type::MG => "a mail group member (EXPERIMENTAL)",
Type::MR => "a mail rename domain name (EXPERIMENTAL)",
Type::NULL => "a null RR (EXPERIMENTAL)",
Type::WKS => "a well known service description",
Type::PTR => "a domain name pointer",
Type::HINFO => "host information",
Type::MINFO => "mailbox or mail list information",
Type::MX => "mail exchange",
Type::TXT => "text strings",
Type::AXFR => "A request for a transfer of an entire zone",
Type::MAILB => "A request for mailbox-related records (MB, MG or MR)",
Type::MAILA => "A request for mail agent RRs (Obsolete - see MX)",
Type::_ALL_ => "A request for all records",
};
write!(f, "{}", msg)
}
}
impl Type {
pub fn from_bytes(bytes: &[u8]) -> Result<Type, ErrorCondition> {
match u16::from_be_bytes([bytes[0], bytes[1]]) {
1 => Ok(Type::A),
2 => Ok(Type::NS),
3 => Ok(Type::MD),
4 => Ok(Type::MF),
5 => Ok(Type::CNAME),
6 => Ok(Type::SOA),
7 => Ok(Type::MB),
8 => Ok(Type::MG),
9 => Ok(Type::MR),
10 => Ok(Type::NULL),
11 => Ok(Type::WKS),
12 => Ok(Type::PTR),
13 => Ok(Type::HINFO),
14 => Ok(Type::MINFO),
15 => Ok(Type::MX),
16 => Ok(Type::TXT),
252 => Ok(Type::AXFR),
253 => Ok(Type::MAILB),
254 => Ok(Type::MAILA),
255 => Ok(Type::_ALL_),
n => Err(ErrorCondition::DeserializationErr(
format!("Unknown Question Type {}", n).to_string(),
)),
}
}
pub fn to_bytes(&self) -> [u8; 2] {
let num = match self {
Type::A => 1,
Type::NS => 2,
Type::MD => 3,
Type::MF => 4,
Type::CNAME => 5,
Type::SOA => 6,
Type::MB => 7,
Type::MG => 8,
Type::MR => 9,
Type::NULL => 10,
Type::WKS => 11,
Type::PTR => 12,
Type::HINFO => 13,
Type::MINFO => 14,
Type::MX => 15,
Type::TXT => 16,
Type::AXFR => 252,
Type::MAILB => 253,
Type::MAILA => 254,
Type::_ALL_ => 255,
};
u16::to_be_bytes(num)
}
}
impl Class {
pub fn from_bytes(buf: &[u8]) -> Result<Self, ErrorCondition> {
let num = u16::from_be_bytes([buf[0], buf[1]]);
match num {
1 => Ok(Class::IN),
2 => Ok(Class::CS),
3 => Ok(Class::CH),
4 => Ok(Class::HS),
_ => Err(ErrorCondition::DeserializationErr(
format!("Unknown Question Class {}", num).to_string(),
)),
}
}
pub fn to_bytes(&self) -> [u8; 2] {
let num = match self {
Class::IN => 1,
Class::CS => 2,
Class::CH => 3,
Class::HS => 4,
Class::_ALL_ => 255,
};
u16::to_be_bytes(num)
}
}
impl Question {
// The from_bytes() function reconstructs a Question struct by iterating through the buffer, extracting labels,
// parsing the query type and class.
pub fn from_bytes(buf: &[u8]) -> Result<Self, ErrorCondition> {
let mut index = 0;
let mut labels: Vec<Label> = Vec::new();
println!("Labels:");
while buf[index] != 0 {
let len = buf[index] as usize;
index += 1;
labels.push(Label::new(&buf[index..index + len])?);
println!("{:?}", labels); // For debugging purposes
index += len;
}
index += 1;
let qtype = Type::from_bytes(&buf[index..index + 2])?;
index += 2;
let qclass = Class::from_bytes(&buf[index..index + 2])?;
Ok(Question {
name: labels,
qtype,
qclass,
})
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::new();
// Write the labels to the buffer and add . inbetween and end with 0
for label in &self.name {
buf.push(label.len() as u8);
buf.extend_from_slice(label.0.as_bytes());
}
buf.push(0);
// Write the question type and class to the buffer
buf.extend_from_slice(&self.qtype.to_bytes());
buf.extend_from_slice(&self.qclass.to_bytes());
buf
}
}

View File

@@ -0,0 +1,52 @@
// src/main.rs
use std::net::UdpSocket;
mod dns;
use dns::{Header, Question};
// Debug print hex bytes of a buffer 16 bytes width followed by the ASCII representation of the bytes
fn debug_print_bytes(buf: &[u8]) {
for (i, chunk) in buf.chunks(16).enumerate() {
print!("{:08x}: ", i * 16);
for byte in chunk {
print!("{:02x} ", byte);
}
for _ in 0..(16 - chunk.len()) {
print!(" ");
}
print!(" ");
for byte in chunk {
if *byte >= 32 && *byte <= 126 {
print!("{}", *byte as char);
} else {
print!(".");
}
}
println!();
}
}
fn main() {
let socket = UdpSocket::bind("0.0.0.0:1053").expect("Could not bind to port 1053");
let mut buf = [0; 512];
println!("DNS server is running at port 1053");
loop {
let (len, addr) = socket.recv_from(&mut buf).expect("Could not receive data");
println!("\nReceived query from {} with length {} bytes", addr, len);
println!("\n### DNS Query: ###");
debug_print_bytes(&buf[..len]);
let header = Header::from_bytes(&buf[..12]).expect("Could not parse DNS header");
println!("\n{:?}", header);
println!("\n### Question: ###");
debug_print_bytes(&buf[12..len]);
println!();
let question = Question::from_bytes(&buf[12..len]).expect("Could not parse DNS question");
println!("\n{:?}", question);
}
}

View File

@@ -0,0 +1,9 @@
[package]
name = "dns-server"
authors = ["Bob Peters <contact@rust-trends.com>"]
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "4.5.29", features = ["derive"] }
thiserror = "2.0.11"

View File

@@ -0,0 +1,349 @@
// src/dns.rs
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ErrorCondition {
#[error("Serialization Error: {0}")]
SerializationErr(String),
#[error("Deserialization Error: {0}")]
DeserializationErr(String),
#[error("Invalid Label")]
InvalidLabel,
}
/// Maximum DNS message size without EDNS0
const MAX_DNS_MESSAGE_SIZE: usize = 512;
#[derive(Debug)]
pub struct Header {
pub id: u16, // identifier
pub qr: bool, // 0 for query, 1 for response
pub opcode: u8, // 0 for standard query
pub aa: bool, // authoritative answer
pub tc: bool, // truncated message
pub rd: bool, // recursion desired
pub ra: bool, // recursion available
pub z: u8, // reserved for future use
pub rcode: u8, // 0 for no error
pub qdcount: u16, // number of entries in the question section
pub ancount: u16, // number of resource records in the answer section
pub nscount: u16, // number of name server resource records in the authority records section
pub arcount: u16, // number of resource records in the additional records section
}
impl Header {
const DNS_HEADER_LEN: usize = 12;
// Serialize the header to a byte array
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(Header::DNS_HEADER_LEN);
buf.extend_from_slice(&self.id.to_be_bytes());
buf.push(
(self.qr as u8) << 7
| self.opcode << 3
| (self.aa as u8) << 2
| (self.tc as u8) << 1
| self.rd as u8,
);
buf.push((self.ra as u8) << 7 | self.z << 4 | self.rcode);
buf.extend_from_slice(&self.qdcount.to_be_bytes());
buf.extend_from_slice(&self.ancount.to_be_bytes());
buf.extend_from_slice(&self.nscount.to_be_bytes());
buf.extend_from_slice(&self.arcount.to_be_bytes());
buf
}
// Deserialize the header from a byte array
pub fn from_bytes(buf: &[u8]) -> Result<Header, ErrorCondition> {
if buf.len() < Header::DNS_HEADER_LEN {
return Err(ErrorCondition::DeserializationErr(
"Buffer length is less than header length".to_string(),
));
}
Ok(Header {
id: u16::from_be_bytes([buf[0], buf[1]]),
qr: (buf[2] & 0b1000_0000) != 0,
opcode: (buf[2] & 0b0111_1000) >> 3,
aa: (buf[2] & 0b0000_0100) != 0,
tc: (buf[2] & 0b0000_0010) != 0,
rd: (buf[2] & 0b0000_0001) != 0,
ra: (buf[3] & 0b1000_0000) != 0,
z: (buf[3] & 0b0111_0000) >> 4,
rcode: buf[3] & 0b0000_1111,
qdcount: u16::from_be_bytes([buf[4], buf[5]]),
ancount: u16::from_be_bytes([buf[6], buf[7]]),
nscount: u16::from_be_bytes([buf[8], buf[9]]),
arcount: u16::from_be_bytes([buf[10], buf[11]]),
})
}
}
#[derive(Debug, Clone)]
pub struct Question {
pub name: Vec<Label>,
pub qtype: Type,
pub qclass: Class,
}
#[derive(Debug, Clone)]
pub struct Label(String);
impl Label {
pub fn new(label: &[u8]) -> Result<Self, ErrorCondition> {
match std::str::from_utf8(label) {
Ok(s) => Ok(Label(s.to_string())),
Err(_) => Err(ErrorCondition::InvalidLabel),
}
}
pub fn len(&self) -> usize {
self.0.len()
}
}
#[derive(Debug, Clone)]
pub enum Type {
// Below are Resource Record Types and QTYPES
A = 1, // a host address
NS = 2, // an authoritative name server
MD = 3, // a mail destination (Obsolete - use MX)
MF = 4, // a mail forwarder (Obsolete - use MX)
CNAME = 5, // the canonical name for an alias
SOA = 6, // marks the start of a zone of authority
MB = 7, // a mailbox domain name (EXPERIMENTAL)
MG = 8, // a mail group member (EXPERIMENTAL)
MR = 9, // a mail rename domain name (EXPERIMENTAL)
NULL = 10, // a null RR (EXPERIMENTAL)
WKS = 11, // a well known service description
PTR = 12, // a domain name pointer
HINFO = 13, // host information
MINFO = 14, // mailbox or mail list information
MX = 15, // mail exchange
TXT = 16, // text strings
// Below are only QTYPES
AXFR = 252, // A request for a transfer of an entire zone
MAILB = 253, // A request for mailbox-related records (MB, MG or MR)
MAILA = 254, // A request for mail agent RRs (Obsolete - see MX)
_ALL_ = 255, // A request for all records
}
#[derive(Debug, Clone)]
pub enum Class {
// Below are Resource Record Classes and QCLASS
IN = 1, // the Internet
CS = 2, // the CSNET class (Obsolete - used only for examples in some obsolete RFCs)
CH = 3, // the CHAOS class
HS = 4, // Hesiod [Dyer 87]
// Below are only QCLASSES
_ALL_ = 255,
}
impl std::fmt::Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let msg: &str = match self {
Type::A => "a host address",
Type::NS => "an authoritative name server",
Type::MD => "a mail destination (Obsolete - use MX)",
Type::MF => "a mail forwarder (Obsolete - use MX)",
Type::CNAME => "the canonical name for an alias",
Type::SOA => "marks the start of a zone of authority",
Type::MB => "a mailbox domain name (EXPERIMENTAL)",
Type::MG => "a mail group member (EXPERIMENTAL)",
Type::MR => "a mail rename domain name (EXPERIMENTAL)",
Type::NULL => "a null RR (EXPERIMENTAL)",
Type::WKS => "a well known service description",
Type::PTR => "a domain name pointer",
Type::HINFO => "host information",
Type::MINFO => "mailbox or mail list information",
Type::MX => "mail exchange",
Type::TXT => "text strings",
Type::AXFR => "A request for a transfer of an entire zone",
Type::MAILB => "A request for mailbox-related records (MB, MG or MR)",
Type::MAILA => "A request for mail agent RRs (Obsolete - see MX)",
Type::_ALL_ => "A request for all records",
};
write!(f, "{}", msg)
}
}
impl Type {
pub fn from_bytes(bytes: &[u8]) -> Result<Type, ErrorCondition> {
match u16::from_be_bytes([bytes[0], bytes[1]]) {
1 => Ok(Type::A),
2 => Ok(Type::NS),
3 => Ok(Type::MD),
4 => Ok(Type::MF),
5 => Ok(Type::CNAME),
6 => Ok(Type::SOA),
7 => Ok(Type::MB),
8 => Ok(Type::MG),
9 => Ok(Type::MR),
10 => Ok(Type::NULL),
11 => Ok(Type::WKS),
12 => Ok(Type::PTR),
13 => Ok(Type::HINFO),
14 => Ok(Type::MINFO),
15 => Ok(Type::MX),
16 => Ok(Type::TXT),
252 => Ok(Type::AXFR),
253 => Ok(Type::MAILB),
254 => Ok(Type::MAILA),
255 => Ok(Type::_ALL_),
n => Err(ErrorCondition::DeserializationErr(
format!("Unknown Question Type {}", n).to_string(),
)),
}
}
pub fn to_bytes(&self) -> [u8; 2] {
let num = match self {
Type::A => 1,
Type::NS => 2,
Type::MD => 3,
Type::MF => 4,
Type::CNAME => 5,
Type::SOA => 6,
Type::MB => 7,
Type::MG => 8,
Type::MR => 9,
Type::NULL => 10,
Type::WKS => 11,
Type::PTR => 12,
Type::HINFO => 13,
Type::MINFO => 14,
Type::MX => 15,
Type::TXT => 16,
Type::AXFR => 252,
Type::MAILB => 253,
Type::MAILA => 254,
Type::_ALL_ => 255,
};
u16::to_be_bytes(num)
}
}
impl Class {
pub fn from_bytes(buf: &[u8]) -> Result<Self, ErrorCondition> {
let num = u16::from_be_bytes([buf[0], buf[1]]);
match num {
1 => Ok(Class::IN),
2 => Ok(Class::CS),
3 => Ok(Class::CH),
4 => Ok(Class::HS),
_ => Err(ErrorCondition::DeserializationErr(
format!("Unknown Question Class {}", num).to_string(),
)),
}
}
pub fn to_bytes(&self) -> [u8; 2] {
let num = match self {
Class::IN => 1,
Class::CS => 2,
Class::CH => 3,
Class::HS => 4,
Class::_ALL_ => 255,
};
u16::to_be_bytes(num)
}
}
impl Question {
// The from_bytes() function reconstructs a Question struct by iterating through the buffer, extracting labels,
// parsing the query type and class.
pub fn from_bytes(buf: &[u8]) -> Result<Self, ErrorCondition> {
let mut index = 0;
let mut labels: Vec<Label> = Vec::new();
println!("Labels:");
while buf[index] != 0 {
let len = buf[index] as usize;
index += 1;
labels.push(Label::new(&buf[index..index + len])?);
println!("{:?}", labels); // For debugging purposes
index += len;
}
index += 1;
let qtype = Type::from_bytes(&buf[index..index + 2])?;
index += 2;
let qclass = Class::from_bytes(&buf[index..index + 2])?;
Ok(Question {
name: labels,
qtype,
qclass,
})
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::new();
// Write the labels to the buffer and add . inbetween and end with 0
for label in &self.name {
buf.push(label.len() as u8);
buf.extend_from_slice(label.0.as_bytes());
}
buf.push(0);
// Write the question type and class to the buffer
buf.extend_from_slice(&self.qtype.to_bytes());
buf.extend_from_slice(&self.qclass.to_bytes());
buf
}
}
#[derive(Debug, Clone)]
pub struct ResourceRecord {
pub name: String,
pub rtype: Type,
pub rclass: Class,
pub ttl: u32,
pub rdlength: u16,
pub rdata: Vec<u8>,
}
impl Default for ResourceRecord {
fn default() -> Self {
ResourceRecord {
name: String::from("www.rust-trends.com"),
rtype: Type::A,
rclass: Class::IN,
ttl: 60,
rdlength: 4,
rdata: Vec::from([172, 67, 221, 148]),
}
}
}
impl ResourceRecord {
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(MAX_DNS_MESSAGE_SIZE);
self.name.split('.').for_each(|label| {
buf.push(label.len() as u8);
buf.extend_from_slice(label.as_bytes());
});
buf.push(0);
buf.extend_from_slice(&self.rtype.to_bytes());
buf.extend_from_slice(&self.rclass.to_bytes());
buf.extend_from_slice(&self.ttl.to_be_bytes());
buf.extend_from_slice(&self.rdlength.to_be_bytes());
buf.extend_from_slice(&self.rdata);
buf
}
}

View File

@@ -0,0 +1,84 @@
// src/main.rs
use std::net::UdpSocket;
mod dns;
use dns::{Header, Question, ResourceRecord};
// Debug print hex bytes of a buffer 16 bytes width followed by the ASCII representation of the bytes
fn debug_print_bytes(buf: &[u8]) {
for (i, chunk) in buf.chunks(16).enumerate() {
print!("{:08x}: ", i * 16);
for byte in chunk {
print!("{:02x} ", byte);
}
for _ in 0..(16 - chunk.len()) {
print!(" ");
}
print!(" ");
for byte in chunk {
if *byte >= 32 && *byte <= 126 {
print!("{}", *byte as char);
} else {
print!(".");
}
}
println!();
}
}
fn main() {
let socket = UdpSocket::bind("0.0.0.0:1053").expect("Could not bind to port 1053");
let mut buf = [0; 512];
println!("DNS server is running at port 1053");
loop {
let (len, addr) = socket.recv_from(&mut buf).expect("Could not receive data");
println!("\nReceived query from {} with length {} bytes", addr, len);
println!("\n### DNS Query: ###");
debug_print_bytes(&buf[..len]);
let header = Header::from_bytes(&buf[..12]).expect("Could not parse DNS header");
println!("\n{:?}", header);
println!("\n### Question: ###");
debug_print_bytes(&buf[12..len]);
println!();
let question = Question::from_bytes(&buf[12..len]).expect("Could not parse DNS question");
println!("\n{:?}", question);
// We parsed the DNS query and question, now we can respond to it
let answer = ResourceRecord::default();
println!("{:?}", answer);
let response_header = Header {
id: header.id,
qr: true, // It is a query response
opcode: header.opcode, // Standard query
aa: false, // Not authoritative
tc: false, // Not truncated
rd: header.rd, // Recursion desired
ra: false, // Recursion not available
z: 0, // Reserved
rcode: if header.opcode == 0 { 0 } else { 4 },
qdcount: 1, // Question count we assume is 1
ancount: 1, // Answer count is 1
nscount: 0, // Name server count is 0
arcount: 0, // Additional record count is 0
};
// Create a response message with the header and question
let mut response: Vec<u8> = Vec::new();
response.extend_from_slice(&response_header.to_bytes());
response.extend_from_slice(&question.to_bytes());
response.extend_from_slice(&answer.to_bytes());
// Send the response back to the client
socket
.send_to(&response, addr)
.expect("Could not send response");
}
}

2908
__network/pingora-demo/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,14 @@
[package]
name = "pingora-demo"
version = "0.1.0"
edition = "2024"
[dependencies]
pingora-core = "0.2"
pingora-proxy = "0.2"
tokio = { version = "1.0", features = ["full"] }
async-trait = "0.1"
mime_guess = "2.0"
headers = "0.3"

View File

@@ -0,0 +1,6 @@
> Copied from: https://mp.weixin.qq.com/s/RHSy2EeK3XTRYXtOSCO0Ug
> https://play.hatter.me/doc/showDocDetail.jssp?id=8495

View File

@@ -0,0 +1,80 @@
use async_trait::async_trait;
use headers::{ContentLength, ContentType};
use pingora_core::server::Server;
use pingora_proxy::{ProxyHttp, Session};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use mime_guess::from_path;
struct StaticFileServer {
root_dir: PathBuf,
}
impl StaticFileServer {
fn new(root: impl AsRef<Path>) -> Self {
StaticFileServer {
root_dir: root.as_ref().to_path_buf(),
}
}
}
#[async_trait]
impl ProxyHttp for StaticFileServer {
async fn response_filter(&self, session: &mut Session, response: &mut pingora_http::Response) {
let path = session.req_header().uri.path();
let file_path = self.root_dir.join(&path[1..]); // 去除前导/
if let Ok(metadata) = tokio::fs::metadata(&file_path).await {
if metadata.is_file() {
if let Ok(file) = tokio::fs::read(&file_path).await {
// 设置正确的Content-Type
let mime = from_path(&file_path).first_or_octet_stream();
response.headers_mut().insert(
headers::CONTENT_TYPE,
ContentType::from(mime).to_string().parse().unwrap(),
);
// 设置Content-Length
response.headers_mut().insert(
headers::CONTENT_LENGTH,
ContentLength(metadata.len()).to_string().parse().unwrap(),
);
// 设置缓存头CDN关键配置
response.headers_mut().insert(
"cache-control",
"public, max-age=31536000".parse().unwrap(), // 1年缓存
);
*response.body_mut() = file.into();
response.set_status(200);
return;
}
}
}
// 文件不存在
*response.status_mut() = 404;
*response.body_mut() = b"Not Found".to_vec().into();
}
}
#[tokio::main]
async fn main() {
// 1. 初始化服务器
let mut server = Server::new(Some("Static File Server")).unwrap();
server.bootstrap();
// 2. 创建文件服务(假设静态文件在./static目录
let static_service = StaticFileServer::new("./static");
let mut service = pingora_proxy::http_proxy_service(&server.configuration, static_service);
// 3. 监听端口
service.add_tcp("0.0.0.0:8080");
// 4. 启动服务
server.add_service(service);
println!("Static file server running on :8080");
server.run_forever();
}

339
__network/tcp-connect-reset/Cargo.lock generated Normal file
View File

@@ -0,0 +1,339 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "addr2line"
version = "0.24.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1"
dependencies = [
"gimli",
]
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "autocfg"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "backtrace"
version = "0.3.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002"
dependencies = [
"addr2line",
"cfg-if",
"libc",
"miniz_oxide",
"object",
"rustc-demangle",
"windows-targets",
]
[[package]]
name = "bitflags"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
[[package]]
name = "bytes"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
[[package]]
name = "cfg-if"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
[[package]]
name = "gimli"
version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
[[package]]
name = "libc"
version = "0.2.173"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8cfeafaffdbc32176b64fb251369d52ea9f0a8fbc6f8759edffef7b525d64bb"
[[package]]
name = "lock_api"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "memchr"
version = "2.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
]
[[package]]
name = "mio"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd"
dependencies = [
"libc",
"wasi",
"windows-sys",
]
[[package]]
name = "object"
version = "0.36.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87"
dependencies = [
"memchr",
]
[[package]]
name = "parking_lot"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-targets",
]
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.5.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928fca9cf2aa042393a8325b9ead81d2f0df4cb12e1e24cef072922ccd99c5af"
dependencies = [
"bitflags",
]
[[package]]
name = "rustc-demangle"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "signal-hook-registry"
version = "1.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410"
dependencies = [
"libc",
]
[[package]]
name = "smallvec"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8917285742e9f3e1683f0a9c4e6b57960b7314d0b08d30d1ecd426713ee2eee9"
[[package]]
name = "socket2"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f5fd57c80058a56cf5c777ab8a126398ece8e442983605d280a44ce79d0edef"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "syn"
version = "2.0.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tcp-connect-reset"
version = "0.1.0"
dependencies = [
"tokio",
]
[[package]]
name = "tokio"
version = "1.45.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75ef51a33ef1da925cea3e4eb122833cb377c61439ca401b770f54902b806779"
dependencies = [
"backtrace",
"bytes",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

View File

@@ -0,0 +1,7 @@
[package]
name = "tcp-connect-reset"
version = "0.1.0"
edition = "2024"
[dependencies]
tokio = { version = "1.45.1", features = ["full"] }

View File

@@ -0,0 +1,30 @@
use std::net::SocketAddr;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpSocket;
#[tokio::main]
async fn main() {
let addr: SocketAddr = "127.0.0.1".parse().unwrap();
let _ = connect_and_reset(addr).await;
}
async fn connect_and_reset(addr: SocketAddr) -> Result<(), String> {
let socket = match TcpSocket::new_v4() {
Ok(s) => s,
Err(e) => return Err(e.to_string()),
};
let mut stream = match socket.connect(addr).await {
Ok(s) => s,
Err(e) => return Err(e.to_string()),
};
if let Err(e) = stream
.write_all(b"GET /test HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n")
.await
{
return Err(e.to_string());
}
// cause reset
stream.set_linger(Some(Duration::from_millis(0))).ok();
Ok(())
}

108
__security/keyring-demo/Cargo.lock generated Normal file
View File

@@ -0,0 +1,108 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bitflags"
version = "2.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394"
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "keyring"
version = "3.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
dependencies = [
"log",
"security-framework 2.11.1",
"security-framework 3.4.0",
"zeroize",
]
[[package]]
name = "keyring-demo"
version = "0.1.0"
dependencies = [
"keyring",
]
[[package]]
name = "libc"
version = "0.2.175"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543"
[[package]]
name = "log"
version = "0.4.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
[[package]]
name = "security-framework"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
dependencies = [
"bitflags",
"core-foundation 0.9.4",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b369d18893388b345804dc0007963c99b7d665ae71d275812d828c6f089640"
dependencies = [
"bitflags",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "zeroize"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"

View File

@@ -0,0 +1,7 @@
[package]
name = "keyring-demo"
version = "0.1.0"
edition = "2024"
[dependencies]
keyring = { version = "3.6.3", features = ["apple-native"] }

View File

@@ -0,0 +1,10 @@
use keyring::{Entry, Result};
fn main() -> Result<()> {
let entry = Entry::new("my-service", "my-name")?;
entry.set_password("topS3cr3tP4$$w0rd")?;
let password = entry.get_password()?;
println!("My password is '{}'", password);
entry.delete_credential()?;
Ok(())
}

View File

@@ -1,171 +1,349 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4
[[package]]
name = "android-tzdata"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "autocfg" name = "autocfg"
version = "1.0.0" version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "bumpalo"
version = "3.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"
[[package]]
name = "cc"
version = "1.2.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3a42d84bb6b69d3a8b3eaacf0d88f179e1929695e1ad012b6cf64d9caaa5fd2"
dependencies = [
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.10" version = "0.4.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d"
dependencies = [ dependencies = [
"num-integer 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", "android-tzdata",
"num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "iana-time-zone",
"time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", "js-sys",
"num-traits",
"wasm-bindgen",
"windows-link",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "iana-time-zone"
version = "0.1.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c919e5debc312ad217002b8048a17b7d83f80703865bbfcfebb0458b0b27d8"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
] ]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "0.4.4" version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
[[package]]
name = "js-sys"
version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f"
dependencies = [
"once_cell",
"wasm-bindgen",
]
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.66" version = "0.2.174"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
[[package]] [[package]]
name = "num-integer" name = "log"
version = "0.1.42" version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [ checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
"autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", [[package]]
] name = "memchr"
version = "2.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.11" version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [ dependencies = [
"autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "autocfg",
] ]
[[package]] [[package]]
name = "proc-macro2" name = "once_cell"
version = "1.0.8" version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [ dependencies = [
"unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-ident",
] ]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.2" version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [ dependencies = [
"proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2",
] ]
[[package]] [[package]]
name = "redox_syscall" name = "rustversion"
version = "0.1.56" version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a0d197bd2c9dc6e53b84da9556a69ba4cdfab8619eb41a8bd1cc2027a0f6b1d"
[[package]] [[package]]
name = "ryu" name = "ryu"
version = "1.0.2" version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.104" version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
dependencies = [ dependencies = [
"serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive",
] ]
[[package]] [[package]]
name = "serde-json-test" name = "serde-json-test"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"chrono 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", "chrono",
"serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", "serde",
"serde_json 1.0.44 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.104" version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
dependencies = [ dependencies = [
"proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2",
"quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "quote",
"syn 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", "syn",
] ]
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.44" version = "1.0.142"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "030fedb782600dcbd6f02d479bf0d817ac3bb40d644745b769d6a96bc3afc5a7"
dependencies = [ dependencies = [
"itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", "itoa",
"ryu 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "memchr",
"serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", "ryu",
"serde",
] ]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.13" version = "2.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
dependencies = [ dependencies = [
"proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2",
"quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "quote",
"unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-ident",
] ]
[[package]] [[package]]
name = "time" name = "unicode-ident"
version = "0.1.42" version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "wasm-bindgen"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
dependencies = [ dependencies = [
"libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", "cfg-if",
"redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", "once_cell",
"winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", "rustversion",
"wasm-bindgen-macro",
] ]
[[package]] [[package]]
name = "unicode-xid" name = "wasm-bindgen-backend"
version = "0.2.0" version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "winapi"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6"
dependencies = [ dependencies = [
"winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "bumpalo",
"winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "log",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
] ]
[[package]] [[package]]
name = "winapi-i686-pc-windows-gnu" name = "wasm-bindgen-macro"
version = "0.4.0" version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]] [[package]]
name = "winapi-x86_64-pc-windows-gnu" name = "wasm-bindgen-macro-support"
version = "0.4.0" version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[metadata] [[package]]
"checksum autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" name = "wasm-bindgen-shared"
"checksum chrono 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)" = "31850b4a4d6bae316f7a09e691c944c28299298837edc0a03f755618c23cbc01" version = "0.2.100"
"checksum itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "501266b7edd0174f8530248f87f99c88fbe60ca4ef3dd486835b8d8d53136f7f" source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d"
"checksum num-integer 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "3f6ea62e9d81a77cd3ee9a2a5b9b609447857f3d358704331e4ef39eb247fcba" dependencies = [
"checksum num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" "unicode-ident",
"checksum proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548" ]
"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe"
"checksum redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)" = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" [[package]]
"checksum ryu 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "bfa8506c1de11c9c4e4c38863ccbe02a305c8188e85a05a784c9e11e1c3910c8" name = "windows-core"
"checksum serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" version = "0.61.2"
"checksum serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "128f9e303a5a29922045a830221b8f78ec74a5f544944f3d5984f8ec3895ef64" source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum serde_json 1.0.44 (registry+https://github.com/rust-lang/crates.io-index)" = "48c575e0cc52bdd09b47f330f646cf59afc586e9c4e3ccd6fc1f625b8ea1dad7" checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
"checksum syn 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)" = "1e4ff033220a41d1a57d8125eab57bf5263783dfdcc18688b1dacc6ce9651ef8" dependencies = [
"checksum time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f" "windows-implement",
"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" "windows-interface",
"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" "windows-link",
"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" "windows-result",
"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" "windows-strings",
]
[[package]]
name = "windows-implement"
version = "0.60.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-interface"
version = "0.59.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-link"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
[[package]]
name = "windows-result"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
dependencies = [
"windows-link",
]

View File

@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Result, Value}; use serde_json::{Result, Value};
use chrono::{DateTime, Utc, TimeZone}; use chrono::{DateTime, Utc, TimeZone};
// alternative JSON for human: https://crates.io/crates/json5
mod my_date_format { mod my_date_format {
use chrono::{DateTime, Utc, TimeZone}; use chrono::{DateTime, Utc, TimeZone};
use serde::{self, Deserialize, Serializer, Deserializer}; use serde::{self, Deserialize, Serializer, Deserializer};
@@ -50,6 +51,20 @@ struct TestStruct {
struct TestStruct2 { struct TestStruct2 {
test_id: i32, test_id: i32,
test_name: String, test_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
test_description: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum StringOrStringArray {
String(String),
Vec(Vec<String>),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct TestStruct3 {
sub: StringOrStringArray,
} }
fn main() -> Result<()> { fn main() -> Result<()> {
@@ -82,7 +97,7 @@ fn main() -> Result<()> {
}); });
println!("{}", &john); println!("{}", &john);
if let Option::Some(ref mut m) = john.as_object_mut() { if let Some(ref mut m) = john.as_object_mut() {
m.insert("test".into(), Value::Bool(true)); m.insert("test".into(), Value::Bool(true));
m.insert("test2".into(), Value::String("hello world".into())); m.insert("test2".into(), Value::String("hello world".into()));
} }
@@ -91,8 +106,15 @@ fn main() -> Result<()> {
let test_struct2 = TestStruct2 { let test_struct2 = TestStruct2 {
test_id: 1, test_id: 1,
test_name: "Hatter".into(), test_name: "Hatter".into(),
test_description: None,
}; };
println!("{}", serde_json::to_string(&test_struct2)?); println!("{}", serde_json::to_string(&test_struct2)?);
println!();
let test_struct3_1: TestStruct3 = serde_json::from_str("{\"sub\": \"name\"}")?;
println!("{}", serde_json::to_string_pretty(&test_struct3_1)?);
let test_struct3_2: TestStruct3 = serde_json::from_str("{\"sub\": [\"name1\", \"name2\"]}")?;
println!("{}", serde_json::to_string_pretty(&test_struct3_2)?);
Ok(()) Ok(())
} }

92
__term/tui-markup-demo/Cargo.lock generated Normal file
View File

@@ -0,0 +1,92 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "ansi_term"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
dependencies = [
"winapi",
]
[[package]]
name = "bytecount"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"
[[package]]
name = "memchr"
version = "2.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "nom_locate"
version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e3c83c053b0713da60c5b8de47fe8e494fe3ece5267b2f23090a07a053ba8f3"
dependencies = [
"bytecount",
"memchr",
"nom",
]
[[package]]
name = "tui-markup"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5437c754f57a2aa554adc76c607d45c4a1a8a3f86f7e261811b361872eec0b69"
dependencies = [
"ansi_term",
"nom",
"nom_locate",
]
[[package]]
name = "tui-markup-demo"
version = "0.1.0"
dependencies = [
"ansi_term",
"tui-markup",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

View File

@@ -0,0 +1,8 @@
[package]
name = "tui-markup-demo"
version = "0.1.0"
edition = "2024"
[dependencies]
ansi_term = "0.12.1"
tui-markup = { version = "0.5.0",features = ["ansi"] }

View File

@@ -0,0 +1,20 @@
use ansi_term::{ANSIStrings, Color, Style};
use tui_markup::generator::ANSIStringsGenerator;
use tui_markup::{compile, compile_with};
fn main() {
// Parse markup into some final result for showing
let result = compile::<ANSIStringsGenerator>("You got a <yellow Coin>").unwrap();
// Show it
println!("{}", ANSIStrings(&result));
// With custom tag
let generator = ANSIStringsGenerator::new(|tag: &str| match tag {
"keyboard" => Some(Style::default().fg(Color::Blue).on(Color::Black).bold()),
"bold" => Some(Style::default().bold()),
"under" => Some(Style::default().underline()),
_ => None,
});
let result = compile_with("Press <keyboard Space> to <bold <under jump>>", generator).unwrap();
println!("{}", ANSIStrings(&result));
}

View File

@@ -0,0 +1,3 @@
target/
work/
.cargo/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
[workspace]
resolver = "3"
members = ["host", "plugin"]
# This will create smaller Wasm files
[profile.release]
strip = "debuginfo"
lto = true

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,19 @@
Copyright (c) Individual contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,72 @@
Rust Wasm Plugins Example
=========================
> clone from: https://github.com/tliron/rust-wasm-plugins-examples
A Great Fit
-----------
You've probably heard that [Wasm](https://web.dev/explore/webassembly) (WebAssembly) can be a great way to support plugins in your application. Plugin authors can write them in any Wasm-compatible language and you're off to the races with your choice among various excellent and safe Wasm runtimes for Rust, including ones optimized for embedded environments (e.g. [wasmi](https://github.com/wasmi-labs/wasmi)).
Not So Easy
-----------
Unfortunately, you're going to find out (in early 2025, when this is written) that examples of this often-mentioned use case are hard to come by, and that so much of the documentation is irrelevant, confusing, incomplete, or just out of date, as things have been moving quite quickly in the Wasm world.
If you've read Surma's [Rust to WebAssembly the hard way](https://surma.dev/things/rust-to-webassembly/) (highly recommended starting point!) then you might feel quite confident in your ability to build `.wasm` modules, load them into Rust, call functions in them, and expose functions to them. But the hard way becomes a dead end as you realize something quite critical: Wasm only supports the transfer of just primitive numeric types, namely integers and floats (and not even unsigned integers). This is an intentional and understandable design choice to keep Wasm lean and mean and agnostic to any specific implementation.
But this means that if you want to transfer something as basic as a string or a vector then you'll have to delve deep into the the Wasm memory model.
People have come up with various solutions for Rust, from piggy-backing on [std::ffi::CString](https://doc.rust-lang.org/std/ffi/struct.CString.html) to exposing custom malloc/free functions to the Wasm module. But not only are these solutions painful, they would obviously need to be ported to every language we want to support, each with its own string and array models. There was, and still is, a need for some kind of standard, built on top of Wasm, that would support higher-level constructs in a portable way.
The Temporary Solutions
-----------------------
It took some time for the community to rally around one. For a while, a promising proposal was Wasm Interfaces (WAI). This was [pioneered by Wasmer](https://github.com/wasmerio/wai), where the [documentation](https://docs.wasmer.io/wai) still points to it as "the" solution (early 2025). As usual in the Wasm world, even that documentation can only take you so far. None of it actually mentions hosting WAI in Rust! And it only shows importing interfaces, not exporting them, though I have managed to learn how to handle exports by delving into the WAI tooling source code. The idea behind
WAI is that you describe your interface in a [`.wai` file](https://github.com/wasmerio/wai/blob/main/WAI.md) and use tooling (e.g. macros) to generate the boilerplate code for clients and hosts, a lot like how things work with RPC protocols (e.g. protobufs).
WAI had not been widely adopted, however it does work and is also quite straightforward. We won't be using it in this example, but it's useful to be aware of its existence.
Also check out [Extism](https://extism.org/), a more comprehensive attempt to fill in the gap.
The Consensus Solution
----------------------
But the consensus now seems to be around the [Wasm Component Model](https://component-model.bytecodealliance.org/), which expands on the WAI proposal with proper namespacing, resources, and richer custom data types. The Component Model is actually part of WASI, and indeed is being used to provide the WASI extensions. So, what's [WASI](https://wasi.dev/)? It's an initiative by the community to deliver a set of common APIs on top of Wasm for accessing streams, like files and stdout/stderr, network sockets, and eventually threads. I say "eventually" because WASI is still very much a work in progress. As of now (early 2025) we just got "preview 2" of it. Luckily, Rust can target "wasip2", meaning that it can be used to create the latest and greatest Components. Though, note that wasip2 does produce larger minimal `.wasm` files than WAI due to the inclusion of the machinery for the Component Model.
Like WAI, the Component Model relies on an interface definition file, [`.wit`](https://component-model.bytecodealliance.org/design/wit.html). And [Wasmtime](https://wasmtime.dev/) has the tooling for it! Yay! So, are we finally off to the races with our plugin system?
Not so fast. Again, finding examples and straightforward documentation is not easy. Wasmtime is a very comprehensive and performative implementation, but it's also designed by committee and has a lot of contributors. And due to the fast-moving nature of these things, what you find might not represent what is actually going on or what you should be using.
Finally We Get to the Point
---------------------------
All that to say, that's why I created this repository. It's intended to be a minimal and straightforward example of how to build plugins in Rust (as Components) and how to host them in your application using Wasmtime and its WIT tooling. Well, at least for early 2025... As of now it does not demonstrate the more advanced features of WIT, such as custom data types, but I might add those in the future.
How to Build and Run
--------------------
There are two crates here, a plugin, which builds into a wasip2 `.wasm`, and a host, which can be built into any Rust target architecure.
```sh
rustup target add wasm32-wasip2
git clone https://github.com/tliron/rust-wasm-plugins-examples.git
cd rust-wasm-plugins-examples
./run.sh
```
Things to See
-------------
* [Rust to WebAssembly the hard way](https://surma.dev/things/rust-to-webassembly/) by Surma
* [Plugins with Rust and WASI Preview 2](https://benw.is/posts/plugins-with-rust-and-wasi) by Ben Wishovich
License
-------
Like much of the Rust ecosystem, licensed under your choice of either of
* [Apache License, Version 2.0](LICENSE-APACHE)
* [MIT license](LICENSE-MIT)
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

View File

@@ -0,0 +1,26 @@
// Note that names *cannot* use underscores, but *can* use dashes
// (In Rust the dashes are converted to underscores, as usual)
// They also can't use numeric digits for some reason!
// A package can include more than one "world"
// (=component, or plugin type for us),
package acme:plugins@1.0.0;
// This is what the host will expose to our plugins
interface host {
log: func(message: string);
}
// This is what our plugins will expose to the host
interface prettify-plugin {
prettify: func(content: string) -> string;
}
// We can create additional worlds per plugin type
// You can import/export more than one interface
// (as well as individual functions, types, and resources)
world prettify {
import host;
export prettify-plugin;
}

View File

@@ -0,0 +1,22 @@
[package]
edition = "2021"
name = "host"
description = "Rust Wasm Plugins Example"
version = "0.0.1"
rust-version = "1.84"
license = "MIT OR Apache-2.0"
repository = "https://github.com/tliron/rust-wasm-plugins-example"
documentation = "https://github.com/tliron/rust-wasm-plugins-example"
authors = ["Tal Liron"]
readme = "../README.md"
categories = ["wasm"] # https://crates.io/category_slugs
keywords = ["wasm", "wasi", "wit", "wasmtime", "examples"]
[dependencies]
anyhow = "1.0.97"
wasmtime = "31.0.0"
wasmtime-wasi = "31.0.0"

View File

@@ -0,0 +1,3 @@
#![allow(missing_docs)]
wasmtime::component::bindgen!(in "../assets/wit/acme-plugins.wit");

View File

@@ -0,0 +1,41 @@
use super::bindings::acme::plugins::host;
use wasmtime_wasi::{IoView, ResourceTable, WasiCtx, WasiCtxBuilder, WasiView};
//
// Host
//
/// Plugins host.
pub struct Host {
wasi: WasiCtx,
resources: ResourceTable,
}
impl Host {
/// Constructor.
pub fn new() -> Self {
let wasi = WasiCtxBuilder::new().inherit_stdout().build();
Self { wasi, resources: ResourceTable::new() }
}
}
// We need to implement WasiView for wasmtime_wasi::add_to_linker_sync
impl WasiView for Host {
fn ctx(&mut self) -> &mut WasiCtx {
&mut self.wasi
}
}
impl IoView for Host {
fn table(&mut self) -> &mut ResourceTable {
&mut self.resources
}
}
// Our exposed Host functions
impl host::Host for Host {
fn log(&mut self, message: String) {
println!("log: {}", message);
}
}

View File

@@ -0,0 +1,11 @@
mod bindings;
mod host;
mod prettify;
use prettify::*;
pub fn main() {
let mut prettify = Prettify::new("target/wasm32-wasip2/release/plugin.wasm").unwrap();
let r = prettify.prettify("We will prettify this with a plugin").unwrap();
println!("{}", r);
}

View File

@@ -0,0 +1,55 @@
use super::{bindings, host::*};
use {
anyhow::Context,
std::path,
wasmtime::{component::*, Engine, Store},
};
//
// Prettify
//
/// Prettify plugin.
pub struct Prettify {
store: Store<Host>,
prettify: bindings::Prettify,
}
// Wasmtime uses Anyhow for most of its errors
// But you could potentially wrap it in your own "PluginError" or similar using .map_err
// For this example we used .context
impl Prettify {
/// Constructor.
pub fn new<PathT>(module: PathT) -> Result<Self, anyhow::Error>
where
PathT: AsRef<path::Path>,
{
let engine = Engine::default();
// Component
let component = Component::from_file(&engine, module).context("load component")?;
// Linker
let mut linker = Linker::new(&engine);
wasmtime_wasi::add_to_linker_sync(&mut linker).context("link WASI")?;
bindings::Prettify::add_to_linker(&mut linker, |state: &mut Host| state).context("link plugin host")?;
// Store
let mut store = Store::new(&engine, Host::new());
// Bindings
let prettify =
bindings::Prettify::instantiate(&mut store, &component, &linker).context("instantiate bindings")?;
Ok(Self { store, prettify })
}
// We'll create convenience wrappers to make calling functions ergonomic:
/// Prettify.
pub fn prettify(&mut self, name: &str) -> Result<String, anyhow::Error> {
self.prettify.acme_plugins_prettify_plugin().call_prettify(&mut self.store, name)
}
}

View File

@@ -0,0 +1,23 @@
[package]
edition = "2021"
name = "plugin"
description = "Rust Wasm Plugins Example"
version = "0.0.1"
rust-version = "1.84"
license = "MIT OR Apache-2.0"
repository = "https://github.com/tliron/rust-wasm-plugins-example"
documentation = "https://github.com/tliron/rust-wasm-plugins-example"
authors = ["Tal Liron"]
readme = "../README.md"
categories = ["wasm"]
keywords = ["wasm", "wasi", "wit", "wasmtime", "examples"]
[dependencies]
wit-bindgen = "0.41.0"
[lib]
crate-type = ["cdylib"]

View File

@@ -0,0 +1,8 @@
// Note that we are using the full notation of the macro in order
// to add some options that allow the bindings to live in this independent file
wit_bindgen::generate!({
path: "../assets/wit/acme-plugins.wit",
default_bindings_module: "crate::bindings",
pub_export_macro: true,
});

View File

@@ -0,0 +1,2 @@
mod bindings;
mod quote_prettify;

View File

@@ -0,0 +1,21 @@
use super::bindings::{acme::plugins::host, export, exports::acme::plugins::prettify_plugin};
// This is our implementation of the "prettify" plugin type
// (=WIT world)
// We shall make the content pretty by quoting all words
// Gorgeous!
pub struct QuotePrettifyPlugin;
export!(QuotePrettifyPlugin);
impl prettify_plugin::Guest for QuotePrettifyPlugin {
fn prettify(content: String) -> String {
host::log("thank you for using the quote prettify plugin!");
let words = content.split(" ");
let words: Vec<String> = words.map(|word| format!("{:?}", word)).collect();
words.join(" ")
}
}

View File

@@ -0,0 +1,4 @@
#!/bin/bash
cargo build --package=plugin --target=wasm32-wasip2 --release
cargo run --package=host

View File

@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"

View File

@@ -35,3 +35,6 @@ fn main() -> XResult<()> {
opt_result!(fs::write("README.md", readme), "Write README.md failed: {}"); opt_result!(fs::write("README.md", readme), "Write README.md failed: {}");
Ok(()) Ok(())
} }
// @SCRIPT-SIGNATURE-V1: yk-r1.ES256.20250308T212308+08:00.MEQCIBblLBxZYIuyjfsrCbQo
// oGiiiUGtdmjOo0p1s9DfPewYAiBZfpz6Nj737qGfejAPmnO03+NGuR0wc51NqXcer2WxKA==